Woodshop
Search…
Prevent record update
This example shows you how to prevent updating records based on specific criteria. Here, shipped orders should not be editable. We will notify the user with a customized error message.

Requirements

    An admin backend running on forest-express-sequelize

How it works

Directory: /models

This directory contains the orders.js file where the model is declared.
/models/order.js
1
module.exports = (sequelize, DataTypes) => {
2
const { Sequelize } = sequelize;
3
const Orders = sequelize.define('orders', {
4
shippingStatus: {
5
type: DataTypes.STRING,
6
},
7
...
8
}, {
9
tableName: 'orders',
10
underscored: true,
11
schema: process.env.DATABASE_SCHEMA,
12
});
13
14
Orders.associate = (models) => {
15
...
16
};
17
18
return Orders;
19
};
20
Copied!

Directory: /routes

This directory contains the orders.js file where the routes are declared.
We override the update route so it sends an error as a response when the shippingStatus is either Shipped or In transit. Otherwise, it triggers the default logic with next().
/routes/orders.js
1
const express = require('express');
2
const { PermissionMiddlewareCreator, RecordsGetter } = require('forest-express-sequelize');
3
const { orders } = require('../models');
4
5
const router = express.Router();
6
const permissionMiddlewareCreator = new PermissionMiddlewareCreator('orders');
7
8
...
9
10
// Update a Order
11
router.put('/orders/:recordId', permissionMiddlewareCreator.update(), (request, response, next) => {
12
return new RecordGetter(orders, request.user, request.query).get(request.params.recordId)
13
.then((order) => {
14
if (order.shippingStatus === 'Shipped' || order.shippingStatus === 'In transit') {
15
response.status(403).send('Sorry, an order cannot be modified once shipped!');
16
} else {
17
next();
18
}
19
});
20
});
21
22
...
23
24
module.exports = router;
Copied!
Last modified 2mo ago