TramwayJS

Restful Controller

A class that orchestrates communications between services and the client - tailored for rapidly developing REST APIs.

If you're just writing a Restful API, it can rapidly become tedious and messy when you end up creating each part of the CRUD structure and register each route.

Much of the logic behind this process can be abstracted, such that if you already have a Provider and a linked Repository, all you will have to do is make a derived RestfulController to put it altogether.

Definition

Locations

  • Implementation: src/controllers
  • Dependency Injection: src/config/services/controllers.js

API

The RestfulController comes with pre-implemented functions.

FunctionUrlMethodResponse
getOne/:resource/:idGETA formatted resource entity
get/:resourceGETA formatted resource collection
create/:resourcePOSTInserts a resource entity
update/:resource/:idPATCHUpdates a resource entity
replace/:resource/:idPUTReplaces a resource entity
delete/:resource/:idDELETEDeletes a resource entity

The following methods from the base Controller class can also be used.

FunctionUsage
getRouter(): RouterReturns the Router class for extendability
redirect(res: Object, path: string, status: number)Calls the main redirect function in Express. Will default to a 301 status code.
getRoute(name: string)Gets route metadata by name.
getRouteByAction(action: string)Gets route for the current controller action where action is the method name.

Example

import { controllers } from 'tramway-core-router';
const { RestfulController } = controllers;
export default class ProductController extends RestfulController {
constructor(router, service, formatter, logger) {
super(router, service, formatter, logger);
}
}

Dependency Injection

import {
ProductController,
} from '../../controllers';
export default {
"controller.product": {
"class": ProductController,
"constructor": [
{"type": "service", "key": "router"},
{"type": "service", "key": "service.product"},
{"type": "service", "key": "service.formatter"},
{"type": "service", "key": "logger"},
],
"functions": []
},
};