无法编写GraphQL Mutation以在数据库中创建新用户

时间:2017-09-08 12:42:03

标签: javascript node.js mongodb graphql

我想要做的基本上是将新用户插入数据库并使用GraphQL Mutation返回新的用户数据。但我无法插入数据 数据库。在下面的图像中获取空值而不是新的用户数据。任何人都可以告诉我我的代码到底错了。

schema.JS

type Mutation {
  createEmployee(input: EmployeeInput): Employee
}

input EmployeeInput {
    firstName: String
    lastName: String
    phone: String
    email: String
    name: String
    domainName: String
    smsID: String
}

type Employee {
    id: ID
    adminFirstName: String
    adminLastName: String
    adminPhone: String
    adminEmail: String
    smsID: String
    domainName: String
}

resolver.JS

import { employeesRepo } from "repos";

const mutationResolvers = {
    createEmployee: async ({ firstName, lastName, email, phone, businessName, domainName }) =>
    await employeesRepo.createEmployee(arguments[0])
};

employeesRepo.Js

async createEmployee(employee) {
let newEmployee = await this.employeeStore.insert(employee);
return newEmployee;

}

MongoStore.JS

async insert(document) {
   let db, collection, result, now;
   now = new Date();
   document.createdOn = now;
   document.lastUpdated = now;
   document._id = new ObjectId();
  try {
     db = await MongoClient.connect(url, options);
     collection = db.collection(this.collectionName);
     result = await collection.insertOne(document);
    } catch (err) {
      console.log(err);
    } finally {
     db.close();
   }
   return document;
  }

1 个答案:

答案 0 :(得分:1)

您已将解析器定义为:

createEmployee: async (source) => await employeesRepo.createEmployee(source)

但是,您实际上想要处理传递给字段的input参数,该参数位于传递给resolve的第二个参数中。请尝试改为:

createEmployee: async (source, args) => await employeesRepo.createEmployee(args.input)

请参阅此处的GraphQLFieldResolveFn定义:

http://graphql.org/graphql-js/type/#graphqlobjecttype

type GraphQLFieldResolveFn = (
  source?: any,
  args?: {[argName: string]: any},
  context?: any,
  info?: GraphQLResolveInfo
) => any