Hi all,
I’m writing a slug system for one of my entities (let’s call it article), but I have a problem that sounds strange.
I need to generate a prefix + ID slug.
The prefix is a fixed string determined by the entity type. For example, article is [ac].
ID is the id of that article.
When we put them together, the slug will be something like ac29.
I managed to update and fix the slug after the article updates, but I couldn’t get the ID when creating the entity in order to generate the slug, because beforeCreate only supports data and doesn’t seem to contain the ID (because it’s the data I passed in?).
Code in ./api/article/models/article.js
const slug = require('slug');
module.exports = {
lifecycles: {
//Problem part
beforeCreate: async (data) => {
if (data.title) {
data.slug = slug(data.title);
}
},
//Perfect code, but it's too late
beforeUpdate: async (params, data) => {
if (data.slug) {
data.slug = slug(data.prefix) + params.id;
}
},
},
};
Does anyone have a good idea to generate the perfect slug when creating an entity? be deeply grateful.