All Projects → boltsource → Apollo Resolvers

boltsource / Apollo Resolvers

Licence: mit
Expressive and composable resolvers for Apollostack's GraphQL server

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Apollo Resolvers

Create Social Network
An educational project, demonstrating how to build a large scalable project with Javascript.
Stars: ✭ 853 (+99.3%)
Mutual labels:  graphql, apollo-client, apollo-server
apollo-resolvers
Expressive and composable resolvers for Apollostack's GraphQL server
Stars: ✭ 434 (+1.4%)
Mutual labels:  resolver, apollo-client, apollo-server
Apollo Errors
Machine-readable custom errors for Apollostack's GraphQL server
Stars: ✭ 405 (-5.37%)
Mutual labels:  graphql, apollo-client, apollo-server
Fullstack Tutorial
🚀 The Apollo platform tutorial app
Stars: ✭ 1,007 (+135.28%)
Mutual labels:  graphql, apollo-client, apollo-server
Chatty
A WhatsApp clone with React Native and Apollo (Tutorial)
Stars: ✭ 481 (+12.38%)
Mutual labels:  graphql, apollo-client, apollo-server
Awesome Apollo Graphql
A curated list of amazingly awesome things regarding Apollo GraphQL ecosystem 🌟
Stars: ✭ 126 (-70.56%)
Mutual labels:  graphql, apollo-client, apollo-server
kontent-boilerplate-express-apollo
Kontent Boilerplate for development of Express application using Apollo server and GraphQL.
Stars: ✭ 21 (-95.09%)
Mutual labels:  apollo-client, apollo-server
now-course
Proyecto para el curso de Now.sh en Platzi
Stars: ✭ 19 (-95.56%)
Mutual labels:  apollo-client, apollo-server
Graphql Resolvers
🔌 Resolver composition library for GraphQL.
Stars: ✭ 274 (-35.98%)
Mutual labels:  graphql, resolver
Fullstack Apollo Express Mongodb Boilerplate
💥A sophisticated GraphQL with Apollo, Express and MongoDB boilerplate project.
Stars: ✭ 301 (-29.67%)
Mutual labels:  apollo-client, apollo-server
Apollo Client
🚀  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
Stars: ✭ 17,070 (+3888.32%)
Mutual labels:  graphql, apollo-client
Apollo Link Firebase
🔥 🔗 apollo-link-firebase provides you a simple way to use Firebase with graphQL.
Stars: ✭ 415 (-3.04%)
Mutual labels:  graphql, apollo-client
les-chat
Real-time messenger with private, public & group chat. Made using PERN + GraphQL stack.
Stars: ✭ 48 (-88.79%)
Mutual labels:  apollo-client, apollo-server
Ember Apollo Client
🚀 An ember-cli addon for Apollo Client and GraphQL
Stars: ✭ 257 (-39.95%)
Mutual labels:  graphql, apollo-client
apollo-errors
Machine-readable custom errors for Apollostack's GraphQL server
Stars: ✭ 408 (-4.67%)
Mutual labels:  apollo-client, apollo-server
Graphcms Examples
Example projects to help you get started with GraphCMS
Stars: ✭ 295 (-31.07%)
Mutual labels:  graphql, apollo-server
Apollo Storybook Decorator
Wrap your storybook environment with Apollo Client, provide mocks for isolated UI testing with GraphQL
Stars: ✭ 333 (-22.2%)
Mutual labels:  graphql, apollo-client
Next Shopify Storefront
🛍 A real-world Shopping Cart built with TypeScript, NextJS, React, Redux, Apollo Client, Shopify Storefront GraphQL API, ... and Material UI.
Stars: ✭ 317 (-25.93%)
Mutual labels:  graphql, apollo-client
Persistgraphql
A build tool for GraphQL projects.
Stars: ✭ 409 (-4.44%)
Mutual labels:  graphql, apollo-client
Firestore Apollo Graphql
An example of a GraphQL setup with a Firebase Firestore backend. Uses Apollo Engine/Server 2.0 and deployed to Google App Engine.
Stars: ✭ 371 (-13.32%)
Mutual labels:  graphql, apollo-server

apollo-resolvers

Expressive and composable resolvers for Apollostack's GraphQL server

NPM

CircleCI Beerpay Beerpay

Overview

When standing up a GraphQL backend, one of the first design decisions you will undoubtedly need to make is how you will handle authentication, authorization, and errors. GraphQL resolvers present an entirely new paradigm that existing patterns for RESTful APIs fail to adequately address. Many developers end up writing duplicitous authorization checks in a vast majority of their resolver functions, as well as error handling logic to shield the client from encountering exposed internal errors. The goal of apollo-resolvers is to simplify the developer experience in working with GraphQL by abstracting away many of these decisions into a nice, expressive design pattern.

apollo-resolvers provides a pattern for creating resolvers that work, essentially, like reactive middleware. By creating a chain of resolvers to satisfy individual parts of the overall problem, you are able to compose elegant streams that take a GraphQL request and bind it to a model method or some other form of business logic with authorization checks and error handling baked right in.

With apollo-resolvers, data flows between composed resolvers in a natural order. Requests flow down from parent resolvers to child resolvers until they reach a point that a value is returned or the last child resolver is reached. Thrown errors bubble up from child resolvers to parent resolvers until an additional transformed error is either thrown or returned from an error callback or the last parent resolver is reached.

In addition to the design pattern that apollo-resolvers provides for creating expressive and composible resolvers, there are also several provided helper methods and classes for handling context creation and cleanup, combining resolver definitions for presentation to graphql-tools via makeExecutableSchema, and more.

Example from Apollo Day

Authentication and Error Handling in GraphQL

Quick start

Install the package:

npm install apollo-resolvers

