Resolvers

Resolvers

Resolver is a collection of functions that generate response for a GraphQL query. You can think of Resolvers like Controllers from REST. It basically handlers GraphQL query just like controllers where the endpoint has particular controller resolvers does the same thing but for query instead of an endpoint.

Lets take a look at one of an example in the project located at enatega-multivendor-api/graphql/resolvers/auth

createUser: async args => {
    try {
      const existingUser = await User.findOne({ email: args.userInput.email });
      if (existingUser) {
        throw new Error('email already registered.');
      }
      const hashedPassword = await bcrypt.hash(args.userInput.password, 12);
      const picture = args.userInput.picture ? saveImageToDisk(args.userInput.picture) : ''
      const user = new User({
        email: args.userInput.email,
        password: hashedPassword,
        phone: args.userInput.phone,
        name: args.userInput.name,
        picture: picture,
        location: {
          longitude: '',
          latitude: '',
          delivery_address: ''
        }
      });

      const result = await user.save();
      sendEmail(result.email, 'Account Creation', signupText, signupTemplate);
      const token = jwt.sign(
        { userId: result.id, email: result.email },
        'somesupersecretkey'
      );
      console.log({ ...result._doc, userId: result.id, token: token, tokenExpiration: 1 })
      return { ...result._doc, userId: result.id, token: token, tokenExpiration: 1 };
    } catch (err) {
      throw err;
    }
  }

createUser is one of the resolver functions it creates a new User just like in REST the parameter are found in args you may have noticed that in line 3 we have to call another object inside args called userInput this is the inputType for every query its a good practice to write its inputType the rest of the code is pretty simple.

Last updated