[英]What's the right way to declare an object in Node.js router
我正在尝试解决我的 Node.js 应用程序中的 memory 泄漏,似乎这段代码确实泄漏了
const ApolloClient = require('apollo-client').ApolloClient;
const fetch = require('node-fetch');
const createHttpLink = require('apollo-link-http').createHttpLink;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
const httpLink = createHttpLink({
uri: 'http://xxxxxx',
fetch: fetch
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
module.exports = (app) => {
app.post('/graphql', async (req, res, next) => {
try {
const data = await client.query({
query: 'xxxxxxx',
variables: 'xxxxxxx'
});
return res.json(data);
} catch (err) {
return next('error');
}
});
};
所以 ApolloClient 客户端每次都会重新创建,因为它是全局的。 在路线内定义它更好吗? 那它不会导致性能问题吗?
const ApolloClient = require('apollo-client').ApolloClient;
const fetch = require('node-fetch');
const createHttpLink = require('apollo-link-http').createHttpLink;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
module.exports = (app) => {
app.post('/graphql', async (req, res, next) => {
try {
let httpLink = createHttpLink({
uri: 'http://xxxxxx',
fetch: fetch
});
let client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
const data = await client.query({
query: 'xxxxxxx',
variables: 'xxxxxxx'
});
httpLink = null
client = null
return res.json(data);
} catch (err) {
return next('error');
}
});
};
出于多种原因,创建一个 ApolloClient 实例并重用它会更好。
考虑有 20 个或更多 (N) 个端点/中间件需要访问存储在数据库中的某些数据。 为每个创建一个ApolloClient
实例意味着 N 个实例。 这不是高效的,并且违反了“不要重复自己”的编码规则。
另一方面,创建一个实例并在整个应用程序中使用它非常方便。 考虑这个例子:
const ApolloClient = require('apollo-client').ApolloClient;
const fetch = require('node-fetch');
const createHttpLink = require('apollo-link-http').createHttpLink;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
const httpLink = createHttpLink({
uri: 'http://xxxxxx',
fetch: fetch
});
// instantiating
module.exports = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
一个模块:
const dbClient = require('./db_client')
module.exports = (app) => {
app.post('/graphql', async (req, res, next) => {
try {
const data = await dbClient.query({
query: 'xxxxxxx',
variables: 'xxxxxxx'
});
return res.json(data);
} catch (err) {
return next('error');
}
});
};
另一个模块:
const dbClient = require('./db_client')
...
另一个模块:
const dbClient = require('./db_client')
...
可以看出,只需一个实例,我们就可以实现更健壮和高性能的应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.