0

I'm making a demo GraphQL API as a learning project which is using Apollo-server-express, Babel, Knex.js and PostgreSQL.

Query resolver went well but found a problem at mutation, returning null for non-nullable field.

// userMutation.js

import knex from '../libs/knex';

const userMutation = {
  create: function(data) {
    return knex('users')
      .insert(data)
      .returning('*');
  }
};

...

// Mutation.js

import userQuery from '../../queries/userQuery';
import userMutation from '../../mutations/userMutation';

const Mutation = {
  async createUser(parent, args, ctx, info) {
    const { data } = args;

    const emailTaken = userQuery.getByEmail(data.email);
    if (emailTaken) throw new Error('Email is taken');

    const user = {
      ...data
    };

    const result = await userMutation.create(user);

    console.log(result);
    return result;
  }
};

// typeDefs.js

type Mutation {
  createUser(data: CreateUserInput!): User
}

And I make a mutation:

mutation {
  createUser(
    data: { lastName: "One", email: "some@one.com", password: "okay123" }
  ) {
    email
  }
}

Then...

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field User.email.",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ],
      "path": [
        "createUser",
        "email"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR"
      }
    }
  ],
  "data": {
    "createUser": null
  }
}

What am I doing wrong? Please help.

Swix
  • 1,883
  • 7
  • 33
  • 50
  • The shape of the data returned by the call to `insert` doesn't match your schema. According to your schema, the field should return a sigle object, but you are returning an array inside your resolver. Either change your schema, or grab the first item returned by `insert`. See [Common Scenario #2: Array Instead of Object](https://stackoverflow.com/a/56319138/6024220) for more details. – Daniel Rearden Jul 18 '19 at 12:10
  • Use console.log to find the shape of the returning object. Then use Daniel's post to solve your problem. You'll get better at this as you get more experience with GraphQL. – Preston Jul 18 '19 at 14:43
  • @DanielRearden Thanks, you're right. Resolver (knex) returning array, I changed the schema to `[User]` and it's fixed. @Preston Thanks, yes I needed to double-check the console.log output. – Swix Jul 19 '19 at 03:27

0 Answers0