javascript - 带有 Express(JS) 的后端 - GraphQL 变异函数不起作用
问题描述
我没有在后端的突变 GraphQL 中获得请求变量。我不明白为什么它不起作用。我收到下一个错误:“无法解构‘未定义’的属性‘名称’,因为它是未定义的。”
我在 Apollo Studio 中所做的突变:
mutation Mutation($createOwnerName: String) {
createOwner(name: $createOwnerName)
}
我在 Apollo Studio 中的变量:
{
"createOwnerName": "John"
}
我使用 Express schema.js 的后端:
const { buildSchema } = require("graphql");
const schema = buildSchema(`
type Mutation {
createOwner(name: String): String
}
`);
module.exports = schema;
解析器.js:
const resolvers = {
Mutation: {
createOwner: ({name}) => {
console.log('createOwner name', name)
return name
}
}
}
server.js:
const { createServer } = require("http");
const express = require("express");
const { execute, subscribe } = require("graphql");
const { ApolloServer } = require("apollo-server-express");
const { SubscriptionServer } = require("subscriptions-transport-ws");
const { makeExecutableSchema } = require("@graphql-tools/schema");
const typeDefs = require("./graphql/schema.js");
const resolvers = require("./graphql/resolvers.js");
require("dotenv").config();
const mongoose = require("mongoose");
// mongoose
mongoose
.connect(process.env.DB_HOST, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected"))
.catch((err) => console.log(err));
(async () => {
const PORT = 3033;
const app = express();
const httpServer = createServer(app);
app.get("/rest", function (req, res) {
return res.json({ data: "rest" });
});
const schema = makeExecutableSchema({ typeDefs, resolvers });
const server = new ApolloServer({
schema,
});
await server.start();
server.applyMiddleware({ app });
SubscriptionServer.create(
{ schema, execute, subscribe },
{ server: httpServer, path: server.graphqlPath }
);
httpServer.listen(PORT, () => {
console.log(
` Query endpoint ready at http://localhost:${PORT}${server.graphqlPath}`
);
console.log(
` Subscription endpoint ready at ws://localhost:${PORT}${server.graphqlPath}`
);
});
})();
解决方案
您正在解构错误的论点。参数按以下顺序:
- 父值
- 参数值
- 语境
- GraphQL 解析信息
解构第二个参数:
const resolvers = {
Mutation: {
createOwner: (parent, {name}) => {
console.log('createOwner name', name)
return name
}
}
}
推荐阅读
- python - 使用 matplotlib 为 y=0 和 y=1 绘制不同颜色的散点图
- python - 返回节点以外的其他内容
- r - R 中的一切都是一个对象,每个动作都是一个函数调用,不是
- node.js - Vue.js - 创建管理员和用户面板 - 最佳实践
- python - 如何使用 Python 从网页中获取 href 链接?
- quarkus - 如何在 Quarkus 中获取 ThreadFactory?
- javascript - 关于单击 div 然后使用 ajax 更新 mysql 数据库的安全问题
- pytorch - 是加载模型不需要评估?
- css - 如何以纯 CSS 方式使 100% 宽度的 div 始终具有 50% 的相对高度?
- sql - 如果存在 sql SELECT