Skip to content

Commit 9c6cc6f

Browse files
committed
better comments, doc update, fix for false/0/empty string return values on resolvers
1 parent 7c50da6 commit 9c6cc6f

File tree

8 files changed

+236
-29
lines changed

8 files changed

+236
-29
lines changed

README.md

Lines changed: 153 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,17 @@ Expressive and composable resolvers for Apollostack's GraphQL server
55

66
[![CircleCI](https://circleci.com/gh/thebigredgeek/apollo-resolvers/tree/master.svg?style=shield)](https://circleci.com/gh/thebigredgeek/apollo-resolvers/tree/master) [![Beerpay](https://beerpay.io/thebigredgeek/apollo-resolvers/badge.svg?style=beer-square)](https://beerpay.io/thebigredgeek/apollo-resolvers) [![Beerpay](https://beerpay.io/thebigredgeek/apollo-resolvers/make-wish.svg?style=flat-square)](https://beerpay.io/thebigredgeek/apollo-resolvers?focus=wish)
77

8-
## Installation and usage
8+
## Overview
9+
10+
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 authentication and authorization checking code in a vast majority of their resolver functions, as well as error handling logic to shield the client for 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.
11+
12+
`apollo-resolvers` provides a pattern for creating resolvers that works essentially like reactive middleware. As a developer, you create a chain of resolvers to satisfy small bits of the overall problem of taking a GraphQL request and binding it to a model method or some other form of business logic.
13+
14+
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.
15+
16+
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.
17+
18+
## Quick start
919

1020
Install the package:
1121

@@ -19,14 +29,18 @@ Create a base resolver for last-resort error masking:
1929
import { createResolver } from 'apollo-resolvers';
2030
import { createError, isInstance } from 'apollo-errors';
2131

22-
const UnknownError = createError({
32+
const UnknownError = createError('UnknownError', {
2333
message: 'An unknown error has occurred! Please try again later'
2434
});
2535

2636
export const baseResolver = createResolver(
27-
null, // don't pass a resolver function, we only care about errors
37+
//incomine requests will pass through this resolver
38+
null,
2839

29-
// Only mask errors that aren't already apollo-errors, such as ORM errors etc
40+
/*
41+
Only mask outgoing errors that aren't already apollo-errors,
42+
such as ORM errors etc
43+
*/
3044
(root, args, context, error) => isInstance(error) ? error : new UnknownError()
3145
);
3246
```
@@ -37,11 +51,11 @@ import { createError } from 'apollo-errors';
3751

3852
import baseResolver from './baseResolver';
3953

40-
const ForbiddenError = createError({
54+
const ForbiddenError = createError('ForbiddenError', {
4155
message: 'You are not allowed to do this'
4256
});
4357

44-
const AuthenticationRequiredError = createError({
58+
const AuthenticationRequiredError = createError('AuthenticationRequiredError', {
4559
message: 'You must be logged in to do this'
4660
});
4761

@@ -55,35 +69,160 @@ export const isAuthenticatedResolver = baseResolver.createResolver(
5569
export const isAdminResolver = isAuthenticatedResolver.createResolver(
5670
// Extract the user and make sure they are an admin
5771
(root, args, { user }) => {
72+
/*
73+
If thrown, this error will bubble up to baseResolver's
74+
error callback (if present). If unhandled, the error is returned to
75+
the client within the `errors` array in the response.
76+
*/
5877
if (!user.isAdmin) throw new ForbiddenError();
78+
79+
/*
80+
Since we aren't returning anything from the
81+
request resolver, the request will continue on
82+
to the next child resolver or the response will
83+
return undefined if no child exists.
84+
*/
5985
}
6086
)
6187
```
6288

63-
Create a few real-work resolvers for our app:
64-
89+
Create a profile update resolver for our user type:
6590
```javascript
66-
import { isAuthenticatedResolver, isAdminResolver } from './acl';
91+
import { isAuthenticatedResolver } from './acl';
6792
import { createError } from 'apollo-errors';
6893

69-
const NotYourUserError = createError({
94+
const NotYourUserError = createError('NotYourUserError', {
7095
message: 'You cannot update the profile for other users'
7196
});
7297

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

110+
export default {
111+
Mutation: {
112+
updateMyProfile
113+
}
114+
};
115+
```
116+
117+
Create an admin resolver:
118+
```javascript
119+
import { createError, isInstance } from 'apollo-errors';
120+
import { isAuthenticatedResolver, isAdminResolver } from './acl';
121+
122+
const ExposedError = createError('ExposedError', {
123+
message: 'An unknown error has occurred'
124+
});
125+
80126
const banUser = isAdminResolver.createResolver(
81-
(root, { input }, { models: { UserModel } }) => UserModel.ban(input)
127+
(root, { input }, { models: { UserModel } }) => UserModel.ban(input),
128+
(root, args, context, error) => {
129+
/*
130+
For admin users, let's tell the user what actually broke
131+
in the case of an unhandled exception
132+
*/
133+
134+
if (!isInstance(error)) throw new ExposedError({
135+
// overload the message
136+
message: error.message
137+
});
138+
}
82139
);
140+
141+
export default {
142+
Mutation: {
143+
banUser
144+
}
145+
};
83146
```
84147

148+
Combine your resolvers into a single definition ready for use by `graphql-tools`:
149+
```javascript
150+
import { combineResolvers } from 'apollo-resolvers';
151+
152+
import { updateMyProfile } from './user';
153+
import { banUser } from './admin';
85154

86-
### To-do
155+
/*
156+
This combines our multiple resolver definition
157+
objects into a single definition object
158+
*/
159+
const resolvers = combineResolvers([
160+
updateMyProfile,
161+
banUser
162+
]);
87163

88-
* Finish docs
89-
* Add more integration tests
164+
export default resolvers;
165+
```
166+
167+
## Resolver context
168+
169+
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:
170+
171+
``` javascript
172+
import express from 'express';
173+
import bodyParser from 'body-parser';
174+
import { graphqlExpress } from 'graphql-server-express';
175+
import { createExpressContext } from 'apollo-resolvers';
176+
import { formatError as apolloFormatError, createError } from 'apollo-errors';
177+
178+
import { UserModel } from './models/user';
179+
import schema from './schema';
180+
181+
const UnknownError = createError('UnknownError', {
182+
message: 'An unknown error has occurred. Please try again later'
183+
});
184+
185+
const formatError = error => {
186+
let e = apolloFormatError(error);
187+
188+
if (e instanceof GraphQLError) {
189+
e = apolloFormatError(new UnknownError({
190+
data: {
191+
originalMessage: e.message,
192+
originalError: e.name
193+
}
194+
}));
195+
}
196+
197+
return e;
198+
};
199+
200+
const app = express();
201+
202+
app.use(bodyParser.json());
203+
204+
app.use((req, res, next) => {
205+
req.user = null; // fetch the user making the request if desired
206+
});
207+
208+
app.post('/graphql', graphqlExpress((req, res) => {
209+
const user = req.user;
210+
211+
const models = {
212+
User: new UserModel(user)
213+
};
214+
215+
const context = createExpressContext({
216+
models,
217+
user
218+
}, res);
219+
220+
return {
221+
schema,
222+
formatError, // error formatting via apollo-errors
223+
context // our resolver context
224+
};
225+
}));
226+
227+
export default app;
228+
```

circle.yml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ machine:
44

55
dependencies:
66
override:
7-
- make environment
8-
- make dependencies
7+
- make configure
98

109
test:
1110
override:

src/context.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,30 @@
11
import assert from 'assert';
22

33
export const createExpressContext = (data, res) => {
4+
data = data || {};
5+
data.user = data.user || null;
6+
data.models = data.models || {};
47
const context = new Context(data);
58
if (res) {
69
assert(typeof res.once === 'function', 'createExpressContext takes response as second parameter that implements "res.once"');
10+
// Bind the response finish event to the context disposal method
711
res.once('finish', () => context && context.dispose ? context.dispose() : null);
812
}
913
return context;
1014
};
1115

1216
export class Context {
13-
constructor ({ models, user }) {
14-
this.models = models;
15-
this.user = user;
17+
constructor (data) {
18+
Object.keys(data).forEach(key => {
19+
this[key] = data[key]
20+
});
1621
}
1722
dispose () {
1823
const models = this.models;
1924
const user = this.user;
2025
this.models = null;
2126
this.user = null;
27+
// Call dispose on every attached model that contains a dispose method
2228
Object.keys(models).forEach((key) => models[key].dispose ? models[key].dispose() : null);
2329
}
2430
}

src/promise.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import assert from 'assert';
33
// Expose the Promise constructor so that it can be overwritten by a different lib like Bluebird
44
let p = Promise;
55

6+
// Allow overload with compliant promise lib
67
export const usePromise = pLib => {
78
assert(pLib && pLib.prototype, 'apollo-errors#usePromise expects a valid Promise library');
89
assert(!!pLib.resolve, 'apollo-errors#usePromise expects a Promise library that implements static method "Promise.resolve"');
@@ -13,4 +14,5 @@ export const usePromise = pLib => {
1314
p = pLib;
1415
};
1516

17+
// Return the currently selected promise lib
1618
export const getPromise = () => p;

src/resolver.js

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
11
import { getPromise } from './promise';
2-
import { isFunction, Promisify } from './util';
2+
import { isFunction, Promisify, isNotNullOrUndefined } from './util';
33

44

55
export const createResolver = (resFn, errFn) => {
66
const Promise = getPromise();
77
const baseResolver = (root, args = {}, context = {}) => {
8+
// Return resolving promise with `null` if the resolver function param is not a function
89
if (!isFunction(resFn)) return Promise.resolve(null);
910
return Promisify(resFn)(root, args, context).catch(e => {
11+
// On error, check if there is an error handler. If not, throw the original error
1012
if (!isFunction(errFn)) throw e;
13+
// Call the error handler.
1114
return Promisify(errFn)(root, args, context, e).then(parsedError => {
15+
// If it resolves, throw the resolving value or the original error.
1216
throw parsedError || e
1317
}, parsedError => {
18+
// If it rejects, throw the rejecting value or the original error
1419
throw parsedError || e
1520
});
1621
});
@@ -20,24 +25,35 @@ export const createResolver = (resFn, errFn) => {
2025
const Promise = getPromise();
2126

2227
const childResFn = (root, args, context) => {
28+
// Start with either the parent resolver function or a no-op (returns null)
2329
const entry = isFunction(resFn) ? Promisify(resFn)(root, args, context) : Promise.resolve(null);
2430
return entry.then(r => {
25-
if (r) return r;
31+
// If the parent returns a value, continue
32+
if (isNotNullOrUndefined(r)) return r;
33+
// Call the child resolver function or a no-op (returns null)
2634
return isFunction(cResFn) ? Promisify(cResFn)(root, args, context) : Promise.resolve(null);
2735
});
2836
};
2937

3038
const childErrFn = (root, args, context, err) => {
39+
// Start with either the child error handler or a no-op (returns null)
3140
const entry = isFunction(cErrFn) ? Promisify(cErrFn)(root, args, context, err) : Promise.resolve(null);
32-
41+
3342
return entry.then(r => {
34-
if (r) throw r;
43+
// If the child returns a value, throw it
44+
if (isNotNullOrUndefined(r)) throw r;
45+
// Call the parent error handler or a no-op (returns null)
3546
return isFunction(errFn) ? Promisify(errFn)(root, args, context, err).then(e => {
47+
// If it resolves, throw the resolving value or the original error
48+
throw e || err;
49+
}, e => {
50+
// If it rejects, throw the rejecting value or the original error
3651
throw e || err;
37-
}) : Promise.resolve(null)
52+
}) : Promise.resolve(null);
3853
});
3954
};
40-
55+
56+
// Create the child resolver and return it
4157
return createResolver(childResFn, childErrFn);
4258
}
4359

src/util.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,5 @@ export const Promisify = fn => {
1212
}
1313
});
1414
};
15+
16+
export const isNotNullOrUndefined = val => val !== null && val !== undefined;

test/unit/context_spec.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,24 @@ import { createExpressContext, Context } from '../../src/context';
77
describe('(unit) src/context.js', () => {
88
describe('createExpressContext', () => {
99
it('returns a context', () => {
10-
const models = {};
11-
const user = {};
10+
const models = {
11+
bar: 'foo'
12+
};
13+
const user = {
14+
id: '123'
15+
};
16+
const other = {
17+
foo: 'bar'
18+
};
1219
const context = createExpressContext({
1320
models,
14-
user
21+
user,
22+
other
1523
})
1624
expect(context instanceof Context).to.be.true;
1725
expect(context.user).to.equal(user);
1826
expect(context.models).to.equal(models);
27+
expect(context.other).to.equal(other);
1928
});
2029
describe('returned context', () => {
2130
let models = null

0 commit comments

Comments
 (0)