简体   繁体   English

如何在Sequelize的更新变异中返回模型(或任何相关的东西)?

[英]How to return a model back (or anything for that matter) on an update mutation in Sequelize?

I am using the update model method to update an entry in Sequelize using the mysql2 dialect. 我正在使用更新模型方法使用mysql2方言更新Sequelize中的条目。 It seems as if with MySQL you can only return a count of rows affected. 似乎使用MySQL,您只能返回受影响的行数。 I would like to pass it back as a boolean. 我想把它作为布尔值传回去。

It should be noted that I am fairly new to JS/ES6, Node, pretty much all of this, I am more versed in PHP so I apologize in advance if the answer is obvious or a fundamental misunderstanding of JS, but I promise I have worked on this for hours. 应该注意的是,我对JS / ES6,Node来说相当新,几乎所有这一切,我对PHP更精通,所以如果答案很明显或对JS的基本误解,我提前道歉,但我保证我有在这工作了几个小时。 The online documentation and online examples for the update method are fairly light. 更新方法的在线文档和在线示例相当简单。

The closest answer I can find is at: Sequelize on GraphQL update not return anything 我能找到的最接近的答案是: 在GraphQL更新上的Sequelize不会返回任何内容

I have removed irrelevant bits of this code for brevity. 为简洁起见,我删除了此代码的不相关内容。

Model: 模型:

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

Schema: 架构:

...
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

}

What I was originally trying to do was: 我最初想要做的是:

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

Resolver: 解析器:

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

If I check my database, the update is actually working correctly. 如果我检查我的数据库,则更新实际上正常工作。 If I console.log(datareturned[0]) I get a 1 (or 0 if no rows were updated). 如果我是console.log(datareturned [0])我得到1(如果没有更新行,则为0)。

I would like to be able to return at least a Boolean as described in my schema but no matter what I try, I get null or some other error because the returned value is null. 我希望能够返回至少一个布尔值,如我的架构中所描述,但无论我尝试什么,我得到null或其他一些错误,因为返回的值为null。 I realize I may be incorrectly assuming returning 1 will be assumed as true but I have also tried: 我意识到我可能错误地假设返回1将被假定为真,但我也尝试过:

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

In GraphiQL: 在GraphiQL中:

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

Response: 响应:

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

I am not sure if the problem is with my lack of JS knowledge, or that Sequelize does not return much using the MySQL dialect, or somewhere in between. 我不确定问题是由于我缺乏JS知识,还是Sequelize使用MySQL方言或其间的某个地方没有太多回报。

Hey i just ran into this last night... i did it like this in my resolver 嘿,我刚刚碰到这个晚上......我在我的解析器中这样做了

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

and my mutation 和我的突变

addUserProfileCertification(input: ProfileCertificationInput!): Boolean

GraphiQL result looks like GraphiQL结果看起来像

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

You can easily return the whole model if you want though by return a findOne with the id from your args at the bottom of your resolver like... 如果你想要的话,你可以轻松返回整个模型,但是你需要从你的解析器底部的args返回一个带有id的findOne ...

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;
    },

You just need to tell your mutation to expect a Payment type rather than a Boolean, and you can refine what you want to pass back to the client by selecting only certain fields from payment as part of the mutation that you enter into GraphiQL 您只需要告诉您的变异需要付款类型而不是布尔值,并且您可以通过仅选择付款中的某些字段作为您输入GraphiQL的变体的一部分来优化您要传递回客户端的内容

This eventually ended up working for me, changing the Resolver for this to: 这最终最终为我工作,将此解析器更改为:

updatePaymentStatus: async (parent, {id, processed}, {models}) => {
            try {
                const foundPayment = await models.Payment.findByPk(id)
                if (foundPayment){
                models.Payment.update({processed: id}, {where: {id: id}})

                return true;
                }
                else{
                    return false;
                }
            }
            catch (e) {
                console.log(e);
                return false;
            }

        },

I wanted to be sure the payment id existed before running the update because the update would run regardless if the row existed or not. 我想确保在运行更新之前存在支付ID,因为无论行是否存在,更新都会运行。 I'm not sure if I even need the try catch, but I left it in there just in case. 我不确定我是否需要尝试捕捉,但我把它留在那里以防万一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM