GraphQL 使用 GraphQL 工具获取用户

GraphQL get a user with GraphQL tools

我有一个使用 ExpressJS 的 GraphQL 服务器。这是使用 GraphQL-Tools 的模式:

import UserModel from '../models/User'

export const Schema =  `

type User {
    id: Int!
    firstName: String
    lastName: String
}

type Query {
    users: [User]
}

schema {
    query: Query
}

`

export const resolveFunctions = {
    Query: {
        users() {
            return UserModel.findAll()
        }
    }
}

在没有 GraphQL-Tools 的情况下,我可以获得完整的用户列表和特定用户,但是现在当我使用 GraphQL-Tools 时,我不知道如何通过 ID 获取特定用户。

除了官方文档,我没有在网上找到任何关于 GraphQL 工具的资源,所以我希望这能帮助其他正在寻找答案的人。

谢谢!

您应该添加一个查询:

user(id: String!): User

和处理程序:

user(root, args, ctx) {
  return UserModel.findOne({id: args.id});
}

(您可能需要调整参数类型和调用语义,我只是概述了所需的步骤)。

如果您想查看一个工作示例,可以查看 graphQL starter project。我最近向其中添加了一个非常相似的查询。

也许你应该看看 graphqly。它是建立在 graphql-tools 之上的抽象,可帮助您更轻松地开发 Graphql 服务。这是 graphqly:

的示例代码
import graphly from "graphqly";

const gBuilder = graphly.createBuilder();

// define types, inputs ... (in any order)
gBuilder.type("Products").implements("List").def(`
    products: [Product]!
`);

gBuilder.type("Product").def(`
    id: ID!
    name: String!
    link: String
    price: Int
`);

gBuilder
.query(`
    products(limit: Int = 20, offset: Int = 0, filter: ProductFilter): Products
`)
.resolve((root, args, context) => {
    // your resolver here
});