node.jsstrapitable-relationships

Intercepting an assignment to a table relation field


I created a one-to one relationship between two tables in strapi.

As an example, suppose that Bob currently has a job, say messenger, if we assign Bob’s Job to secretary, Strapi simply reassigns the new Job, without warning that Bob was already in a job

If a person is not in a current job, it’s job would be ‘none’

I’d like to forbid the reassignment of the job, if Bob was already in a job (the user would have to assign the Bob's job to ‘none’ before assigning a new job)

In strapi, what would be the right way to forbid it (checking if the current job is not ‘none’, and, if it’s the case, stopping the assignment), using a service, a controller or a lifecycle hook?


Solution

  • One way to handle this in Strapi would be to use a lifecycle hook. Lifecycle hooks allow you to perform specific actions at certain stages of the CRUD operations (create, update, delete) on a model. In this case, you can use the beforeUpdate hook to check if the current job is not none before allowing the assignment of a new job:

    // api/person/models/Person.js
    
    module.exports = {
      lifecycles: {
        // This hook will be called before updating a person
        async beforeUpdate(params, data) {
          // Check if the current job is not 'none'
          if (params.current.job !== 'none') {
            // If the current job is not 'none', throw an error
            throw new Error('Cannot reassign a job to a person who already has a job');
          }
        }
      }
    };
    

    You can also use a service or a controller to handle this logic, but using a lifecycle hook allows you to centralize this logic and keep it separate from your business logic.