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.
module.exports = (sequelize, DataTypes) => {
  const { Sequelize } = sequelize;
  const Orders = sequelize.define('orders', {
    shippingStatus: {
      type: DataTypes.STRING,
    },
    ...
  }, {
    tableName: 'orders',
    underscored: true,
    schema: process.env.DATABASE_SCHEMA,
  });
  Orders.associate = (models) => {
    ...
  };
  return Orders;
};
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().
const express = require('express');
const { PermissionMiddlewareCreator, RecordsGetter } = require('forest-express-sequelize');
const { orders } = require('../models');
const router = express.Router();
const permissionMiddlewareCreator = new PermissionMiddlewareCreator('orders');
...
// Update a Order
router.put('/orders/:recordId', permissionMiddlewareCreator.update(), (request, response, next) => {
  return new RecordGetter(orders, request.user, request.query).get(request.params.recordId)
    .then((order) => {
      if (order.shippingStatus === 'Shipped' || order.shippingStatus === 'In transit') {
        response.status(403).send('Sorry, an order cannot be modified once shipped!');
      } else {
        next();
      }
    });
});
...
module.exports = router;PreviousDisplay AWS S3 files from signed URLsNextDisplay, search and update attributes from a JSON field
Last updated
Was this helpful?
