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

Admin UI: cleaned up and simplified ApolloClient initialization #2830

Merged
merged 2 commits into from
May 6, 2020
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
5 changes: 5 additions & 0 deletions .changeset/clean-snails-teach.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystonejs/app-admin-ui': patch
---

Cleaned up and simplified ApolloClient initialization. The `cross-fetch` dependency was also updated to 3.0.4.
106 changes: 27 additions & 79 deletions packages/app-admin-ui/client/apolloClient.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { ApolloLink, Observable } from 'apollo-link';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { createUploadLink } from 'apollo-upload-client';
import { withClientState } from 'apollo-link-state';
import { onError } from 'apollo-link-error';

import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import ApolloClient from 'apollo-client';

import fetch from 'cross-fetch';

// This shouldn't be necessary, but it silences an annoying error from Apollo
// Client: https://github.com/apollographql/apollo-client/issues/3397#issuecomment-421433032
Expand All @@ -16,78 +16,26 @@ const fragmentMatcher = new IntrospectionFragmentMatcher({
},
});

const fetch = require('cross-fetch');

// Ejected from apollo-boost v0.1.4:
// https://github.com/apollographql/apollo-client/tree/4e2b2b90b181d9c1927a721de4e26e4ed3c86637/packages/apollo-boost
// (with Typescriptyness removed)
// Then modified to replace apollo-link-http with apollo-upload-client:
// https://github.com/jaydenseric/apollo-upload-client

class BoostClientWithUpload extends ApolloClient {
constructor(config) {
const cache =
config && config.cacheRedirects
? new InMemoryCache({ fragmentMatcher, cacheRedirects: config.cacheRedirects })
: new InMemoryCache({ fragmentMatcher });

const stateLink =
config && config.clientState ? withClientState({ ...config.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 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));

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

const httpLink = createUploadLink({
uri: (config && config.uri) || '/graphql',
fetch, // support mocking `fetch` in Cypress tests. See https://github.com/cypress-io/cypress/issues/687#issuecomment-384953881
fetchOptions: (config && config.fetchOptions) || {},
credentials: 'same-origin',
});

const link = ApolloLink.from([errorLink, requestHandler, stateLink, httpLink].filter(x => x));

// super hacky, we will fix the types eventually
super({ cache, link });
}
}

export default BoostClientWithUpload;
export const initApolloClient = ({ uri }) => {
const errorLink = 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 httpLink = createUploadLink({
uri,
fetch, // support mocking `fetch` in Cypress tests. See https://github.com/cypress-io/cypress/issues/687#issuecomment-384953881
credentials: 'same-origin',
});

return new ApolloClient({
link: ApolloLink.from([errorLink, httpLink]),
cache: new InMemoryCache({ fragmentMatcher }),
});
};
4 changes: 2 additions & 2 deletions packages/app-admin-ui/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Global } from '@emotion/core';

import { globalStyles } from '@arch-ui/theme';

import ApolloClient from './apolloClient';
import { initApolloClient } from './apolloClient';
import Nav from './components/Nav';
import ScrollToTop from './components/ScrollToTop';
import ConnectivityListener from './components/ConnectivityListener';
Expand Down Expand Up @@ -36,7 +36,7 @@ export const KeystoneAdminUI = () => {
hooks,
} = useAdminMeta();

const apolloClient = useMemo(() => new ApolloClient({ uri: apiPath }), [apiPath]);
const apolloClient = useMemo(() => initApolloClient({ uri: apiPath }), [apiPath]);

const routes = [
...pages
Expand Down
4 changes: 2 additions & 2 deletions packages/app-admin-ui/client/public.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Global } from '@emotion/core';

import { globalStyles } from '@arch-ui/theme';

import ApolloClient from './apolloClient';
import { initApolloClient } from './apolloClient';

