Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow pre-configured cache to be given as config option to Apollo Boost Client #3561

Merged
merged 3 commits into from
Jun 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/apollo-boost/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

### vNext

- Allow `cache` to be given as a configuration option to `ApolloBoost`.
[Issue #3220](https://github.com/apollographql/apollo-client/issues/3220)
[PR #3561](https://github.com/apollographql/apollo-client/pull/3561)
- Allow `headers` and `credentials` to be passed in as configuration
parameters to the `apollo-boost` `ApolloClient` constructor.
[PR #3098](https://github.com/apollographql/apollo-client/pull/3098)
Expand Down
2 changes: 1 addition & 1 deletion packages/apollo-boost/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"filesize": "npm run build && npm run build:browser"
},
"dependencies": {
"apollo-cache": "^1.1.9",
"apollo-cache-inmemory": "^1.2.2",
"apollo-client": "^2.3.2",
"apollo-link": "^1.0.6",
Expand All @@ -45,7 +46,6 @@
"devDependencies": {
"@types/graphql": "0.12.7",
"@types/jest": "22.2.3",
"apollo-cache": "^1.1.9",
"apollo-utilities": "^1.0.13",
"browserify": "15.2.0",
"fetch-mock": "6.4.3",
Expand Down
24 changes: 23 additions & 1 deletion packages/apollo-boost/src/__tests__/config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import ApolloClient, { gql } from '../';
import ApolloClient, { gql, InMemoryCache } from '../';
import { stripSymbols } from 'apollo-utilities';
import { HttpLink } from 'apollo-link-http';
import * as fetchMock from 'fetch-mock';
Expand Down Expand Up @@ -60,6 +60,28 @@ describe('config', () => {
});
});

it('throws if passed cache and cacheRedirects', () => {
const cache = new InMemoryCache();
const cacheRedirects = { Query: { foo: () => 'woo' } };

expect(_ => {
const client = new ApolloClient({
cache,
cacheRedirects,
});
}).toThrow('Incompatible cache configuration');
});

it('allows you to pass in cache', () => {
const cache = new InMemoryCache();

const client = new ApolloClient({
cache,
});

expect(client.cache).toBe(cache);
});

it('allows you to pass in cacheRedirects', () => {
const cacheRedirects = { Query: { foo: () => 'woo' } };

Expand Down
120 changes: 74 additions & 46 deletions packages/apollo-boost/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { HttpLink } from 'apollo-link-http';
import { withClientState, ClientStateConfig } from 'apollo-link-state';
import { onError, ErrorLink } from 'apollo-link-error';

import { ApolloCache } from 'apollo-cache';
import { InMemoryCache, CacheResolverMap } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
import ApolloClient from 'apollo-client';
Expand All @@ -23,62 +24,89 @@ export interface PresetConfig {
clientState?: ClientStateConfig;
onError?: ErrorLink.ErrorHandler;
cacheRedirects?: CacheResolverMap;
cache?: ApolloCache<any>;
}

export default class DefaultClient<TCache> extends ApolloClient<TCache> {
constructor(config: PresetConfig) {
const cache =
config && config.cacheRedirects
? new InMemoryCache({ cacheRedirects: config.cacheRedirects })
constructor(config: PresetConfig = {}) {
const {
request,
uri,
credentials,
headers,
fetchOptions,
clientState,
cacheRedirects,
onError: errorCallback,
} = config;

let { cache } = config;

if (cache && cacheRedirects) {
throw new Error(
'Incompatible cache configuration. If providing `cache` then ' +
'configure the provided instance with `cacheRedirects` instead.',
);
}

if (!cache) {
cache = cacheRedirects
? new InMemoryCache({ cacheRedirects })
: new InMemoryCache();
}

const stateLink =
config && config.clientState
? withClientState({ ...config.clientState, cache })
: false;
const stateLink = clientState
? withClientState({ ...clientState, cache })
: false;

const errorLink =
config && config.onError
? onError(config.onError)
: onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) console.log(`[Network error]: ${networkError}`);
});
const errorLink = errorCallback
? onError(errorCallback)
: onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
// tslint:disable-next-line
console.log(
`[GraphQL error]: Message: ${message}, Location: ` +
`${locations}, Path: ${path}`,
),
);
}
if (networkError) {
// tslint:disable-next-line
console.log(`[Network error]: ${networkError}`);
}
});

const requestHandler =
config && config.request
? new ApolloLink(
(operation, forward) =>
new Observable(observer => {
let handle: any;
Promise.resolve(operation)
.then(oper => config.request(oper))
.then(() => {
handle = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})
.catch(observer.error.bind(observer));
const requestHandler = request
? new ApolloLink(
(operation, forward) =>
new Observable(observer => {
let handle: any;
Promise.resolve(operation)
.then(oper => request(oper))
.then(() => {
handle = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})
.catch(observer.error.bind(observer));

return () => {
if (handle) handle.unsubscribe;
};
}),
)
: false;
return () => {
if (handle) {
handle.unsubscribe();
}
};
}),
)
: false;

const httpLink = new HttpLink({
uri: (config && config.uri) || '/graphql',
fetchOptions: (config && config.fetchOptions) || {},
credentials: (config && config.credentials) || 'same-origin',
headers: (config && config.headers) || {},
uri: uri || '/graphql',
fetchOptions: fetchOptions || {},
credentials: credentials || 'same-origin',
headers: headers || {},
});

const link = ApolloLink.from([
Expand Down