问题描述
我想知道是否有区别,或者 apollo-server 中通过 mongoose
查询 mongodb 的最佳做法是什么从上下文中获取模型:
import User from './User' const apolloServer = new ApolloServer({ typeDefs, resolvers, context: ({ req, res }) => ({ req, res, User, }),
getUser(parent, args, context, info) { return context.User.findOne({ _id: args.id}) },
VS
import User from './User' getUser(parent, args, context, info) { return User.findOne({ _id: args.id}) },
推荐答案
无论您使用什么 ORM 或查询构建器,通过上下文向解析器注入依赖项都会更好.
易于测试.我们可以为 User 创建模拟对象并轻松使用它.遵循依赖倒置原则.
如果您有很多解析器,则不需要为每个解析器导入 User.只需在初始化上下文的文件中导入一次.用于初始化上下文的模块在一个文件中管理,而不是分散在各处
有些模块可能只需要初始化一次并将实例传递给上下文.
问题描述
I am wondering if there is a difference, or what is best practice in an apollo-server to query mongodb via mongoose
Get model from context:
import User from './User' const apolloServer = new ApolloServer({ typeDefs, resolvers, context: ({ req, res }) => ({ req, res, User, }),
getUser(parent, args, context, info) { return context.User.findOne({ _id: args.id}) },
VS
import User from './User' getUser(parent, args, context, info) { return User.findOne({ _id: args.id}) },
推荐答案
Inject dependencies to resolver via context is better no matter what ORM or query builder you are using.
Easy to test. We can create mocked object for User and use it easily. Follow the principle of dependency inversion.
If you have many resolvers, you don't need to import User for each resolver. Just import it once in the file where to initialize the context. The modules for initializing the context are managed in one file instead of scattered everywhere
Some modules may only need to be initialized once and pass the instance to context.