Search code examples
javascriptnode.jsexpressmodulesolid-principles

Which is the most elegant way to extend a native object in a NodeJS project?


I have a NodeJS project that uses BigInt for its model's ids. I also have a WebSocket where I sent serialized objects to a client. The problem with BigInt is that it is not serializable like other objects (Boolean, Number, etc). Therefore I use MDN recommendation to define a global handler function the BigInt object.

BigInt.prototype.toJSON = function() { return this.toString()  }

I will use this in the entire app scope from now on.

The question is where do I place this code so it is elegant and respects SOLID principles?

I am looking for a good solution for kind of issue.

Currently it is placed in index.js like this:

import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from './middleware/logger';

const main = async () => {
  // where should I modularise BigInt extension
  BigInt.prototype.toJSON = function () {
    return this.toString();
  };

  app.use(cors());

  app.get('/', (req, res) => {
    res.send('Hello World!');
  });

  app.listen(3000, () => console.log(`Example app listening on port 3000!`));
};

main().catch((err) => {
  logger.error(err);
});

Solution

  • The best practice for this kind of extension is to use the solution for this question.

    I've refactored the code like this.

    utils.ts

    (BigInt.prototype as any).toJSON = function () {
      return this.toString();
    };
    

    index.ts

    import 'dotenv/config';
    import cors from 'cors';
    import express from 'express';
    import logger from './middleware/logger';
    import "utils.ts" // <== this code gets executed, therefore BigInt extenstion is in the scope of project from now on
    
    const main = async () => {
      app.use(cors());
    
      app.get('/', (req, res) => {
        res.send('Hello World!');
      });
    
      app.listen(3000, () => console.log(`Example app listening on port 3000!`));
    };
    
    main().catch((err) => {
      logger.error(err);
    });