Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update data in field pre hook #123

Closed
grimabe opened this issue May 15, 2016 · 3 comments
Closed

Update data in field pre hook #123

grimabe opened this issue May 15, 2016 · 3 comments

Comments

@grimabe
Copy link

grimabe commented May 15, 2016

In my user model I have a password field that I would like to hash when the user is created or updated.
I already achieve to do it with mongoose pre save hook.

But it appears to be only working when creating the document because the update mutation doesn't seems to use the model save method.

So I thought about using the field pre hook like below but I don't know how to update the value.

        password: {
            type: String,
            required: true,
            hooks: {
                pre: (next, root, args, request) => {
                    //replace  with hashed password
                    next();
                },
                post: (next) => next(`********`)
            }
        },

Is there a way to do that ?

Thank you

@tothandras
Copy link
Contributor

tothandras commented May 17, 2016

Hi @grimabe,
you can change the arguments like:

pre: (next, root, args, ...rest) => {
   // replace  with hashed password
   args.password = hash(args.password)
   next(root, args, ...rest)
}

Give it a try and let me know if it worked or not!

@grimabe
Copy link
Author

grimabe commented May 27, 2016

Hi @tothandras,
Thanks for the answer, I tried exactly the code you wrote but the field is still not modified in the database.

Do you have something else to try ?

@tothandras
Copy link
Contributor

tothandras commented Jul 26, 2016

Hi @grimabe,
sorry for the delay. I've just realised that the field hooks are for queries, not mutations. So this is what you need to do (using the example in the project) to change arguments for mutations:

const hooks = {
  mutation: {
    pre(next, args, context, info) {
      if (info.fieldName === 'updateUser') {
        args.name += ' MutationPreHook';
      }
      next(args, context, info);
    }
  }
};
const schema = getSchema([User], { hooks });

Let's see a user:

query {
  users {
    id,
    name
  }
}

image

Update its name:

mutation {
  updateUser(input: {id: "VXNlcjo1Nzk3YTA0NDdjZjhlMDQ4ODY5ZDRlNGQ=", name: "UserUpdated", clientMutationId: "0"}) {
    changedUser {
      id,
      name
    }
  }
}

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants