0

I am trying to run a graphql mutation to create a user to dynamoDB. When I run the mutation, I am expecting it to return the newly create User. But even though my data is added to the DB successfully and my resolver is returning the correct type, the data coming back is always null.

My Mutation schema:

input UserInput {
    active: Boolean!
    email: String!
    fullname: String!
    description: String!
    tags: [String!]!
  }

type User {
    active: Boolean!
    email: String!
    fullname: String!
    description: String!
    tags: [String!]!
  }

type Mutation {
    createUser(input: UserInput!): User!
  }

My resolver:

Mutation: {
        createUser: (_, user, { dataSources }) => {
            return dataSources.userAPI.createUser(user)
        }
    }

Lastly, my userAPI is:

class UserAPI extends DataSource {
  initialize(config) {
    this.context = config.context;
  }

  createUser(user) {
    const params = {
      TableName: "Users",
      Item: {
        active: {BOOL: user.input.active},
        email: { S: user.input.email },
        fullname: { S: user.input.fullname },
        description: { S: user.input.description },
        tags: { SS: user.input.tags.map(tag => tag) },
        id: {S: uuidv4()}
      }
    };

    return dynamodb.putItem(params, function(err) {
      if (err) {
        console.log("Error: ", err);
      } else {
        console.log("Success");
        return user.input;
      }
    });
  }

I keep getting an error saying "Cannot return null for non-nullable field ...." Any idea why this is happening?

Kaisin Li
  • 514
  • 3
  • 7
  • 21
  • 1
    Callbacks are asynchronous. If you return a value inside a callback, it won't be accessible inside the function that called it. In other words, the result of calling `dynamodb.putItem` is simply `undefined` and that's what you are returning inside your resolver. Instead, you should return some value or a Promise that will resolve the value. In general, don't use callbacks with GraphQL -- always use Promises instead. The aws sdk can return a Promise if you omit the callback I believe. Otherwise you can wrap the callback in a promise. – Daniel Rearden Oct 31 '19 at 02:04
  • See [Common Scenario #6](https://stackoverflow.com/questions/56319137) – Daniel Rearden Oct 31 '19 at 02:04

0 Answers0