从上下文获取模型VS导入-apollo server express & mongoose[英] Get model from context vs Import - apollo server express & mongoose

本文是小编为大家收集整理的关于从上下文获取模型VS导入-apollo server express & mongoose的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我想知道是否有区别,或者 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 或查询构建器,通过上下文向解析器注入依赖项都会更好.

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

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

  3. 有些模块可能只需要初始化一次并将实例传递给上下文.

本文地址:https://www.itbaoku.cn/post/1938160.html

问题描述

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.

  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.