返回结果后执行Graphql postgresql promise

时间:2017-02-27 19:07:02

标签: node.js es6-promise graphql

我正在尝试使用graphql。我从postgresql中提取数据,除了在查询完成之前解析完成的一个问题之外,其他任何工作似乎都有效。我虽然我的查询承诺正常工作。这是我创建的用于查询数据库的类:

class PgPoolClient {

    constructor(options) {
        this.connection = options.connection;
    }

    query(sql, data = []) {

        return new Promise((resolve, reject) => {
            var pool = new pg.Pool(this.connection);
            pool.connect((err, client, done) => {
                if (err) {
                    reject({
                        code: 505,
                        message: err.message,
                        entrys: []
                    });
                } else {
                    client.query(sql, data, (err, results) => {
                        done();
                        if (err) {
                            reject({
                                code: 404,
                                message: err.message,
                                entrys: []
                            });
                        } else {
                            resolve({
                                code: 200,
                                message: "ok",
                                entrys: results
                            });
                        }
                    });
                }
            });

            pool.on("error", (err, client) => {
                reject({
                    code: 505,
                    message: err.message,
                    entrys: {}
                });
            });

        });
    }
}

这是我的graphql查询:

const Query = new GraphQLObjectType({
    name: 'Query',
    description: 'Root query object',
    fields: () => ({
        accounts: {
            type: new GraphQLList(Account),
            resolve(root, args) {

                const parameters = [];
                pg.query(`SELECT
id, token, user_identifier as userIdentifier, hash_password as hashPassword,
is_enabled as isEnabled, security_type_id as securityTypeID,
is_admin as isAdmin, ad_path as adPath, date_created as dateCreated,
date_modified as dateModified, modified_by as modifiedBy
FROM accounts.account`, parameters)
                .then((result) =>
                {
                    console.log(result.entrys.rows);
                    //return result.entrys.rows;
                    return [
                        {
                        id: '33333',
                        token: '111',
                        userIdentifier: 'test'
                        }
                    ]

                })
                .catch((err) =>
                {
                    console.log(err);
                    return err.message;
                });

                console.log('finished');
        }
    })
});

我注释掉了我的结果,只是想看看返回静态内容,似乎当它在then()中时,结果不会返回到graphisql(意味着在then()之前完成了解析)。输出:

{
  "data": {
   "accounts": null
 }

}

我能够通过将静态返回数组放在console.log('finished')下面来验证这一点,并且它可以正确地返回数据。

console.log('finished');
return [
    {
    id: '33333',
    token: '111',
    userIdentifier: 'test'
    }
]                   

显示在graphiql中:

{
  "data": {
    "accounts": [
      {
        "id": "33333",
        "token": "111",
        "userIdentifier": "test"
      }
    ]
  }
}

所以似乎我的承诺没有被等待。我的查询函数中是否存在一些导致决定不等待我的结果的东西?任何帮助将不胜感激。

更新1

似乎我将查询包装在Promise中它起作用:

return new Promise((resolve, reject) => {

pg.query(`SELECT
id, token, user_identifier as userIdentifier, hash_password as hashPassword,
is_enabled as isEnabled, security_type_id as securityTypeID,
is_admin as isAdmin, ad_path as adPath, date_created as dateCreated,
date_modified as dateModified, modified_by as modifiedBy
FROM accounts.account`, parameters)
.then((result) =>
{
    console.log(result.entrys.rows);
    //return result.entrys.rows;
    resolve( [
        {
        id: '33333',
        token: '111',
        userIdentifier: 'test'
        }
    ]);

})
.catch((err) =>
{
    console.log(err);
    reject(err.message);
});

我想我的问题是,如果我的查询功能已经包含在Promise中,为什么我必须再次执行呢?

1 个答案:

答案 0 :(得分:1)

您的resolve函数需要返回承诺。当你明确地将它包装在一个promise中时,它是有效的,因为你返回了它。如果你返回调用pg.query的结果,它应该没有它。

const Query = new GraphQLObjectType({
name: 'Query',
description: 'Root query object',
fields: () => ({
    accounts: {
        type: new GraphQLList(Account),
        resolve(root, args) {
            const parameters = [];
            return pg.query(`query`, parameters)
            .then((result) =>
            {
                console.log(result.entrys.rows);
                //return result.entrys.rows;
                return [
                    {
                    id: '33333',
                    token: '111',
                    userIdentifier: 'test'
                    }
                ]
            })
            .catch((err) =>
            {
                console.log(err);
                return err.message;
            });
            console.log('finished');
        }
    })
});