1.0.5 • Published 2 years ago

express-api-base v1.0.5

Weekly downloads
12
License
-
Repository
-
Last release
2 years ago

Express API Base

This project is a simple utility around a lot of Express functionality.

It allows fine-grain control over IO, configuration, CORS, documentation generation, payload standardization, internal event pipeline, user-safe errors, base pathing, and more.

Basic Use

1.) Create a config.js in the root of your project. See the example config.js for starting base.

2.) Create a config folder in the root of your project. See example config folder for complementary base configs.

3.) Create an index.js with the following (customize to your liking):

const createApp = require("express-api-base/app");
const startApp = require("express-api-base");
const config = require("./config");

const app = createApp({
    config,
    routes: require("./routes")
});

startApp(app, config);

Feature - JSONPayload

This module allows you to standardize route responses, including response codes. Adds the following new properties to the response object:

res.payload // payload object
res.setPayload(payload); // set internal object
res.setError(error); // set internal error
res.noContent(); // set 204 status, remove body

res.sendNoContent();
res.sendPayload(payload, status = 200, metadata = {});
res.sendError(type, details, status = 500, metadata = {});

res.handleError(exception, type = "generic", status = 500);

This module standardizes the output to the following (if not noContent):

{
    "error": "Error type, default is 'generic'",
    "details": "Actual error here",
    "payload": "Actual payload"
}

If an error has occurred, payload is null. The opposite is the case if there was no error, just a payload. metadata in the send*() functions will be spread into the response object.

This allows consuming clients to easily check for problems.

handleError() is a convenient way to handle exceptions in a route. It will automatically console.error() the exception and call res.sendError() with the type, exception and status code.

Feature - Health Check

ECS is a common companion to applications these days. This endpoint simply gives back a 200 with body "Health OK"

Feature - Validation and Documentation

Joi is a popular and powerful validation library. The optional middleware provided allows you to not only validate header, query parameters, path variables or request bodies with joi, but will also populate that in the included OpenAPI endpoint.

OpenAPI is not used, only generated for documentation. Additionally, setting the NODE_ENV to "build" will allow you to save the OpenAPI file to the project root. If you want, you can set your app config's outputType property to openapi or postman to generate either an OpenAPI yaml file or a Postman collection JSON.

Any route registered with validation middleware in express can output its joi description by adding the x-validation-schema query parameter. This request will be intercepted by the validation middleware. Alternatively, you can retrieve the serialized joi schema with the x-joi-schema query parameter.

In addition to validation, additional metadata middleware can be used to decorate the virtual OpenAPI definition further. A route description can be set with the metadata middleware, but in the future more functionality will be added.

Finally, you can view the auto-generated documentation with the /docs endpoint. This can be disabled when calling createApp() by setting disableSwagger to truthy. This endpoint uses swagger-ui-express to render the constructed OpenAPI definition.

Feature - Error Handling

When combined with the payload standardization technique above, this package will automatically handle route errors and return a 500 with the standard error payload format.

Feature - Event Pipeline

PubSub is a common architecture, even when used internally within an application. Using the EventPipeline utility, which is simply an EventEmitter with a few extra functions, you can publish and subscribe to events within your application, decoupling app features when desired.

Other Utilities

Included in this repo is an example package.json scripts and nodemon config, example .eslintrc, example .gitignore, example jsconfig.json. Everything you need to get started quickly.