Getting Started
Essentials

API Server Resolvers

Resolvers

A group of operations known as a resolver creates a response to a GraphQL query. Resolvers are comparable to REST’s Controllers. In essence, it handles GraphQL queries similarly to controllers, where each endpoint has a unique controller resolver that accomplishes the same task but for queries rather than an endpoint. Let’s take a look at one 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;
    }
  }

One of the resolver functions is called createUser; it creates a new User similarly to how REST works. You may have noticed that in line 3, we have to call another object inside args called userInput; this is the inputType for each query; it is best practice to write its inputType. The rest of the code is fairly straightforward.

On this page