Where to write reusable code to access in all the models

You should not write business logic inside the model/{model}.js files.

For these purposes you can use functions:
https://strapi.io/documentation/developer-docs/latest/concepts/configurations.html#functions

Create a file under ./config/functions/encryption.js

With the content:

const Hashids = require("hashids/cjs");
const hashids = new Hashids("RandomSalt", 10);

module.exports = {
  async decrypt(id) {
     id = hashids.decode(id);
     if (id.length === 0) return 0;
     else if (id.length === 1) return Number(id[0]);
     return id;
  },
  async decryptId(params) {
     if (params.id) params.id = decrypt(params.id);
     return params;
  }
}

Now these functions are accessible from anywhere as follows:

  • await strapi.config.functions['encryption'].decrypt(id)
  • await strapi.config.functions['encryption'].decryptId(params)
3 Likes