express-api-loader
Enhance API writing experience in declarative way with Express.js.
We'd like to provide a new way as below:
/** * @method get * @api /users/:id */moduleexports { const url originalUrl params = req res}
It's declarative, all you need for API writing is giving a proper annotation, @method
- for http method definition; @api
- for API path. And nothing else.
You don't have to worry about how router organized any more.
Install
yarn
yarn add express-api-loader
npm
npm install --save express-api-loader
Import
const withExpressApp =
Quick Start
Let's say you have apis/users/user.js
as below:
/** * @method get * @api /users/:id */moduleexports { const url originalUrl params = req res}
How can we get it up and running as APIs? see:
const express = const resolve = const withExpressApp = // create express app as usualconst app = // scan API files and register as routers automatically scanOpts: cwd: // where to start scanning pattern: '**/*.js' // which file will be loaded as API declaration ignore: '**/_*.js' // which file will be ignored from scanning apiPrefix: '/apis' // will be prepended in every api path app
try
curl http://localhost:9876/apis/users/123?name=hello
to see the result.
Methods
withCors(app: express.Express)
Enable Cross-Origin Resource Sharing
withExpressApp(app: express.Express)
Setup scan options for API initialization
withLogger(opts)
Provide specific logger
implementation. console.log/warn/error
is used by default
withRequestHandler(app: express.Express, customHandler: (function(bodyParser): any))
Setup request middlewares as needed. app.use(bodyParser.json())
by default
withResponseHandler(opts: {onNormalResponse: function, onErrorResponse: function})
Setup response transformer for normal/error case individually while fast return {value}
with @api
Properties
logger
Log information
ResponseError
You have to use this custom error implementation while throwing error within @api