【问题标题】:Backend with Express(JS) - GraphQL mutation function doesn't work带有 Express(JS) 的后端 - GraphQL 变异函数不起作用
【发布时间】:2021-10-20 08:15:36
【问题描述】:

我没有在后端的突变 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;

resolvers.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}`
    );
  });
})();

【问题讨论】:

    标签: javascript express graphql apollo mutation


    【解决方案1】:

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

    • 父值
    • 参数值
    • 上下文
    • GraphQL 解析信息

    解构第二个参数:

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

    【讨论】:

      猜你喜欢
      • 2023-01-20
      • 2020-12-26
      • 2023-03-25
      • 2021-06-14
      • 2020-06-22
      • 2021-01-01
      • 2022-08-24
      • 2017-05-07
      • 1970-01-01
      相关资源
      最近更新 更多