Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
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);
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda