我有一個 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上,我的資料為空。輸入:
{
address(id: 1) {
address_type
}
}
輸出:
{
"data": {
"address": null
}
}
我對 GraphQL 很陌生。我會在這里錯過什么?我試圖從終端獲取此資訊以在 GraphiQL 中查詢時顯示。只是想了解更多。
uj5u.com熱心網友回復:
注意力不集中的經典問題:您將res變數用于控制臺。并且您在任何地方都沒有為result.
并且在return result執行查詢之前執行。(在您擁有資料的背景關系之外)
有關如何使用async / await語法,請參閱檔案。您當前正在使用回呼 - 這不是推薦的語法。
uj5u.com熱心網友回復:
不確定,但應該類似于,您應該使用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;
},
},
uj5u.com熱心網友回復:
最終對我有用的是以下內容:
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];
},
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/367604.html
標籤:javascript mysql 图形
上一篇:GROUPBY不顯示所有欄位
