首页 > 解决方案 > 带有 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}`
    );
  });
})();

标签: javascriptexpressgraphqlapollomutation

解决方案


您正在解构错误的论点。参数按以下顺序:

  • 父值
  • 参数值
  • 语境
  • GraphQL 解析信息

解构第二个参数:

const resolvers = {
 Mutation: {
  createOwner: (parent, {name}) => {
      console.log('createOwner name', name)
      return name
  }
 }
}

推荐阅读