• Stars
    star
    354
  • Rank 115,772 (Top 3 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 10 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Design-driven apis with swagger 2.0 and express.

swaggerize-express

Build Status
NPM version

swaggerize-express is a design-driven approach to building RESTful apis with Swagger and Express.

swaggerize-express provides the following features:

  • API schema validation.
  • Routes based on the Swagger document.
  • API documentation route.
  • Input validation.

See also:

Why "Design Driven"

There are already a number of modules that help build RESTful APIs for node with swagger. However, these modules tend to focus on building the documentation or specification as a side effect of writing the application business logic.

swaggerize-express begins with the swagger document first. This facilitates writing APIs that are easier to design, review, and test.

Quick Start with a Generator

This guide will let you go from an api.json to a service project in no time flat.

First install generator-swaggerize (and yo if you haven't already):

$ npm install -g yo
$ npm install -g generator-swaggerize

Now run the generator.

$ mkdir petstore && cd $_
$ yo swaggerize

Follow the prompts (note: make sure to choose express as your framework choice).

When asked for a swagger document, you can try this one:

https://raw.githubusercontent.com/wordnik/swagger-spec/master/examples/v2.0/json/petstore.json

You now have a working api and can use something like Swagger UI to explore it.

Manual Usage

var swaggerize = require('swaggerize-express');

app.use(swaggerize({
    api: require('./api.json'),
    docspath: '/api-docs',
    handlers: './handlers'
}));

Options:

  • api - a valid Swagger 2.0 document.
  • docspath - the path to expose api docs for swagger-ui, etc. Defaults to /.
  • handlers - either a directory structure for route handlers or a premade object (see Handlers Object below).
  • express - express settings overrides.

After using this middleware, a new property will be available on the app called swagger, containing the following properties:

  • api - the api document.
  • routes - the route definitions based on the api document.

Example:

var http = require('http');
var express = require('express');
var swaggerize = require('swaggerize-express');

app = express();

var server = http.createServer(app);

app.use(swaggerize({
    api: require('./api.json'),
    docspath: '/api-docs',
    handlers: './handlers'
}));

server.listen(port, 'localhost', function () {
    app.swagger.api.host = server.address().address + ':' + server.address().port;
});

Mount Path

Api path values will be prefixed with the swagger document's basePath value.

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.js

Will route as:

foo.js => /foo
foo/bar.js => /foo/bar
baz.js => /baz

Path 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}.js

This works with directory names as well:

handlers
  |--users
  |    |--{id}.js
  |    |--{id}
  |        |--foo.js

To represent /users/{id}/foo.

Handlers File

Each provided javascript file should export an object containing functions with HTTP verbs as keys.

Example:

module.exports = {
    get: function (req, res) { ... },
    put: function (req, res) { ... },
    ...
}

Handler Middleware

Handlers can also specify middleware chains by providing an array of handler functions under the verb:

module.exports = {
    get: [
        function m1(req, res, next) { ... },
        function m2(req, res, next) { ... },
        function handler(req, res)  { ... }
    ],
    ...
}

Handlers Object

The directory generation will yield this object, but it can be provided directly as options.handlers.

Note that if you are programatically 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 (req, res) { ... },
        'bar': {
            '$get': function (req, res) { ... },
            '$post': function (req, res) { ... }
        }
    }
    ...
}

Handler keys in files do not have to be namespaced in this way.

Security Middleware

If a security definition exists for a path in the swagger API definition, and an appropriate authorize function exists (defined using x-authorize in the securityDefinitions as per swaggerize-routes), then it will be used as middleware for that path.

In addition, a requiredScopes property will be injected onto the request object to check against.

For example:

Swagger API definition:

    .
    .
    .

    //A route with security object.
    "security": [
        {
            "petstore_auth": [
                "write_pets",
                "read_pets"
            ]
        }
    ]
    .
    .
    .
    //securityDefinitions
    "securityDefinitions": {
        "petstore_auth": {
            "x-authorize": "lib/auth_oauth.js", // This path has to be relative to the project root.
            "scopes": {
                "write_pets": "modify pets in your account",
                "read_pets": "read your pets"
            }
        }
    },

