koas-oauth2-server v0.1.11
Koas
Koa + Open API Specification = Koas
Koas aims to make it easy to write a RESTful API based on Koa and an Open API V3 Specification. Koas is a middleware for Koa which implements the Open API V3 specification based on a plugin system.
Note: This is still unstable. Any breaking changes may be introduced until version 1.0.0 stable is released.
Installation
To install Koas along with all official plugins, run the following command:
koa koas-body-parser koas-core koas-operations koas-parameters koas-security koas-serializer koas-spec-handler koas-status-code koas-swagger-ui
Usage
The simplest way to use Koas, is to pull in this boilerplate:
const Koa = require('koa');
const koasBodyParser = require('koas-body-parser');
const koas = require('koas-core');
const koasOperations = require('koas-operations');
const koasParameters = require('koas-parameters');
const koasSecurity = require('koas-security');
const koasSerializer = require('koas-serializer');
const koasSpecHandler = require('koas-spec-handler');
const koasStatusCode = require('koas-status-code');
const koasSwaggerUI = require('koas-swagger-ui');
const api = require('./api.json');
const operations = require('./operations');
const securityChecks = require('./securityChecks');
async function main() {
const app = new Koa();
app.use(
await koas(api, [
// Serve the Open API spec
koasSpecHandler(),
// Serve Swagger-UI
koasSwaggerUI(),
// Verify authentication based on security requirements
koasSecurity(securityChecks),
// Automatically set the success status code
koasStatusCode(),
// Serialize the response body
koasSerializer(),
// Parse path and query parameters
koasParameters(),
// Process the request body
koasBodyParser(),
// Run business logic
koasOperations({ operations }),
]),
);
app.listen(3333);
}
Plugins
Koas only does a little work. The real functionality happens in plugins.
Mono Repository Plugins
The Koas mono repository contains the following plugins:
koas-body-parser
koas-operations
koas-parameters
koas-security
koas-serializer
koas-spec-handler
koas-status-code
koas-swagger-ui
Creating Plugins
It is also possible to create your own plugins. A Koas plugin is simply a function which returns Koa middleware. It is recommended to create a function that returns a Koas plugin. This allows users to pass options to the plugin.
Koas provides TypeScript typings. All that’s needed to get typings for the entire plugin is a
koas.Plugin
return type. It is recommended to expose plugins using a namespace.
import * as koas from 'koas-core';
function myPlugin(options: myPlugin.Options): koas.Plugin {
return ({ rawSpec, runAlways, spec, validate }) => async (ctx, next) => {
await next();
};
}
export = myPlugin;
namespace myPlugin {
export interface MyPluginOptions {}
}