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
- Library: tramway-core-router
- File: https://github.com/tramwayjs/router/blob/master/src/core/controllers/RestfulController.js
Locations
- Implementation:
src/controllers
- Dependency Injection:
src/config/services/controllers.js
API
The RestfulController comes with pre-implemented functions.
Function | Url | Method | Response |
---|---|---|---|
getOne | /:resource/:id | GET | A formatted resource entity |
get | /:resource | GET | A formatted resource collection |
create | /:resource | POST | Inserts a resource entity |
update | /:resource/:id | PATCH | Updates a resource entity |
replace | /:resource/:id | PUT | Replaces a resource entity |
delete | /:resource/:id | DELETE | Deletes a resource entity |
The following methods from the base Controller
class can also be used.
Function | Usage |
---|---|
getRouter(): Router | Returns 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": []},};