@iamjoeker/swaggerize-routes v2.0.1
swaggerize-routes (formerly swaggerize-builder)
swaggerize-routes is a component used by swaggerize-express and swaggerize-hapi for parsing and building route definitions based on a Swagger 2.0 document.
swaggerize-routes provides the following features:
- Schema validation.
- Building route definitions from a Swagger 2.0 document.
- Validation helpers for input parameters.
- Validation helpers for response.
Usage
const builder = require('swaggerize-routes');
const routeBuilder = builder({
    api: require('./api.json'),
    handlers: './handlers',
    security: './security' //Optional - security authorize handlers as per `securityDefinitions`
});
//Promise Style
routeBuilder.then(routeObj => {
    let { api, routes } = routeObj;
    // `api` is the resolved swagger api Object ($ref, both remote and local references are resolved)
    // `routes` - an array of routes corresponding to the swagger api `paths`.
}).catch(error => Assert.ifError(error));
//OR
// Callback style
builder({
    api: 'http://petstore.swagger.io/v2/swagger.json',
    handlers: './handlers',
    security: './security', //Optional - security authorize handlers as per `securityDefinitions`
    joischema: true //Set to true if `joischema` need to be used for validators.
}, (error, routes) => {
    Assert.ifError(error);
    let { api, routes } = routeObj;
    // `api` is the resolved swagger api Object ($ref and remote and local ref are resolved)
    // `routes` - an array of routes corresponding to the swagger api `paths`.
});API
builder(options, [cb])
- options- (Object) - (required) - Options to build the routes based on swagger api.- api- (Object) or (String) or (Promise) - (required) - api can be one of the following.- A relative or absolute path to the Swagger api document.
- A URL of the Swagger api document.
- The swagger api Object
- A promise (or a thenable) that resolves to the swagger api Object.
 
- handlers- (Object) or (String) - (required) - either a directory structure for route handlers or a pre-created object (see Handlers Object below). If- handlersoption is not provided, route builder will try to use the default- handlersdirectory (only if it exists). If there is no- handlersdirectory available, then the route builder will try to use the- x-handlerswagger schema extension.
- basedir- (String) - (optional) - base directory to search for- handlerspath (defaults to- dirnameof caller).
- security- (String) - (optional) - directory to scan for authorize handlers corresponding to- securityDefinitions.
- validated- (Boolean) - (optional) - Set this property to- trueif the api is already validated against swagger schema and already dereferenced all the- $ref. This is really useful to generate validators for parsed api specs. Default value for this is- falseand the api will be validated using swagger-parser validate.
- joischema- (Boolean) - (optional) - Set to- trueif you want to use Joi schema based Validators. Swagvali uses enjoi - The json to joi schema converter - to build the validator functions, if- joischemaoption is set to- true.
 
- callback- (Function) - (optional) -- function (error, mock). If a callback is not provided a- Promisewill be returned.
Handlers Directory
The options.handlers option specifies a directory to scan for handlers. These handlers are bound to the api paths defined in the swagger document.
handlers
  |--foo
  |    |--bar.js
  |--foo.js
  |--baz.jsWill route as:
foo.js => /foo
foo/bar.js => /foo/bar
baz.js => /bazPath Parameters
The file and directory names in the handlers directory can also represent path parameters.
For example, to represent the path /users/{id}:
handlers
  |--users
  |    |--{id}.jsThis works with directory names as well:
handlers
  |--users
  |    |--{id}.js
  |    |--{id}
  |        |--foo.jsTo represent /users/{id}/foo.
Schema Extensions for Handlers
An alternative to automatically determining handlers based on a directory structure, handlers can be specified for both paths and/or operations.
Example:
{
    "/pets": {
        "x-handler": "handlers/pets.js"
    }
}Or at the operation level:
{
    "/pets": {
        "GET": {
            "x-handler": "handlers/pets.js"
        }
    }
}These paths are relative to the options.basedir and are used as fallbacks for missing handlers from directory scan.
If the options.handlers and options.defaulthandler is empty, then they will be used exclusively.
Handlers File
Each provided javascript file should export an object containing functions with HTTP verbs as keys.
Example:
module.exports = {
    get: function (...) { ... },
    put: function (...) { ... },
    ...
}Where the function signature is a handler for the target framework (e.g. express or hapi).
Handlers specified by x-handler can also be of the form:
module.exports = function (...) {
    ...
};In the case where a different x-handler file is specified for each operation.
Handlers Object
The directory generation will yield this object, but it can be provided directly as options.handlers.
Note that if you are programmatically constructing a handlers obj this way, you must namespace HTTP verbs with $ to
avoid conflicts with path names. These keys should also be lowercase.
Example:
{
    'foo': {
        '$get': function (...) { ... },
        'bar': {
            '$get': function (...) { ... },
            '$post': function (...) { ... }
        }
    }
    ...
}Handler keys in files do not have to be namespaced in this way.
Route Object response
The response route object has two properties - api and routes.
api is the resolved swagger api object. This has all the resolved $ref values - both local and remote references.
The routes array returned from the call to the builder will contain route objects. Each route has the following properties:
- path- same as- pathfrom- apidefinition.
- name- same as- operationIdin- apidefinition.
- description- same as- descriptionin- pathfor- apidefinition.
- method- same as- methodfrom- api- operationdefinition.
- security- the security definition for this route, either pulled from the operation level or path level.
- validators- an array of validation objects created from each- parameteron the- operation.
- handler- a handler function appropriate to the target framework (e.g express).
- consumes- same as- consumesin- apidefinition.
- produces- same as- producesin- apidefinition.
Validator Object
The validator object in the validators array will have the following properties:
- validate(value, callback)- a function for validating the input data against the- parameterdefinition.
- spec- The schema of the parameter.
- joischema- The- joischema being validated against. This will be available only for the validators with option- joischemaset as- true. By default the validator uses- is-my-json-validJSON schema validator and- joischemaproperty in validator object will be- undefined.
Security directory
The options.security option specifies a directory to scan for security authorize handlers. These authorize handlers are bound to the api securityDefinitions defined in the swagger document.
The name of the securityDefinitions should match the file name of the authorize handler.
For example, for the security definition :
"securityDefinitions": {
    "default": {
        "type": "oauth2",
        "scopes": {
            "read": "read pets.",
            "write": "write pets."
        }
    },
    "secondary": {
        "type": "oauth2",
        "scopes": {
            "read": "read secondary pets.",
            "write": "write secondary pets."
        }
    }
}The options.security, say security directory should have following files:
├── security
   ├── default.js
   ├── secondary.jsSchema Extension for security authorize handler
An alternative approach to options.security option, is use swagger schema extension (^x-) and define x-authorize as part of the securityDefinitions.
"securityDefinitions": {
    "default": {
        "type": "oauth2",
        "scopes": {
            "read": "read pets.",
            "write": "write pets."
        },
        "x-authorize": "security/default_authorize.js"
    },
    "secondary": {
        "type": "oauth2",
        "scopes": {
            "read": "read secondary pets.",
            "write": "write secondary pets."
        },
        "x-authorize": "security/secondary_authorize.js"
    }
}x-authorize will override any resolved authorize handlers defined by options.security.
Security Object
The security object in the route is an object containing keys corresponding to names found under the Swagger Security Definitions.
Under each key will be an object containing the following properties:
- scopes- an array of scopes accepted for this route.
- authorize- a function scanned from the authorize handlers defined by the- options.securitydirectory. Or this may be provided by defining a- x-authorizeattribute to the security definition.