【问题标题】:Apollo Server - how to create and add object in resolver when type isn't available in namespaceApollo Server - 当类型在命名空间中不可用时如何在解析器中创建和添加对象
【发布时间】:2020-10-17 04:43:28
【问题描述】:

在下面的示例中,我试图创建一个帖子并将其添加到 Dictionary 'post' 中。当项目类型对解析器的命名空间不可用时,Mutation 如何创建、添加到哈希并返回创建的项目的类型?

mutation createPost {
  createPost(input: {name: "Post Name"}){
    name
  }
}

index.js:

const { ApolloServer, gql } = require('apollo-server');
const dictionary = {};
const typeDefs = gql`

    input PostSpecInput {
        name: String
    }

    type PostSpec {
        id: ID!
        name: String
    }

    type Mutation {
          createPost(input: PostSpecInput): PostSpec
    }

    type Query {
        post_specs: [PostSpec]
    }
`;

const resolvers = {
    Query: {
        post_specs: () => Object.keys(dictionary).map(function(key){
            return dictionary[key];
        })
    },
    Mutation: {
        createPost(parent, args, context, info) {
            var id = require('crypto').randomBytes(10).toString('hex');
                const postSpec = new PostSpec(id, args.input);
                posts_mock_database[id] =  args.input;
                return postSpec;
            }
      }
}

const server =  new ApolloServer({typeDefs, resolvers})

server.listen().then(({url}) => {
    console.log(`Server Ready at ${url}`);
})

错误:

{
  "errors": [
    {
      "message": "PostSpec is not defined",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "createPost"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "ReferenceError: PostSpec is not defined",
            "    at createPost (index.js:38:34)",

【问题讨论】:

    标签: apollo apollo-server


    【解决方案1】:

    类型定义既不是类也不是对象实例,它们只是用于强制类型。即使您在命名空间中,调用“新”也行不通。这是模拟数据库的解决方案:

     Mutation: {
            createPost(parent, args, context, info) {
                var id = require('crypto').randomBytes(10).toString('hex');
                    const newPostSpec = { id: id, name: args.input.name }
                    posts_mock_database[id] = newPostSpec;
                    return newPostSpec;
                }
          }
    

    【讨论】:

    • 这确实消除了对底层结构的根本误解。
    猜你喜欢
    • 2019-08-01
    • 2021-12-14
    • 2018-10-04
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多