在 NodeJS 项目中扩展本机对象的最优雅方式是什么?
Which is the most elegant way to extend a native object in a NodeJS project?
我有一个使用 BigInt 作为其模型 ID 的 NodeJS 项目。我还有一个 WebSocket,我将序列化的对象发送给客户端。 BigInt 的问题在于它不像其他对象(Boolean、Number 等)那样可序列化。因此,我使用 MDN recommendation 来定义 BigInt 对象的全局处理函数。
BigInt.prototype.toJSON = function() { return this.toString() }
从现在开始,我将在整个应用范围内使用它。
问题是我应该把这段代码放在哪里,这样它才优雅并且尊重 SOLID 原则?
我正在为某种问题寻找好的解决方案。
目前它被放置在 index.js 中,像这样:
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);
});
此类扩展的最佳做法是使用此 question 的解决方案。
我重构了这样的代码。
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);
});
我有一个使用 BigInt 作为其模型 ID 的 NodeJS 项目。我还有一个 WebSocket,我将序列化的对象发送给客户端。 BigInt 的问题在于它不像其他对象(Boolean、Number 等)那样可序列化。因此,我使用 MDN recommendation 来定义 BigInt 对象的全局处理函数。
BigInt.prototype.toJSON = function() { return this.toString() }
从现在开始,我将在整个应用范围内使用它。
问题是我应该把这段代码放在哪里,这样它才优雅并且尊重 SOLID 原则?
我正在为某种问题寻找好的解决方案。
目前它被放置在 index.js 中,像这样:
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);
});
此类扩展的最佳做法是使用此 question 的解决方案。
我重构了这样的代码。
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);
});