import ConnectivityListener from './components/ConnectivityListener';
import { AdminMetaProvider, useAdminMeta } from './providers/AdminMeta';
Expand All @@ -27,7 +27,7 @@ import SigninPage from './pages/Signin';
const Keystone = () => {
const { authStrategy, apiPath, signoutPath, hooks } = useAdminMeta();

const apolloClient = useMemo(() => new ApolloClient({ uri: apiPath }), [apiPath]);
const apolloClient = useMemo(() => initApolloClient({ uri: apiPath }), [apiPath]);

return (
<HooksProvider hooks={hooks}>
Expand Down
3 changes: 1 addition & 2 deletions packages/app-admin-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,14 @@
"apollo-client": "^2.6.8",
"apollo-link": "^1.2.13",
"apollo-link-error": "^1.1.12",
"apollo-link-state": "^0.4.2",
"apollo-upload-client": "^12.1.0",
"apply-ref": "^0.2.0",
"babel-loader": "^8.0.5",
"babel-plugin-emotion": "^10.0.27",
"babel-preset-react-app": "^9.0.2",
"clipboard-copy": "^3.0.0",
"compression": "^1.7.4",
"cross-fetch": "^2.2.0",
"cross-fetch": "^3.0.4",
"css-loader": "^3.2.0",
"express": "^4.17.1",
"express-history-api-fallback": "^2.2.1",
Expand Down
27 changes: 2 additions & 25 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4685,14 +4685,6 @@ apollo-link-http@^1.3.2:
apollo-link-http-common "^0.2.11"
tslib "^1.9.3"

apollo-link-state@^0.4.2:
version "0.4.2"
resolved "https://registry.yarnpkg.com/apollo-link-state/-/apollo-link-state-0.4.2.tgz#ac00e9be9b0ca89eae0be6ba31fe904b80bbe2e8"
integrity sha512-xMPcAfuiPVYXaLwC6oJFIZrKgV3GmdO31Ag2eufRoXpvT0AfJZjdaPB4450Nu9TslHRePN9A3quxNueILlQxlw==
dependencies:
apollo-utilities "^1.0.8"
graphql-anywhere "^4.1.0-alpha.0"

[email protected]:
version "1.0.8"
resolved "https://registry.yarnpkg.com/apollo-link-ws/-/apollo-link-ws-1.0.8.tgz#ac1de8f29e92418728479a9a523af9f75b9ccc8b"
Expand Down Expand Up @@ -4834,7 +4826,7 @@ [email protected], apollo-utilities@^1.3.3:
ts-invariant "^0.4.0"
tslib "^1.10.0"

apollo-utilities@^1.0.1, apollo-utilities@^1.0.25, apollo-utilities@^1.0.8, apollo-utilities@^1.2.1:
apollo-utilities@^1.0.1, apollo-utilities@^1.2.1:
version "1.2.1"
resolved "https://registry.yarnpkg.com/apollo-utilities/-/apollo-utilities-1.2.1.tgz#1c3a1ebf5607d7c8efe7636daaf58e7463b41b3c"
integrity sha512-Zv8Udp9XTSFiN8oyXOjf6PMHepD4yxxReLsl6dPUy5Ths7jti3nmlBzZUOxuTWRwZn0MoclqL7RQ5UEJN8MAxg==
Expand Down Expand Up @@ -7534,22 +7526,14 @@ [email protected]:
node-fetch "2.1.2"
whatwg-fetch "2.0.4"

[email protected]:
[email protected], cross-fetch@^3.0.4:
version "3.0.4"
resolved "https://registry.yarnpkg.com/cross-fetch/-/cross-fetch-3.0.4.tgz#7bef7020207e684a7638ef5f2f698e24d9eb283c"
integrity sha512-MSHgpjQqgbT/94D4CyADeNoYh52zMkCX4pcJvPP5WqPsLFMKjr2TCMg381ox5qI0ii2dPwaLx/00477knXqXVw==
dependencies:
node-fetch "2.6.0"
whatwg-fetch "3.0.0"

cross-fetch@^2.2.0:
version "2.2.3"
resolved "https://registry.yarnpkg.com/cross-fetch/-/cross-fetch-2.2.3.tgz#e8a0b3c54598136e037f8650f8e823ccdfac198e"
integrity sha512-PrWWNH3yL2NYIb/7WF/5vFG3DCQiXDOVf8k3ijatbrtnwNuhMWLC7YF7uqf53tbTFDzHIUD8oITw4Bxt8ST3Nw==
dependencies:
node-fetch "2.1.2"
whatwg-fetch "2.0.4"

[email protected], cross-spawn@^5.0.1, cross-spawn@^5.1.0:
version "5.1.0"
resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-5.1.0.tgz#e8bd0efee58fcff6f8f94510a0a554bbfa235449"
Expand Down Expand Up @@ -11767,13 +11751,6 @@ graphiql@^0.11.2:
codemirror-graphql "^0.6.11"
markdown-it "^8.4.0"

graphql-anywhere@^4.1.0-alpha.0:
version "4.1.22"
resolved "https://registry.yarnpkg.com/graphql-anywhere/-/graphql-anywhere-4.1.22.tgz#1c831ba3c9e5664a0dd24d10d23a9e9512d92056"
integrity sha512-qm2/1cKM8nfotxDhm4J0r1znVlK0Yge/yEKt26EVVBgpIhvxjXYFALCGbr7cvfDlvzal1iSPpaYa+8YTtjsxQA==
dependencies:
apollo-utilities "^1.0.25"

graphql-compose@^6.3.2:
version "6.3.5"
resolved "https://registry.yarnpkg.com/graphql-compose/-/graphql-compose-6.3.5.tgz#019a5a4441293cdf15dbe0173438a2c997017e26"
Expand Down