gpt4 book ai didi

node.js - 使用 GraphQl : How to update fields using mutation 进行 Sequelize

转载 作者:行者123 更新时间:2023-12-03 22:22:51 25 4
gpt4 key购买 nike

我正在使用一堆 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。

关于node.js - 使用 GraphQl : How to update fields using mutation 进行 Sequelize ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45434452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com