【问题标题】:Resolve data returned from psql in graphql在 graphql 中解析从 psql 返回的数据
【发布时间】:2017-05-13 05:09:02
【问题描述】:

我正在尝试将 graphQL 添加到我现有的应用程序中。 我目前使用 psql db 调用支持 Express 端点。 我的目标是使用 psql 访问我的数据,然后在我的 graphQL 'resolves' 中使用这些查询的结果。

这是我的 psql db 调用示例:

'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
}

这是我的 graphQL 架构:

'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;

问题似乎在于我的决心,因为每次我从 graphiql 界面中查询玩家时,我都会看到正确的玩家信息正确记录在我的服务器上,但 graphiql 界面中的结果是null。 有什么想法我在这里做错了吗?

【问题讨论】:

  • PostgresDAO 的类型到底是什么?也许你没有使用方法queryOne 对,就像它返回一个承诺一样?

标签: node.js postgresql express graphql graphql-js


【解决方案1】:

您需要让 Player.getById 返回一个包含回调结果的承诺。

很有可能(完全未经测试的代码):

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);
      }
    );
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-13
    • 2019-07-25
    • 2017-11-01
    • 2023-03-06
    • 2020-03-04
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    相关资源
    最近更新 更多