简体   繁体   English

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

[英]Sequelize with GraphQl: How to update fields using mutation

I'm using a stack of koa2, sequelize and graphql. 我正在使用一堆koa2,sequelize和graphql。 I wan't to change the state field of the users model using graphql mutation and return the changed object. 我不想使用graphql突变来更改用户模型的状态字段,并返回更改后的对象。

Currently my mutation looks like this: 目前,我的变异如下所示:

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

And that's the corresponding query: 这就是相应的查询:

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

It's working, but I'm pretty sure there are better solutions for this. 它正在工作,但是我很确定对此有更好的解决方案。

I would avoid trying to use graphql-sequelize's resolver helper for a mutation. 我会避免尝试使用graphql-sequelize的resolver帮助resolver进行突变。 Looking over the source for that library, it looks like it's really meant only for resolving queries and types. 查看该库的源代码,看起来它实际上仅是为了解析查询和类型。

I think a much cleaner approach would just to do something like this: 我认为更干净的方法只是做这样的事情:

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

I'm avoiding using update() here since that only returns the affected fields. 我在这里避免使用update() ,因为那只会返回受影响的字段。 If you ever decide to expand the fields returned by your mutation, this way you're returning the whole User Object and avoiding returning null for some fields. 如果您决定扩展由变异返回的字段,则可以通过这种方式返回整个用户对象,并避免为某些字段返回null。

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

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