2016-12-28 65 views
0

我试图将graphQL添加到我现有的应用程序中。 我目前使用psql db调用返回Express端点。 我的目标是使用psql来访问我的数据,然后在我的graphQL'resolves'中使用这些查询的结果。解决在graphql中从psql返回的数据

这里是我的PSQL数据库调用的例子:

'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。 任何想法我在这里做错了吗?

+0

那是什么类型'PostgresDAO'真的是?也许你没有使用'queryOne'方法,或许它会返回一个promise? –

回答

2

您需要让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); 
     } 
    ); 
    }); 
}