0

I am learning GraphQL. Just made a simple API with Apollo-server-express with Knex.js and PostgreSQL. I am facing a weird issue with querying user by ID, which return null.

This is user schema.

// user.schema.ts
  extend type Query {
    users: [User!]!
    user(id: ID): User
  }

This is user resolver.

// user.resolver.ts

    user: async (_: any, { id }: { id: number }, { dataSources }: any) => {
      await dataSources.userAPI.findOne({ id });
    }

This is datasource for user.

  async findOne({ id: idArg }: { id?: number } = {}) {
    const user: User = await this.knex('user')
      .where('id', idArg)
      .first();

    if (!user) return;
    console.log('@ USER HERE > ', user)
    return user;
  }

Note: console.log returns user with values.

@ USER HERE >  {
  id: 1,
  first_name: 'Some',
  last_name: 'One',
  email: 's@one.com',
  password: '$2a$08$C8PP992UaUX.T90mxm2yD.RKB.ZnAx.gzMpK796JQei4H1BvVNxBG',
  role: 'staff',
  is_active: false,
  created_at: 2019-09-17T16:03:06.949Z,
  updated_at: 2019-09-17T16:03:06.949Z
}

But somehow, it returns null in GraphQL playground.

{
  "data": {
    "user": null
  }
}

Does it relate to the caching? Because I tested some cache controls from Apollo docs. This is what I added in user findOne resolver before;

      // Add cache hints dynamically, this will hide result and return null
      // info.cacheControl.setCacheHint({ maxAge: 60, scope: 'PRIVATE' });
      await dataSources.userAPI.findOne({ id });

After that it started returning null, even after I removed it back. I have the same code for Post without testing that info.cache. Querying by Post ID is working fine.

Please help me.

Swix
  • 1,883
  • 7
  • 33
  • 50
  • 2
    nothing is returned from user.resolver.ts -> user function, that could be the issue. – Pavan Bahuguni Sep 17 '19 at 16:53
  • 1
    A resolver must always return some value. Returning undefined will cause the field to resolve to null. See [Common Scenario #4](https://stackoverflow.com/a/56319138/6024220). – Daniel Rearden Sep 18 '19 at 01:41
  • Thanks! I don't know what went wrong, but now everything is fine after I rewrote the code. – Swix Sep 20 '19 at 06:04

0 Answers0