gpt4 book ai didi

javascript - 无法让 Graphql-tools 读取我的 schema.graphql 文件

转载 作者:行者123 更新时间:2023-12-04 16:26:20 35 4
gpt4 key购买 nike

我正在使用 Apollo-server-express 和 Graphql-tools。我一直在阅读 Graphql-tools 文档,但我无法让它工作。我正在尝试将我的 schema.graphql 文件导入为我的 typeDefs。似乎 Graphql-tools 应该让这一切变得简单,但有些事情并没有落实到位。

index.js

const { ApolloServer } = require("apollo-server-express");
const { makeExecutableSchema } = require('@graphql-tools/schema');
const express = require("express");
const { join } = require("path");
const { loadSchema } = require("@graphql-tools/load");
const { GraphQLFileLoader } = require("@graphql-tools/graphql-file-loader");
const { addResolversToSchema } = require("@graphql-tools/schema");
const app = express();

const resolvers = {
Query: {
items: (parent, args, ctx, info) => {
return ctx.prisma.item.findMany();
},
},
Mutation: {
makeItem: (parent, args, context, info) => {
const newItem = context.prisma.item.create({
data: {
...args,
price: parseInt(Math.ceil(args.price * 100)),
},
});
return newItem;
},
deleteItem: (parent, args, context, info) => {
return context.prisma.item.delete({
where: {
id: args.id,
},
});
},
},
};

const schemaSource = loadSchemaSync(join(__dirname, "schema.graphql"), {
loaders: [new GraphQLFileLoader()],
});

const schema = makeExecutableSchema({
typeDefs: schemaSource,
resolvers,
});

const server = new ApolloServer({
schema,
resolvers,
});

server.applyMiddleware({ app });

app.listen(
{ port: 4000 },
() =>
console.log(
`🌎 => Backend server is now running on port http://localhost:4000`
)
);

schema.graphql

type Query {
items: [Item!]!
}

type Mutation {
makeItem(
piece: String!
image: String!
identifier: String!
price: Float!
itemNumber: Int!
): Item!
deleteItem(id: ID!): Item!
}

type Item {
id: ID!
piece: String!
image: String!
identifier: String!
price: Int!
itemNumber: Int!
}

在当前状态下,我收到一条错误消息:“错误:typeDefs 必须是字符串、数组或模式 AST,得到对象”

据我了解,makeExecutableSchema 应该执行所有必要的步骤,例如将架构更改为字符串。我似乎无法弄清楚这里发生了什么,任何帮助将不胜感激。

最佳答案

loadSchemaSync 将使用提供的指针加载 GraphQLSchema 对象。您应该改用 loadTypedefsSync

const sources = loadTypedefsSync(join(__dirname, "schema.graphql"), {
loaders: [new GraphQLFileLoader()],
});
const typeDefs = sources.map(source => source.document)
const server = new ApolloServer({ typeDefs, resolvers })

如果你想使用loadSchema,你不需要使用makeExecutableSchema,因为你的schema已经创建好了。所以你可以这样做,如 docs 所示。 :

const schema = loadSchemaSync(join(__dirname, "schema.graphql"), {
loaders: [new GraphQLFileLoader()],
});

const resolvers = {...};
const schemaWithResolvers = addResolversToSchema({
schema,
resolvers,
});
const server = new ApolloServer({ schema: schemaWithResolvers })

关于javascript - 无法让 Graphql-tools 读取我的 schema.graphql 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63117446/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com