1.0.0 • Published 5 years ago

apollo-resolvers-effect v1.0.0

Weekly downloads
4
License
Apache
Repository
github
Last release
5 years ago

apollo-resolvers-effect

Coverage Status npm.io npm.io npm.io

Reactively add reusable logic in Apollostack's GraphQL server resolvers.

Overview

When setup a apollo server, some features have to implement same logic in a lot of resolvers, like "authorization", "push notification", etc. This package's goal is to turn those logic into effect, it can decrease duplicated logic and improve maintainability, in addition, there is need to rewrite original resolvers when using this package.

Installing

yarn add apollo-resolvers-effect

npm install apollo-resolvers-effect

Quick Start

// Create authorization effect
const checkAuthorizationEffect = (_p, _v, context, _i) => {
  if (context.user.role !== Role.Admin) {
    throw Error(`You don't have authorization on this operation`)
  }
}

// Log operation effect
const logAfterOperation = (_p, _v, _c, info) => {
  console.log(info.fieldName)
}

// Determine which operations need to add effects
const effects = [
  {
    type: 'All',
    afterEffects: [logAfterOperation]
  },
  {
    operationNames: ['deleteUser', 'updateUser', 'createUser'],
    beforeEffects: [checkAuthorizationEffect]
  }
]

// Create resolvers with effect
const resolversWithEffect = withEffect({
    resolvers,
    effects,
    effectErrorHandler: e => console.log(e)
  })

// Create server
const server = new ApolloServer({
  typeDefs,
  context: () => {
    const context = {
      // login user information
      user: fakeUsers[0]
    }
    return context
  },
  resolvers: resolversWithEffect
})