Sample x-authorize code - lib/auth_oauth.js :

//x-authorize: auth_oauth.js
function authorize(req, res, next) {
    validate(req, function (error, availablescopes) {
        /*
         * `req.requiredScopes` is set by the `swaggerize-express` module to help
         * with the scope and security validation.
         *
         */
        if (!error) {
            for (var i = 0; i < req.requiredScopes.length; i++) {
                if (availablescopes.indexOf(req.requiredScopes[i]) > -1) {
                    next();
                    return;
                }
            }

            error = new Error('Do not have the required scopes.');
            error.status = 403;

            next(error);
            return;
        }

        next(error);
    });
}

The context for authorize will be bound to the security definition, such that:

function authorize(req, res, next) {
    this.authorizationUrl; //from securityDefinition for this route's type.
    //...
}

More Repositories

1

kraken-js

An express-based Node.js web application bootstrapping module.
JavaScript
4,950
star
2

zoid

Cross domain components
JavaScript
1,975
star
3

lusca

Application security for express apps.
JavaScript
1,785
star
4

post-robot

Cross domain post-messaging on the client side using a simple listener/client pattern.
JavaScript
726
star
5

kappa

A hierarchical npm-registry proxy
JavaScript
556
star
6

grumbler

A template for writing distributable front-end javascript modules.
JavaScript
293
star
7

beaver-logger

Client-side logging w/ super powers
JavaScript
249
star
8

hapi-openapi

Build design-driven apis with OpenAPI (formerly swagger) 2.0 and hapi.
JavaScript
209
star
9

jsx-pragmatic

Build JSX structures, then decide at runtime which pragma you want to use to render them.
JavaScript
181
star
10

express-enrouten

An express route initialization and configuration module.
JavaScript
171
star
11

levee

A circuit-breaker pattern implementation with fallback support.
JavaScript
170
star
12

fetch-robot

Proxy fetch through an iframe
JavaScript
154
star
13

makara

An internationalization module for kraken and express
JavaScript
134
star
14

cross-domain-utils

Cross Domain utilities
JavaScript
132
star
15

adaro

A Dust.js view renderer for express
JavaScript
127
star
16

kraken-example-with-shoppingcart

An example Kraken app showing off a shopping cart
JavaScript
116
star
17

generator-kraken

Yeoman generator for kraken.js apps
JavaScript
110
star
18

jwt-csrf

Stateless CSRF protection using jsonwebtoken (JWT)
JavaScript
108
star
19

shush

A simple module for reading JSON files that may have comments.
JavaScript
90
star
20

meddleware

Middleware configuration for express.
JavaScript
87
star
21

generator-swaggerize

Yeoman generator for design-driven apis with swagger 2.0 and krakenjs/swaggerize tools.
JavaScript
70
star
22

confit

Environment-aware configuration.
JavaScript
61
star
23

zoid-demo

A clonable demo project for xcomponent
JavaScript
61
star
24

swaggerize-routes

Swagger document driven route builder.
JavaScript
58
star
25

zalgo-promise

Release zalgo with synchronous promises
JavaScript
55
star
26

shortstop

Enables use of protocols in configuration.
JavaScript
55
star
27

kraken-example-with-passport

An example integrating kraken with passport authentication
JavaScript
53
star
28

caller

A node module for enabling a module to determine its caller.
JavaScript
47
star
29

nemo

node.js selenium-webdriver/mocha based combined testing framework
JavaScript
44
star
30

kraken-devtools

Development-time tools for kraken.js applications.
JavaScript
39
star
31

cross-domain-safe-weakmap

Cross-domain safe WeakMap shim
JavaScript
33
star
32

grabthar

Hot install and activation of npm modules
JavaScript
23
star
33

karka

A simple rule parser
JavaScript
21
star
34

