Search code examples
strapi

Change / validate properties before insert or update


I am trying to do some custom validation / sanitization on the data before insert and update. I thought the model's lifecycle callbacks are a good place to this kind of work:

module.exports = {
  // Before saving a value.
  // Fired before an `insert` or `update` query.
  beforeSave: async (model) => {
    console.log('[beforeSave]', 'model', model)
    // Do something here with the model
  },

  // Before creating a value.
  // Fired before an `insert` query.
  beforeCreate: async (model) => {
    console.log('[beforeCreate]', 'model', model)
    // Do something here with the model
  },

  // Before updating a value.
  // Fired before an `update` query.
  beforeUpdate: async (model) => {
    console.log('[beforeUpdate]', 'model', model)
    // Do something here with the model
  }
};

When I insert a new record the beforeSave and beforeCreate methods both get called. The model in this case is the new object I want to insert.

When I update a record the beforeSave method does not get called, the beforeUpdate method gets called but the model is not the object I want to save. In this case the model is a Query object.

Is this the best place to this validation?

If so how can I modify the object before update?

I am using Strapi v3.0.0-beta.16.3 with MongoDB.


Solution

  • Here is what I suggest you to manage your life cycle. Example to manage slug

    // const slugify = require('slugify');
    
    beforeSave: async (model) => {
      if (model.title) {
        model.slug = slugify(model.title);
      }
    },
    beforeUpdate: async (model) => {
      if (model.getUpdate().title) {
        model.update({
          slug:  slugify(model.getUpdate().title)
        });
      }
    },
    

    For SQL connections this would be the option:

    beforeSave: async (model) => {
      if (model.get('title')) {
        model.set({slug: slugify(model.get('title'))});
      }
    },