使用 GraphQl 续集:如何使用突变更新字段



我正在使用一堆koa2,sequelize和graphql。我不想使用 graphql 突变更改用户模型的状态字段并返回更改的对象。

目前我的突变看起来像这样:

mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
setState: {
type: userType,
args: {
input: {
type: userStateInputType
}
},
resolve: resolver(db.user, {
before: async (findOptions, {input}) => {
const {uuid, state} = input;
await db.user.update(
{state},
{where: {uuid}}
);
findOptions.where = {
uuid
};
return findOptions;
}
})
}
}
})

这是相应的查询:

mutation setstate{
setState(input: {uuid: "..UUID..", state: "STATE"}) {
uuid
state
}
}

它正在工作,但我很确定有更好的解决方案。

我会避免尝试使用graphql-sequelize的resolver助手来处理突变。查看该库的源代码,看起来它实际上仅用于解析查询和类型。

我认为更干净的方法就是做这样的事情:

resolve: async (obj, { input: { uuid, state } }) => {
const user = await db.user.findById(uuid)
user.set('state', state)
return user.save()
}

我避免在这里使用update(),因为这只返回受影响的字段。如果您决定扩展突变返回的字段,则以这种方式返回整个用户对象并避免为某些字段返回 null。

最新更新