【问题标题】:Connect GraphQL resolvers to database将 GraphQL 解析器连接到数据库
【发布时间】:2020-11-12 12:13:38
【问题描述】:

我正在制作一个小项目,它包含在 Prisma migrate 中制作的单个用户表中。我正在使用 typescript 和 graphQl,并且我知道您可以将实例化的 prisma 客户端传递给我的 graphQLHTTP 中的上下文(使用 express-graphQL),但我无法在我的模式文件中接收它。我将展示架构和我的服务器。

代码中的一些 cmets 显示了我遇到问题的地方

我想将 prisma 客户端作为我的上下文传递,以便我可以在解析器中使用它。我试图找到示例,但在寻找它时我没有找到任何示例。所有的例子都使用了graphql瑜伽之类的东西,我想知道怎么做,如果有人知道怎么做,请给我一些帮助

server.ts

import express from 'express'
import { graphqlHTTP } from 'express-graphql'
import { PrismaClient } from '@prisma/client'

const schema = require('./schemas/schema')
const router = require('../router/router')
const app = express()

const prisma = new PrismaClient()

app.use(router)
app.use('/graphql', graphqlHTTP({
  graphiql: true,
  schema,
  context: prisma <--- I wanted to pass it here. 
}))

app.listen(4000, () => console.log('Server started at 4000'))

schema.ts

import {
   GraphQLObjectType,
   GraphQLString,
   GraphQLList,
   GraphQLID,
   GraphQLSchema
} from 'graphql'


const UserType = new GraphQLObjectType({
  name: 'User',
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    email: { type: GraphQLString },
  })
})

const RootQuery = new GraphQLObjectType({
  name: 'RootQuery',
  fields: {
    users: {
      type: new GraphQLList(UserType),
      resolve(context, args, parent) {
        //What I wanted to do:
        //return context.db.user.findMany() <--- Example

        console.log(context) <-- logs undefined
      }
    }
  }
})

module.exports = new GraphQLSchema({
  query: RootQuery
})

【问题讨论】:

  • 是什么让您觉得上下文是传递给解析器的第一个参数?
  • 是错误吗??
  • 我需要为日志中的所有内容定义一个接口吗?我正在使用打字稿。

标签: database typescript graphql


【解决方案1】:

解析器函数的类型可以在文档中找到here。如果你使用的是 VS Code 之类的 IDE,也可以直接查找相关的 TypeScript 定义。

type GraphQLFieldResolveFn = (
  source?: any,
  args?: {[argName: string]: any},
  context?: any,
  info?: GraphQLResolveInfo
) => any

第一个参数是父字段解析器返回的“父”值。然后是字段参数。然后是上下文。

所以你需要确保你访问的是正确的参数。

此外,您应该像这样设置上下文:

app.use('/graphql', graphqlHTTP({
  graphiql: true,
  schema,
  context: { prisma },
}))

这样,如果您需要向上下文添加其他属性,则无需重构现有代码。

【讨论】:

    猜你喜欢
    • 2020-08-17
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2020-11-19
    • 2017-07-27
    • 2021-06-17
    相关资源
    最近更新 更多