简体   繁体   中英

Sequelize with GraphQl: How to update fields using mutation

I'm using a stack of koa2, sequelize and graphql. I wan't to change the state field of the users model using graphql mutation and return the changed object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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