Resolve data returned from psql in graphql

460 Views Asked by At

I'm attempting to add graphQL to my existing application. I currently back Express endpoints with psql db calls. I aim to use psql to access my data and then use the results of these queries in my graphQL 'resolves'.

Here is an example of my psql db call:

'use strict';

const config = require('../../config');
const PostgresDAO = require('core/src/server/db/dao/postgres');
const postgresRW = new PostgresDAO(config.postgresRW);

function getById(id) {
  postgresRW.queryOne(
    `
      SELECT id, email, create_date
      FROM gamesDB.players
      WHERE id = $1;
    `,
    [id],
    function(err, result) {
      console.log(result);
      return result;
    }
  );
}

module.exports = {
  getById: getById
}

Here is my graphQL schema:

'use strict';

const graphql = require('graphql');
const Player = require('./types/player');
const db = require('../db');

const RootQueryType = new graphql.GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    player: {
      type: Player,
      description: 'The current player identified by an ID.',
      args: {
        key: {
          type: new graphql.GraphQLNonNull(graphql.GraphQLString)
        }
      },
      resolve: (obj, args) => {
        return db.players.getById(args.key);
      }
    }
  }
});

const testSchema = new graphql.GraphQLSchema({
  query: RootQueryType
});

module.exports = testSchema;

The issue seems to lie in my resolve as each time I query a player from within the graphiql interface I see the correct player's info properly logged on my server, but the result in the graphiql interface is null. Any ideas what I'm doing wrong here?

1

There are 1 best solutions below

0
On BEST ANSWER

You need to make Player.getById return a promise that contains the result from the callback.

So likely (completely untested code):

function getById(id) {
  return new Promise(function(resolve, reject) {
    postgresRW.queryOne(
      `
        SELECT id, email, create_date
        FROM gamesDB.players
        WHERE id = $1;
      `,
      [id],
      function(err, result) {
        if (err) reject(err);
        else resolve(result);
      }
    );
  });
}