quick and dirty api boilerplate

Craig Fletcher 4c9c8d3549 Add middlewares, multiple handlers hace 4 años
src 4c9c8d3549 Add middlewares, multiple handlers hace 4 años
.env.example 086655b567 Add docker-compose hace 4 años
.eslintrc.cjs 4337b08561 Initial commit hace 4 años
.gitignore 086655b567 Add docker-compose hace 4 años
.nvmrc 4337b08561 Initial commit hace 4 años
.prettierrc 4337b08561 Initial commit hace 4 años
README.md 4c9c8d3549 Add middlewares, multiple handlers hace 4 años
docker-compose.yml 086655b567 Add docker-compose hace 4 años
package-lock.json 4c9c8d3549 Add middlewares, multiple handlers hace 4 años
package.json 8de3d7b176 Add logging hace 4 años

README.md

Easy API boilerplate

Quick and dirty API boilerplate, using:

  • Redis for the DB
  • Yup for validation
  • Restify for the web server/routing
  • Winston for logging
  • ESLint for linting

There are many limitations to this configuration, it is intended as a debugging/prototyping tool.

There are fairly few npm modules, not a lot of code, and most things are simply factories with dependencies passed in.

Usage

Import start from easy-api.js, call like so:

start({
  routes[], 
  host, 
  port,
  middlewares[],
  redisOpts{}, 
  restifyOpts{}
})

The included example uses docker and docker-compose, so the db host is set to "redis" and the restify server listens on 0.0.0.0:8080. You'll need to rename .env.example to .env and change the password.

Storage

Objects are stored in redis by calculating the sha256 hash, hex digest from a "path" array for convenience (e.g. ["users", req.params.userName, "stats", "visits"]).

There is no hardening or security intention behind this - it's simply a fast hash to use as an ID.

Routes

Routes are defined as simple factories, passed a db wrapper, yup and log instance as an object ({db, yup, log}) and expected to return:

  • verb: HTTP verb, e.g. get
  • path: restify path string, e.g. /api/hello/:name
  • handlers: array of restify handler functions for route
  • schema (optional): yup schema to validate against

Validation

If a route passes a schema, the request will be validated against it before any other handlers are called.

  • get requests validate against req.params
  • post requests validate against req.body

When validation fails, a HTTP 400 is returned and the remaining handlers are not processed.

Middlewares

Middlewares are defined as factories, returning a restify-compatible middleware. They are passed the server instance and restify, like so:

const middlewareToBeApplied = middlewareFactory({server, restify});
server.use(middlewareToBeApplied);