GraphQL查询在GraphiQL中返回NULL,但数据显示在控制台日志中



我有一个GraphQL API,它应该从MySQL和PostGres数据库返回数据。在解析器中,我有console.log结果,可以在终端中查看数据。

address: {
type: AddressType,
description: "An Address",
args: {
id: { type: GraphQLInt },
},
resolve: (parent, args) => {
// Make a connection to MySQL
let result;
connection.query(
`SELECT * FROM addresses WHERE id = ${args.id}`,
(err, res, fields) => {
if (err) console.log(err);
console.log("========");
console.log(res);
console.log("+++++++++");
console.log(res[0]);
// console.log(result);
}
);
return result;
},
},

在终端中,当我在GraphiQL:上运行查询时,我可以看到结果

[nodemon] starting `node schema.js`
Server is running
Connected to PSQL database.
Connected to mySQL database.
========
[
RowDataPacket {
id: 1,
address_type: 'House',
status: 'Inactive',
entity: 'Building',
number_and_street: 'PO BOX 276',
suite_and_apartment: 'PO',
city: 'Ennis',
postal_code: '59729-0276',
country: 'USA',
notes: 'Dolorem quia repellendus et et nobis.',
created_at: 2020-12-18T05:00:00.000Z,
updated_at: 2021-05-21T04:00:00.000Z,
latitude: null,
longitude: null
}
]
+++++++++
RowDataPacket {
id: 1,
address_type: 'House',
status: 'Inactive',
entity: 'Building',
number_and_street: 'PO BOX 276',
suite_and_apartment: 'PO',
city: 'Ennis',
postal_code: '59729-0276',
country: 'USA',
notes: 'Dolorem quia repellendus et et nobis.',
created_at: 2020-12-18T05:00:00.000Z,
updated_at: 2021-05-21T04:00:00.000Z,
latitude: null,
longitude: null
}

然而,在GraphiQL上,数据为null。输入:

{
address(id: 1) {
address_type
}
}

输出:

{
"data": {
"address": null
}
}

我是GraphQL的新手。我在这里会错过什么?我正试图从终端获取这些信息,以便在GraphiQL中查询时显示。只是想学习更多。

注意力不集中的经典问题:您可以将res变量用于控制台。你没有给result赋值。

并且在执行查询之前执行CCD_ 3。(断章取义,你有数据(

有关如何使用async / await语法,请参阅文档。您当前正在使用回调,这不是推荐的语法。

不确定,但应该类似于,您应该使用async/await,并等待query数据的返回。还要确保将值分配给您拥有的变量:

address: {
type: AddressType,
description: "An Address",
args: {
id: { type: GraphQLInt },
},
resolve: async (parent, args) => {
const result = await connection.query('SELECT * FROM addresses WHERE id = $1', [args.id]);

return result;
},
},

最终对我有效的是:

address: {
type: AddressType,
description: "An Address",
args: {
id: { type: GraphQLInt },
},
resolve: async (parent, args) => {
const [rows, fields] = await promisePool.query(
`SELECT * FROM addresses WHERE id = ${args.id}`
);
console.log(rows[0]);
return rows[0];
},
},

最新更新