Create a base resolver for last-resort error masking:

import { createResolver } from 'apollo-resolvers';
import { createError, isInstance } from 'apollo-errors';

const UnknownError = createError('UnknownError', {
  message: 'An unknown error has occurred!  Please try again later'
});

export const baseResolver = createResolver(
   //incoming requests will pass through this resolver like a no-op
  null,

  /*
    Only mask outgoing errors that aren't already apollo-errors,
    such as ORM errors etc
  */
  (root, args, context, error) => isInstance(error) ? error : new UnknownError()
);

Create a few child resolvers for access control:

import { createError } from 'apollo-errors';

import { baseResolver } from './baseResolver';

const ForbiddenError = createError('ForbiddenError', {
  message: 'You are not allowed to do this'
});

const AuthenticationRequiredError = createError('AuthenticationRequiredError', {
  message: 'You must be logged in to do this'
});

export const isAuthenticatedResolver = baseResolver.createResolver(
  // Extract the user from context (undefined if non-existent)
  (root, args, { user }, info) => {
    if (!user) throw new AuthenticationRequiredError();
  }
);

export const isAdminResolver = isAuthenticatedResolver.createResolver(
  // Extract the user and make sure they are an admin
  (root, args, { user }, info) => {
    /*
      If thrown, this error will bubble up to baseResolver's
      error callback (if present).  If unhandled, the error is returned to
      the client within the `errors` array in the response.
    */
    if (!user.isAdmin) throw new ForbiddenError();

    /*
      Since we aren't returning anything from the
      request resolver, the request will continue on
      to the next child resolver or the response will
      return undefined if no child exists.
    */
  }
)

Create a profile update resolver for our user type:

import { isAuthenticatedResolver } from './acl';
import { createError } from 'apollo-errors';

const NotYourUserError = createError('NotYourUserError', {
  message: 'You cannot update the profile for other users'
});

const updateMyProfile = isAuthenticatedResolver.createResolver(
  (root, { input }, { user, models: { UserModel } }, info) => {
    /*
      If thrown, this error will bubble up to isAuthenticatedResolver's error callback
      (if present) and then to baseResolver's error callback.  If unhandled, the error
      is returned to the client within the `errors` array in the response.
    */
    if (!user.isAdmin && input.id !== user.id) throw new NotYourUserError();
    return UserModel.update(input);
  }
);

export default {
  Mutation: {
    updateMyProfile
  }
};

Create an admin resolver:

import { createError, isInstance } from 'apollo-errors';
import { isAuthenticatedResolver, isAdminResolver } from './acl';

const ExposedError = createError('ExposedError', {
  message: 'An unknown error has occurred'
});

const banUser = isAdminResolver.createResolver(
  (root, { input }, { models: { UserModel } }, info) => UserModel.ban(input),
  (root, args, context, error) => {
    /*
      For admin users, let's tell the user what actually broke
      in the case of an unhandled exception
    */

    if (!isInstance(error)) throw new ExposedError({
      // overload the message
      message: error.message
    });
  }
);

export default {
  Mutation: {
    banUser
  }
};

Combine your resolvers into a single definition ready for use by graphql-tools:

import { combineResolvers } from 'apollo-resolvers';

import User from './user';
import Admin from './admin';

/*
  This combines our multiple resolver definition
  objects into a single definition object
*/
const resolvers = combineResolvers([
  User,
  Admin
]);

export default resolvers;

Conditional resolvers:

import { and, or } from 'apollo-resolvers';

import isFooResolver from './foo';
import isBarResolver from './bar';

const banResolver = (root, { input }, { models: { UserModel } }, info)=> UserModel.ban(input);

// Will execute banResolver if either isFooResolver or isBarResolver successfully resolve
// If none of the resolvers succeed, the error from the last conditional resolver will
// be returned
const orBanResolver = or(isFooResolver, isBarResolver)(banResolver);

// Will execute banResolver if both isFooResolver and isBarResolver successfully resolve
// If one of the condition resolvers throws an error, it will stop the execution and
// return the error
const andBanResolver = and(isFooResolver, isBarResolver)(banResolver);

// In both cases, conditions are evaluated from left to right

Resolver context

Resolvers are provided a mutable context object that is shared between all resolvers for a given request. A common pattern with GraphQL is inject request-specific model instances into the resolver context for each request. Models frequently reference one another, and unbinding circular references can be a pain. apollo-resolvers provides a request context factory that allows you to bind context disposal to server responses, calling a dispose method on each model instance attached to the context to do any sort of required reference cleanup necessary to avoid memory leaks:

import express from 'express';
import bodyParser from 'body-parser';
import { GraphQLError } from 'graphql';
import { graphqlExpress } from 'apollo-server-express';
import { createExpressContext } from 'apollo-resolvers';
import { formatError as apolloFormatError, createError } from 'apollo-errors';

import { UserModel } from './models/user';
import schema from './schema';

const UnknownError = createError('UnknownError', {
  message: 'An unknown error has occurred.  Please try again later'
});

const formatError = error => {
  let e = apolloFormatError(error);

  if (e instanceof GraphQLError) {
    e = apolloFormatError(new UnknownError({
      data: {
        originalMessage: e.message,
        originalError: e.name
      }
    }));
  }

  return e;
};

const app = express();

app.use(bodyParser.json());

app.use((req, res, next) => {
  req.user = null; // fetch the user making the request if desired
  next();
});

app.post('/graphql', graphqlExpress((req, res) => {
  const user = req.user;

  const models = {
    User: new UserModel(user)
  };

  const context = createExpressContext({
    models,
    user
  }, res);

  return {
    schema,
    formatError, // error formatting via apollo-errors
    context // our resolver context
  };
}));

export default app;
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].