The fastest way to create endpoints for a model is to use the CRUD helper function. One line of code can give you all 5 REST endpoints for a model.
// Adds CRUD endpoints for the Car model: list, get, create, update, delete
app.addCrudEndpoints(models.car);Would generate the following endpoints:
- GET /car - list all cars
- GET /car/:id - get a single car by id
- POST /car - create a new car
- PUT /car/:id - update a car by id
- DELETE /car/:id - delete a car by idYou can also manually specify which endpoints to add:
// You can also specify which endpoints to add
app.addCrudEndpoints(models.car, {
types: ['get', 'create']
});You can add business logic that is used in the CRUD endpoints, by specifying actions to run before or after certain operations:
const assertMaxCarsPerUser = app.action({
outputSchema: {
count: sInteger().type(),
message: sString().type(),
},
run: async (system) => {
const maxCarsPerUser = 3;
const count = await system.models.car.count();
const isAllowed = count < maxCarsPerUser;
if (!isAllowed) {
throw new Error(`You can only create up to ${maxCarsPerUser} cars.`);
}
return {
count,
message: 'Ok'
};
}
});
app.addCrudEndpoints(models.car, {
actions: {
// Run assertMaxCarsPerUser action before creating a car
createBefore: assertMaxCarsPerUser,
}
});