express-api-loader v1.1.1
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
*/
module.exports.getUsers = function(req, res) {
const { url, originalUrl, params } = req
res.json({
url,
originalUrl,
id: params.id
})
}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-loadernpm
npm install --save express-api-loaderImport
const { withExpressApp } = require('express-api-loader')Quick Start
Let's say you have apis/users/user.js as below:
/**
* @method get
* @api /users/:id
*/
module.exports.getUsers = async function(req, res) {
const { url, originalUrl, params } = req
res.json({
url,
originalUrl,
id: params.id
})
}How can we get it up and running as APIs? see:
const express = require('express')
const { resolve } = require('path')
const { withExpressApp } = require('express-api-loader')
// create express app as usual
const app = express()
// scan API files and register as routers automatically
withExpressApp(app)({
scanOpts: {
cwd: resolve(__dirname, 'apis'), // 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.listen(9876, () => {
console.log('server running at 9876')
})try
curl http://localhost:9876/apis/users/123?name=helloto 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
