本文介绍了从上下文vs导入获取模型-Apollo Server Express&猫鼬的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有区别,或者apollo-server中通过mongoose查询mongodb的最佳实践是什么

I am wondering if there is a difference, or what is best practice in an apollo-server to query mongodb via mongoose

从上下文中获取模型:

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或查询构建器,都最好通过上下文将依赖项注入解析器.

Inject dependencies to resolver via context is better no matter what ORM or query builder you are using.

  1. 易于测试.我们可以为User创建模拟对象并轻松使用它.遵循依赖倒置的原理.

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

如果您有很多解析器,则无需为每个解析器导入User.只需将其导入到初始化上下文的文件中一次即可.初始化上下文的模块在一个文件中管理,而不是分散在各处

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.

这篇关于从上下文vs导入获取模型-Apollo Server Express&猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 09:07