Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda