问题
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})
},
回答1:
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 everywhereSome modules may only need to be initialized once and pass the instance to context.
来源:https://stackoverflow.com/questions/62968788/get-model-from-context-vs-import-apollo-server-express-mongoose