Skip to content

Commit

Permalink
Short circuit fetch for /graphql on SSR (kriasoft#1502)
Browse files Browse the repository at this point in the history
  • Loading branch information
nbclark authored and langpavel committed Jan 23, 2018
1 parent 065fb24 commit 2388870
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
26 changes: 23 additions & 3 deletions src/createFetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*/

/* @flow */
import { graphql } from 'graphql';

type Fetch = (url: string, options: ?any) => Promise<any>;

Expand All @@ -22,7 +23,7 @@ type Options = {
* of boilerplate code in the application.
* https://developer.mozilla.org/docs/Web/API/Fetch_API/Using_Fetch
*/
function createFetch(fetch: Fetch, { baseUrl, cookie }: Options) {
function createFetch(fetch: Fetch, { baseUrl, cookie, schema }: Options) {
// NOTE: Tweak the default options to suite your application needs
const defaults = {
method: 'POST', // handy with GraphQL backends
Expand All @@ -35,8 +36,26 @@ function createFetch(fetch: Fetch, { baseUrl, cookie }: Options) {
},
};

return (url: string, options: any) =>
url.startsWith('/graphql') || url.startsWith('/api')
return async (url: string, options: any) => {
const isGraphQL = url.startsWith('/graphql');
if (schema && isGraphQL) {
// We're SSR, so route the graphql internall to avoid latency
const query = JSON.parse(options.body);
const result = await graphql(
schema,
query.query,
{ request: {} }, // fill in request vars needed by graphql
null,
query.variables,
);
return new Promise(resolve =>
resolve({
status: result.errors ? 400 : 200,
json: () => new Promise(resolveJson => resolveJson(result)),
}),
);
}
return isGraphQL || url.startsWith('/api')
? fetch(`${baseUrl}${url}`, {
...defaults,
...options,
Expand All @@ -46,6 +65,7 @@ function createFetch(fetch: Fetch, { baseUrl, cookie }: Options) {
},
})
: fetch(url, options);
};
}

export default createFetch;
1 change: 1 addition & 0 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ app.get('*', async (req, res, next) => {
fetch: createFetch(fetch, {
baseUrl: config.api.serverUrl,
cookie: req.headers.cookie,
schema,
}),
};

Expand Down

0 comments on commit 2388870

Please sign in to comment.