{"id":15313314,"url":"https://github.com/thebigredgeek/apollo-resolvers","last_synced_at":"2025-10-20T02:18:05.347Z","repository":{"id":14020019,"uuid":"75667214","full_name":"thebigredgeek/apollo-resolvers","owner":"thebigredgeek","description":"Expressive and composable resolvers for Apollostack's GraphQL server","archived":false,"fork":false,"pushed_at":"2025-04-04T22:02:22.000Z","size":131,"stargazers_count":430,"open_issues_count":17,"forks_count":41,"subscribers_count":12,"default_branch":"master","last_synced_at":"2025-04-13T14:00:02.799Z","etag":null,"topics":["apollo-client","apollo-server","apollostack-graphql-server","child-resolver","composible-resolvers","graphql","javascript","nodejs","parent-resolver","resolver"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thebigredgeek.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-12-05T21:20:23.000Z","updated_at":"2024-11-23T02:10:28.000Z","dependencies_parsed_at":"2024-02-29T14:48:37.853Z","dependency_job_id":"b657fdec-7709-40bc-8121-721864b89f38","html_url":"https://github.com/thebigredgeek/apollo-resolvers","commit_stats":{"total_commits":84,"total_committers":16,"mean_commits":5.25,"dds":0.5357142857142857,"last_synced_commit":"17e1f77ce9e21051e0784f5b8a6ca724b8cd8a2c"},"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thebigredgeek%2Fapollo-resolvers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thebigredgeek%2Fapollo-resolvers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thebigredgeek%2Fapollo-resolvers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thebigredgeek%2Fapollo-resolvers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thebigredgeek","download_url":"https://codeload.github.com/thebigredgeek/apollo-resolvers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248724585,"owners_count":21151560,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["apollo-client","apollo-server","apollostack-graphql-server","child-resolver","composible-resolvers","graphql","javascript","nodejs","parent-resolver","resolver"],"created_at":"2024-10-01T08:41:24.070Z","updated_at":"2025-10-20T02:18:00.301Z","avatar_url":"https://github.com/thebigredgeek.png","language":"JavaScript","funding_links":[],"categories":["Libraries"],"sub_categories":["JavaScript Libraries"],"readme":"# apollo-resolvers\nExpressive and composable resolvers for Apollostack's GraphQL server\n\n[![NPM](https://nodei.co/npm/apollo-resolvers.png?downloads=true\u0026downloadRank=true\u0026stars=true)](https://nodei.co/npm/apollo-resolvers/)\n\n[![CircleCI](https://circleci.com/gh/thebigredgeek/apollo-resolvers/tree/master.svg?style=shield)](https://circleci.com/gh/thebigredgeek/apollo-resolvers/tree/master)\n\n## Overview\n\nWhen 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.\n\n`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.\n\nWith `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.\n\nIn 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.\n\n## Example from Apollo Day\n\n[![Authentication and Error Handling in GraphQL](https://img.youtube.com/vi/xaorvBjCE7A/0.jpg)](https://www.youtube.com/watch?v=xaorvBjCE7A)\n\n## Quick start\n\nInstall the package:\n\n```bash\nnpm install apollo-resolvers\n```\n\nCreate a base resolver for last-resort error masking:\n\n```javascript\nimport { createResolver } from 'apollo-resolvers';\nimport { createError, isInstance } from 'apollo-errors';\n\nconst UnknownError = createError('UnknownError', {\n  message: 'An unknown error has occurred!  Please try again later'\n});\n\nexport const baseResolver = createResolver(\n   //incoming requests will pass through this resolver like a no-op\n  null,\n\n  /*\n    Only mask outgoing errors that aren't already apollo-errors,\n    such as ORM errors etc\n  */\n  (root, args, context, error) =\u003e isInstance(error) ? error : new UnknownError()\n);\n```\n\nCreate a few child resolvers for access control:\n```javascript\nimport { createError } from 'apollo-errors';\n\nimport { baseResolver } from './baseResolver';\n\nconst ForbiddenError = createError('ForbiddenError', {\n  message: 'You are not allowed to do this'\n});\n\nconst AuthenticationRequiredError = createError('AuthenticationRequiredError', {\n  message: 'You must be logged in to do this'\n});\n\nexport const isAuthenticatedResolver = baseResolver.createResolver(\n  // Extract the user from context (undefined if non-existent)\n  (root, args, { user }, info) =\u003e {\n    if (!user) throw new AuthenticationRequiredError();\n  }\n);\n\nexport const isAdminResolver = isAuthenticatedResolver.createResolver(\n  // Extract the user and make sure they are an admin\n  (root, args, { user }, info) =\u003e {\n    /*\n      If thrown, this error will bubble up to baseResolver's\n      error callback (if present).  If unhandled, the error is returned to\n      the client within the `errors` array in the response.\n    */\n    if (!user.isAdmin) throw new ForbiddenError();\n\n    /*\n      Since we aren't returning anything from the\n      request resolver, the request will continue on\n      to the next child resolver or the response will\n      return undefined if no child exists.\n    */\n  }\n)\n```\n\nCreate a profile update resolver for our user type:\n```javascript\nimport { isAuthenticatedResolver } from './acl';\nimport { createError } from 'apollo-errors';\n\nconst NotYourUserError = createError('NotYourUserError', {\n  message: 'You cannot update the profile for other users'\n});\n\nconst updateMyProfile = isAuthenticatedResolver.createResolver(\n  (root, { input }, { user, models: { UserModel } }, info) =\u003e {\n    /*\n      If thrown, this error will bubble up to isAuthenticatedResolver's error callback\n      (if present) and then to baseResolver's error callback.  If unhandled, the error\n      is returned to the client within the `errors` array in the response.\n    */\n    if (!user.isAdmin \u0026\u0026 input.id !== user.id) throw new NotYourUserError();\n    return UserModel.update(input);\n  }\n);\n\nexport default {\n  Mutation: {\n    updateMyProfile\n  }\n};\n```\n\nCreate an admin resolver:\n```javascript\nimport { createError, isInstance } from 'apollo-errors';\nimport { isAuthenticatedResolver, isAdminResolver } from './acl';\n\nconst ExposedError = createError('ExposedError', {\n  message: 'An unknown error has occurred'\n});\n\nconst banUser = isAdminResolver.createResolver(\n  (root, { input }, { models: { UserModel } }, info) =\u003e UserModel.ban(input),\n  (root, args, context, error) =\u003e {\n    /*\n      For admin users, let's tell the user what actually broke\n      in the case of an unhandled exception\n    */\n\n    if (!isInstance(error)) throw new ExposedError({\n      // overload the message\n      message: error.message\n    });\n  }\n);\n\nexport default {\n  Mutation: {\n    banUser\n  }\n};\n```\n\nCombine your resolvers into a single definition ready for use by `graphql-tools`:\n```javascript\nimport { combineResolvers } from 'apollo-resolvers';\n\nimport User from './user';\nimport Admin from './admin';\n\n/*\n  This combines our multiple resolver definition\n  objects into a single definition object\n*/\nconst resolvers = combineResolvers([\n  User,\n  Admin\n]);\n\nexport default resolvers;\n```\n\nConditional resolvers:\n```javascript\nimport { and, or } from 'apollo-resolvers';\n\nimport isFooResolver from './foo';\nimport isBarResolver from './bar';\n\nconst banResolver = (root, { input }, { models: { UserModel } }, info)=\u003e UserModel.ban(input);\n\n// Will execute banResolver if either isFooResolver or isBarResolver successfully resolve\n// If none of the resolvers succeed, the error from the last conditional resolver will\n// be returned\nconst orBanResolver = or(isFooResolver, isBarResolver)(banResolver);\n\n// Will execute banResolver if both isFooResolver and isBarResolver successfully resolve\n// If one of the condition resolvers throws an error, it will stop the execution and\n// return the error\nconst andBanResolver = and(isFooResolver, isBarResolver)(banResolver);\n\n// In both cases, conditions are evaluated from left to right\n```\n\n## Resolver context\n\nResolvers 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:\n\n``` javascript\nimport express from 'express';\nimport bodyParser from 'body-parser';\nimport { GraphQLError } from 'graphql';\nimport { graphqlExpress } from 'apollo-server-express';\nimport { createExpressContext } from 'apollo-resolvers';\nimport { formatError as apolloFormatError, createError } from 'apollo-errors';\n\nimport { UserModel } from './models/user';\nimport schema from './schema';\n\nconst UnknownError = createError('UnknownError', {\n  message: 'An unknown error has occurred.  Please try again later'\n});\n\nconst formatError = error =\u003e {\n  let e = apolloFormatError(error);\n\n  if (e instanceof GraphQLError) {\n    e = apolloFormatError(new UnknownError({\n      data: {\n        originalMessage: e.message,\n        originalError: e.name\n      }\n    }));\n  }\n\n  return e;\n};\n\nconst app = express();\n\napp.use(bodyParser.json());\n\napp.use((req, res, next) =\u003e {\n  req.user = null; // fetch the user making the request if desired\n  next();\n});\n\napp.post('/graphql', graphqlExpress((req, res) =\u003e {\n  const user = req.user;\n\n  const models = {\n    User: new UserModel(user)\n  };\n\n  const context = createExpressContext({\n    models,\n    user\n  }, res);\n\n  return {\n    schema,\n    formatError, // error formatting via apollo-errors\n    context // our resolver context\n  };\n}));\n\nexport default app;\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthebigredgeek%2Fapollo-resolvers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthebigredgeek%2Fapollo-resolvers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthebigredgeek%2Fapollo-resolvers/lists"}