Apollo Server - 当命名空间中的类型不可用时如何在解析器中创建和添加对象

Apollo Server - how to create and add object in resolver when type isn't available in namespace

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

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)",

类型定义不是 类 也不是对象实例,它们只是用于强制类型。即使您在命名空间中,调用 'new' 也不会起作用。这是您的模拟数据库的解决方案:

 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;
            }
      }