gpt4 book ai didi

javascript - 如何在 Sequelize 中的更新突变中返回模型(或任何与此相关的内容)?

转载 作者:行者123 更新时间:2023-11-29 15:58:09 57 4
gpt4 key购买 nike

我正在使用更新模型方法来使用 mysql2 方言更新 Sequelize 中的条目。看起来 MySQL 只能返回受影响的行数。我想将它作为 bool 值传递回来。

应该指出的是,我对 JS/ES6、Node 以及几乎所有这些都相当陌生,我更精通 PHP,所以如果答案很明显或者对 JS 存在根本误解,我提前道歉,但我我保证我已经为此工作了几个小时。更新方法的在线文档和在线示例相当简单。

我能找到的最接近的答案是:Sequelize on GraphQL update not return anything

为了简洁起见,我删除了此代码中不相关的部分。

型号:

export default (sequelize, DataTypes) => {
const Payment = sequelize.define('payment', {
...
processed: {
type: DataTypes.INTEGER(1).UNSIGNED,
allowNull: false,
defaultValue: '0'
},
...
return Payment;

架构:

...
type Payment {
id: Int!
amount: Float!
processedTime: Int
processed: Int!
dueDate: Int!
status: PaymentStatuses

Employee: Employee
Client: Client!
Merchant: Merchant
PaymentType: PaymentType
}

type Query {
getPayment(id: Int!): Payment
}
type Mutation {

updatePaymentStatus(id: Int!, processed: Int!): Boolean

}

我最初想做的是:

updatePaymentStatus(id: Int!, processed: Int!): Payment!

解析器:

Mutation {
updatePaymentStatus: async (parent, {id, processed}, {models}) =>
{await models.Payment.update({processed}, {where: {id}})
.then((datareturned) => {return datareturned[0]})}
}

如果我检查我的数据库,更新实际上工作正常。如果我 console.log(datareturned[0]) 我得到一个 1 (如果没有更新行则得到 0)。

我希望能够至少返回一个 bool 值,如我的架构中所述,但无论我尝试什么,我都会收到 null 或其他错误,因为返回的值为 null。我意识到我可能错误地假设返回 1 将被假定为 true,但我也尝试过:

.then((datareturned) => {if (datareturned[0] === 1) {return true}})}

在 GraphiQL 中:

mutation{
updatePaymentStatus(id:1, processed:0)
}

回应:

{
"data": {
"updatePaymentStatus": null
}
}

我不确定问题是否在于我缺乏 JS 知识,或者 Sequelize 使用 MySQL 方言没有返回太多内容,或者介于两者之间。

最佳答案

嘿,我昨晚刚刚遇到这个......我在我的解析器中这样做了

addUserProfileCertification: async (_, args, { models }) => {
try {
await models.ProfileCompanyCertification.create(args.input);
return true;
} catch (err) {
logger.error(err);
}
return false;
},

和我的突变

addUserProfileCertification(input: ProfileCertificationInput!): Boolean

GraphiQL 结果看起来像

{
"data": {
"addUserProfileCertification": true
}
}

如果您愿意,您可以轻松返回整个模型,方法是返回一个 findOne ,其中包含解析器底部的参数中的 id,例如...

updateUserProfileContact: async (_, args, { models }) => {

let returnValue = null;
const { id, input } = args;
try {
await models.ProfileContact.update(input, { where: { id } });
returnValue = await models.ProfileContact.findOne({ where: { id } });
} catch (err) {
logger.error(err);
}
return returnValue;
},

您只需要告诉您的突变需要支付类型而不是 bool 值,并且您可以通过仅选择付款中的某些字段作为您输入 GraphiQL 的突变的一部分来细化您想要传回客户端的内容

关于javascript - 如何在 Sequelize 中的更新突变中返回模型(或任何与此相关的内容)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56350748/

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