belter

Miscellaneous browser utilities
JavaScript
16
star
35

angular-remove-di-loaders

Webpack loaders to remove Angular DI (Dependency Injection)
JavaScript
16
star
36

good-influxdb

HapiJS good-reporter for use with InfluxDb
JavaScript
16
star
37

freshy

An (admittedly naïve) node module (un|re)loader/refreshener.
JavaScript
15
star
38

endgame

A tiny module for ensuring uncaught exceptions are handled in Node.js
JavaScript
15
star
39

shortstop-handlers

Common protocol handlers for use with the shortstop node module.
JavaScript
15
star
40

passport-saml-encrypted

A strategy for Passport authentication that supports encrypted SAML responses
JavaScript
14
star
41

pine

A logging wrapper for winston.
JavaScript
14
star
42

react-redux-krakenjs-swaggerize-express

React client app, redux stage management, passport oauth2, paypal rest api and swagger based krakenjs node.js server
JavaScript
14
star
43

spud

A content store parser, reading a java .properties-like format
JavaScript
14
star
44

kraken-example-with-i18n

An example Kraken app showing off internationalization support
JavaScript
11
star
45

kraken-example-with-specialization

An example Kraken app showing off template specialization features.
JavaScript
11
star
46

bundalo

Manage localized sets of content files (be they property/json/etc) which may require rendering with data models
JavaScript
10
star
47

engine-munger

A helper module to insert specialization and i18n in the render workflow
JavaScript
10
star
48

memcookies

Persist cookies on the client-side, useful for supporting cookies disabled browsers
JavaScript
9
star
49

subprocess-robot

Create processes, process pools, and message between processes
JavaScript
8
star
50

grumbler-scripts

Build scripts for grumbler modules
JavaScript
6
star
51

universal-serialize

Universal serializer allowing for custom types
JavaScript
5
star
52

reverend

DEPRECATED: Merge an express-style path string with data to create a valid path.
JavaScript
5
star
53

sync-browser-mocks

Synchronous browser mocks for testing
JavaScript
4
star
54

webpack-mem-compile

Compile webpack to and from memory
TypeScript
3
star
55

hotware

JavaScript
3
star
56

localizr

A library and tool to apply localization to dust templates before rendering
JavaScript
3
star
57

neff

nconf & express based feature flags
JavaScript
3
star
58

krakenjs.github.io

Source for the kraken website
JavaScript
3
star
59

construx

Compile-on-the-fly and other development tools for use when building express applications.
JavaScript
2
star
60

spundle

command line tool and library to package localization files as json
JavaScript
2
star
61

dust-makara-helpers

Server-side configuration of helpers for makara
JavaScript
2
star
62

nodejs_deployment

Design and architecture details of node.js deployment solutions
JavaScript
2
star
63

node-benchmarker

Runs benchmarks and publishes results
JavaScript
2
star
64

grabthar-release

Release scripts for grabthar modules
JavaScript
2
star
65

express-promisified

Express with promises
JavaScript
2
star
66

file-resolver

Used in kraken based projects for resolving files given the locale , file name, and the file extension.
JavaScript
2
star
67

webpack-promise-shim-plugin

Plugin to shim in Promise polyfill into webpack core
JavaScript
2
star
68

beaver-logger-ios

Beaver Logger client for iOS
Swift
2
star
69

anemone-machina

express view engine and browser renderer for React and react-router
JavaScript
1
star
70

findatag

A specialized tokenizer for finding dust-style tags ({@tagname [attributes]})
JavaScript
1
star
71

construx-webpack

web pack dev middleware for krakenjs
JavaScript
1
star
72

express-bcp47

Locale handling middleware for Express
JavaScript
1
star
73

dustjacket

Loader middleware for dustjs
JavaScript
1
star
74

strict-merge

Strict deep merge of objects
JavaScript
1
star
75

makara-languagepackpath

Middleware for exposing the path to a language pack to templates
JavaScript
1
star