我是GraphQL的新手并尝试编写更新变异。但是,我收到Resolve函数\“User.id \”返回undefined“错误,虽然数据库实际上已更新。
我做错了什么?
userSchema.js:
import Sequelize from 'sequelize';
import SqlHelper from '../helpers/sqlhelper';
const config = require('../../config');
const sequelizer = new SqlHelper(config).Init();
const createUser = sequelizer.define(
'createUser',
{
...
}
);
const updateUser = sequelizer.define(
'updateUser',
{
id: {
type: Sequelize.UUID,
field: 'Id',
primaryKey: true,
defaultValue: Sequelize.UUIDV4,
},
username: {
type: Sequelize.STRING,
field: 'Username',
allowNull: true,
},
email: {
type: Sequelize.STRING,
field: 'Email',
allowNull: true,
},
firstname: {
type: Sequelize.STRING,
field: 'FirstName',
allowNull: true,
},
lastname: {
type: Sequelize.STRING,
field: 'LastName',
allowNull: true,
},
....
},
{
// define the table's name
tableName: 'Users',
},
);
module.exports = User;
UserResolver.js:
import User from '../dbschemas/user';
import Sequelize from 'sequelize';
const Op = Sequelize.Op;
export default {
Mutation: {
createUser: async (obj, args) =>
(await User.create(args)),
updateUser: async (obj, args) =>
(await User.update(args,
{
where: {
id: args.id,
},
returning: true
}))
}
};
虽然从GraphiQL调用updateUser会更新记录(在db中),但会导致“Resolve function for”User.id \“返回undefined”错误:
mutation{
updateUser(id: "2ecd38ca-cf12-4e79-ac93-e922f24af9e3",
username: "newUserTesting",
email: "testemail@yahoo.com",
lastname: "TestUserLName",
firstname: "fname1") {
id
}
}
{
"data": null,
"errors": [
{
"message": "Resolve function for \"User.id\" returned undefined",
"locations": [
{
"line": 16,
"column": 4
}
],
"path": [
"updateUser",
"id"
]
}
]
}
答案 0 :(得分:1)
问题很明显,您的解析器不会返回包含grid = initial_grid[:]
的对象。
The docs说id
返回一个数组,其中第二个元素是受影响的行。
因此,您的解析器应如下所示:
Model.update
......被你需要的任何东西取代。
答案 1 :(得分:1)
显然,update不会为MSSQL返回受影响的行,只会返回受影响的记录数。
返回时仅适用于postgres:true:
public static update(values: Object, options: Object): Promise<Array<affectedCount, affectedRows>>
设置返回:true(对于MSSQL)返回undefined(并且数组中的params顺序甚至不是正确的顺序...即,第一个受影响的行 - >未定义,然后是affectedCount - >受影响的行数。)
要获得一个物体,你需要做这样的事情:
Mutation: {
createUser: async (obj, args) =>
(await User.create(args.user)),
updateUser: async (obj, args, context, info) =>{
let user = args.user;
let response = await User.update(user,
{
where: {
[Op.or]: [{ email: user.email }, { id: user.id }, { username: user.username }, { lastname: user.lastname}]
},
//returning: true //not working... only for postgres db :(
}).then(ret => {
console.log('ret', ret);
return ret[0];
}).catch(error => {
console.log('error', error)
});
if (response > 0) return user; //return record
//return response > 0; //return true
}
}