我正在try 通过GraphQL解析器返回Postgres DB查询.出于某种原因,当我(故意)查询一行不存在的ID时,result
返回为未定义.当我记录它时,result
总是按预期返回:
result = {
rows: [],
...
}
然而,当我运行它并进行查询时,或者当我使用node inspect index.js
并让它一直运行到调试器时,它似乎没有意识到result
已经定义.当我在 node 中运行console.log(result)
时,当它点击调试器时,我得到以下错误:
debug> console.log(result)
REPL2:1
console.log(result)
^
Uncaught ReferenceError: result is not defined
at REPL2:1:13
at Script.runInContext (node:vm:139:12)
at Object.runInContext (node:vm:289:6)
at REPLServer.controlEval (node:internal/debugger/inspect_repl:578:25)
at bound (node:domain:421:15)
at REPLServer.runBound [as eval] (node:domain:432:12)
at REPLServer.onLine (node:repl:898:10)
at REPLServer.emit (node:events:527:28)
at REPLServer.emit (node:domain:475:12)
at [_onLine] [as _onLine] (node:internal/readline/interface:424:12)
当我在操场上运行查询时,我得到以下错误:
/Users/user/Projects/geolocatr_api/db/queries/user.queries.js:21
id: user.id,
^
TypeError: Cannot read properties of undefined (reading 'id')
at /Users/user/Projects/geolocatr_api/db/queries/user.queries.js:21:20
at Query.<anonymous> (/Users/user/Projects/geolocatr_api/node_modules/pg-pool/index.js:417:18)
at Query.handleReadyForQuery (/Users/user/Projects/geolocatr_api/node_modules/pg/lib/query.js:138:12)
at Client._handleReadyForQuery (/Users/user/Projects/geolocatr_api/node_modules/pg/lib/client.js:290:19)
at Connection.emit (node:events:527:28)
at /Users/user/Projects/geolocatr_api/node_modules/pg/lib/connection.js:114:12
at Parser.parse (/Users/user/Projects/geolocatr_api/node_modules/pg-protocol/dist/parser.js:40:17)
at Socket.<anonymous> (/Users/user/Projects/geolocatr_api/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:324:12)
Node.js v18.0.0
error Command failed with exit code 1.
我真的不知道为什么我的控制台日志(log)似乎看到了一些东西,但Node没有.否则,当传入表中存在的ID时,它会按预期工作.
代码:
// Resolver
Query: {
user: ( _, { id } ) => {
console.log({id}); // Node recognizes this as the correct number
return getUserById(id);
},
},
// DB Query Function
const getUserById = (id) => {
return new Promise(function(resolve, reject) {
db.query(
`
SELECT id, first_name, email, phone
FROM users
WHERE id = $1;
`,
[id],
function(err, result) {
// debugger; // Result comes back as not defined
if (!result.rows) { // Will not run this if block
console.log(result.rows);
reject("Could not find user.");
}
if (err) reject(err);
const user = rows[0];
resolve({
id: user.id,
firstName: user.first_name,
email: user.email,
phone: user.phone,
});
}
);
});
};