一直在尝试学习GraphQL,我有一个graphql变异,它在mysql数据库中成功创建了一个用户但是解析fn没有返回mysql查询返回的id(由result.insertId访问)。但是,如果我注销结果,则日志具有正确的值(我知道一旦开始工作,我可以将其清理一下)。获取数据的所有查询都可以正常工作。有人有主意吗?提前谢谢。
resolve: async (parentValue, args) => {
const res = await addUser(args)
const id = await res.insertId
console.log('Returning: ', id); // This logs out the correct id
return await id // In graphiql, the id returned is null and is returned WAY before the log above it. Not sure why that write is so slow, but that's another issue
}
// addUser function defined in another file
module.exports = {
addUser: (args) => {
const {
firstName,
lastName,
username,
password,
occupation,
email
} = args
return db.query(`
INSERT INTO users (firstName, lastName, userName, password, occupation, email)
VALUES (?, ?, ?, ?, ?, ?)`,
[
firstName,
lastName,
username,
password,
occupation,
email
])
}
}
// Class to make wrap mysql with Promises (from https://codeburst.io/node-js-mysql-and-promises-4c3be599909b)
class Database {
constructor(config) {
this.connection = mysql.createConnection(config);
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.connection.query(sql, args, (err, rows) => {
if (err)
return reject(err);
resolve(rows);
});
});
}
close() {
return new Promise((resolve, reject) => {
this.connection.end(err => {
if (err)
return reject(err);
resolve();
});
});
}
}
module.exports = new Database(config);
**更新 我没有尝试返回新创建的字段的id,而是尝试获取id,然后获取新创建的用户并且完美地工作。那么我在这里做错了什么?为什么我必须获取新用户而不是仅返回id?我认为这可能是因为addUser变种上的类型设置为UserType(具有字段id,firstName,lastName等),但我创建了一个NewUserType,它只有一个id字段,但仍然无效。很想知道这里发生了什么。
resolve: async (parentValue, args) => {
const res = await addUser(args)
const id = await res.insertId
return getUser(id)
}