2016-12-28 67 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); 
     } 
    ); 
    }); 
}