Get model from context vs Import - apollo server express & mongoose

只谈情不闲聊 提交于 2020-07-23 06:43:26

问题


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.

  1. Easy to test. We can create mocked object for User and use it easily. Follow the principle of dependency inversion.

  2. 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

  3. Some 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!