Where to write reusable code to access in all the models

System Information
  • Strapi Version: 3.2.5
  • Operating System: Ubuntu
  • Database: Postgresql
  • Node Version:14.15.3
  • NPM Version: 6.14.9
  • Yarn Version: 1.22.10

Hi i have a piece of code which i am using for external id encryption and decrytion.
The code is working fine.
but i am facing the code redundancy issue. as i have placed same code in all the models/{modelName}.js

Here is the small snippet i am trying to use…
./api/{apiName}/models/{modelName}.js

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

/**
 * Read the documentation (https://strapi.io/documentation/v3.x/concepts/models.html#lifecycle-hooks)
 * to customize this model
 */
function decrypt(id) {
  id = hashids.decode(id);
  if (id.length === 0) return 0;
  else if (id.length === 1) return Number(id[0]);
  return id;
}
function decryptId(params) {
  if (params.id) params.id = decrypt(params.id);
  return params;
}
module.exports = {
  /**
   * Triggered before products find
   */

      lifecycles: {
        async beforeFind(params, populate) {
          params = decryptId(params);
        },
    }
}

const Hashids = require(“hashids/cjs”);
const hashids = new Hashids(“RandomSalt”, 10);
function decrypt(id){..}
function decryptId(params){...} 

now where can i add this reusable functionality
so that somehow i can call them at all the models/{ModelName}.js.
Thank you.

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

For these purposes you can use 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)
2 Likes

Thank you very much :slight_smile:

Hey Sunny, great answer. Just out of curiosity for learning purposes, why should we not write core business functions inside the model.js files?

They are used for life cycles, and this structure will change likely later on in 2021.

2 Likes