Employ conventions to register express routes. This is done by creating route definition objects - convroutes - which:
- register the route's method and path
- handle input validation
- document the route
npm install --save convexpressNote: this library requires nodejs >= 8
/* File: src/api/pets/get.js */
// Assuming NODE_PATH=src
const dbClient = require("services/db");
exports.path = "/pets";
exports.method = "get";
exports.description = "List pets";
exports.tags = ["pets"];
exports.responses = {
"200": {
description: "pets list"
}
};
exports.parameters = [
{
name: "status",
description: "Filter by pet status (e.g. available / not available)",
in: "query",
required: false,
type: "string"
}
];
exports.handler = async (req, res) => {
const pets = await dbClient.query(`SELECT * FROM pets WHERE status = $1`, [
req.query.status
]);
res.status(200).send(pets);
};/* File: src/server.js */
const express = require("express");
const convexpress = require("convexpress");
const options = {
info: {
title: "pet store",
version: "1.0.0"
},
host: "localhost:3000"
};
const api = convexpress(options)
// Serve the API's swagger definition at /swagger.json
.serveSwagger()
// Register the route (assuming NODE_PATH=src)
.convroute(require("api/pets/get"))
// Or register multiple routes at once
.loadFrom(`${__dirname}/api/**/*.js`);
const server = express()
.use(api)
.listen(process.env.PORT);Create an express router object (convrouter), which the additional methods
convroute, serveSwagger, and loadFrom.
optionsobject: top-level properties of the swagger definitionhoststringbasePathstringinfoobject:titlestring: title of the api docsversionstring: version of the api
bodyParserOptionsobject: options for the json body parser:
The express router (convrouter).
Registers a convroute.
convrouteobject required: a convroute definition object:pathstring requiredmethodstring requiredhandlerfunction _required__paramtersArray< object >middlewareArray< function >descriptionstringtagsArray< string >responsesMap< object >
The convrouter, to allow for method chaining.
Registers the route GET /swagger.json for serving the swagger definition, and
the route GET /swagger/ for serving the swagger UI html.
None.
The convrouter, to allow for method chaining.
Loads and registers convroutes from files matching the specified pattern.
patternstring required: glob pattern of files to load convroutes from
The convrouter, to allow for method chaining.
See CONTRIBUTING.md.