TramwayJS

Create API

Now the application is ready to support HATEOAS, let's create an API and implement it.

Create API

  1. Create an API for the resource you want to create. In this example we will use Product.
tramway create:api Product --provider provider.mysql

Remember that if Tramway is installed locally, you will need to reference its path in the node_modules folder: ./node_modules/.bin/tramway

This walkthrough will assume that your provider is ready and working with the necessary schemas.

The command will have created the scaffold for the API leaving just the Product entity and ProductFactory factory for you to implement. The rest is already implemented and wired with Tramway - including the routing:

VerbRouteController Action
GETproductsget
GETproducts/:idgetOne
POSTproductscreate
PUTproducts/:idreplace
DELETEproducts/:iddelete

Update Controller Definition

  1. Update the Controller definition to add a formatter and logger.

One of the new files that was created is src/controllers/ProductController.js, note that it extends RestfulController. The RestfulController implements all the main endpoints you need to get started but can be overridden if necessary. To support HATEOAS, you'll need to forward the formatter and logger like so:

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);
}
}

Then you'll need to update the dependency configuration to ensure a formatter and logger get mapped at boot, otherwise these fields will be undefined.

Your ProductController entry should now look like this:

"controller.product": {
"class": ProductController,
"constructor": [
{"type": "service", "key": "router"},
{"type": "service", "key": "service.product"},
{"type": "service", "key": "service.formatter"},
{"type": "service", "key": "logger"},
],
"functions": []
},