Skip to content

Routes & Middlewares

Konstantinos Markopoulos edited this page Jul 17, 2019 · 1 revision

Routes

All routes are collected in routes/index.ts and mounted on '/api'.

import routes = require('./api/routes/index');
app.use('/api', routes);

Create a new router: user.ts and mount it on routes/index.ts

import users = require('./users');
router.use('/users', users);

This will be available on /api/users/. E.g. /api/users/create

Add an endpoint

// Create new user
router.route('/').post(
  prepare(method.createUser),
  respond
);

POST @ /api/users/ will create a new user.

prepare and respond are middlewares and method.createUser() is an async function, which does the actual job.

Middlewares

  • prepare will actually construct a middleware that will gather all input (url query & post payload) into a single object and call the method (in this case method.createUser) with this object. It writes the output of the method into res.locals or calls the error-handler on failure.
  • respond just sends the res.locals

There are more middleware:

  • authenticate checks request headers and validates the token
  • guards depending on the guard, checks that the token owner has access to do what he request

Full example:

// Update user by id
router.route('/:id').post(
  authenticate, // Is the Authorization header (token) valid? Yes: continue, No: Unauthorized
  guard.asSelf, // Are you the user you are trying to update? Yes: continue, No: Unauthorized
  prepare(method.updateUser), // Do the update
  respond // send back the result
);

TODO: add middleware to validate input

Clone this wiki locally