Skip to main content

Structure

How it works

Basically, a Model needs a Controller and if any data needs to be exposed through the API, then a Route is needed as well. The next part of the documentation will show a practical example on how to create a new model, controller, route and middleware.

Models

Check out the Sequelize documentation to find out all the possible options for a model. To create a new model run the following command in server/models:
…where Brew is the model name and name is a string attribute. Important! make sure that the generated migration contains all the fields created in the model. Check the other models to learn how to create associations. Code style used by the models:
Now let’s see how a new model can be integrated with the app. In the example below we will create a Brew model.

Controllers

The controllers hold all the functions that the app needs to manipulate the data with Sequelize (or any other functionality that uses data from the database). If the functions are not using any data from the database, consider using Middleware or Modules. Controllers code-style and Brew example below:

Routes

Like the models, all the routes need to be registered in api/index.js file in order for the application to see them. Below is an example of a brew route that uses the controller created above with some explanations about the code style guide.
The next step is to register the new route with the index file:

Authentication

Chartbrew uses jwt token authentication. To make authenticated requests, the Authorization header must be set to include a valid token
Making a POST to /user/login with a valid email and password will return the token in the response. In order to add authorization checks to the routes, the verifyToken middleware can be used in the routes like so:

Permissions & Roles

Chartbrew implements permissions and roles as well, but in not-so-ideal way. A future update will try a remedy this in a way to make it easier to make changes to these. All the permissions and roles are registered in modules/accessControl.js. It is important to note that most of these roles are from the team perspective. So for example if a chart "read:any" permission is given to a user, this user can read any charts from the team that user is in only. Below you can see an example on how to protect resources based on permissions and roles.

Middleware

The middleware can be used in the all the routes in the api folder. Have a look at the ExpressJS documentation on Middleware for more details.

Modules

This folder contains various functionality that usually doesn’t use local database data. The middleware will be moved from here in due course.