forked from apollographql/meteor-integration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain-client.js
64 lines (51 loc) · 1.63 KB
/
main-client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import './check-npm.js';
import { createNetworkInterface } from 'apollo-client';
import { addTypenameToSelectionSet } from 'apollo-client/queries/queryTransform';
import { Accounts } from 'meteor/accounts-base';
import { _ } from 'meteor/underscore';
const defaultNetworkInterfaceConfig = {
path: '/graphql',
options: {},
useMeteorAccounts: true
};
export const createMeteorNetworkInterface = (givenConfig) => {
const config = _.extend(defaultNetworkInterfaceConfig, givenConfig);
// absoluteUrl adds a '/', so let's remove it first
let path = config.path;
if (path[0] === '/') {
path = path.slice(1);
}
// For SSR
const url = Meteor.absoluteUrl(path);
const networkInterface = createNetworkInterface(url);
if (config.useMeteorAccounts) {
networkInterface.use([{
applyMiddleware(request, next) {
const currentUserToken = Accounts._storedLoginToken();
if (!currentUserToken) {
next();
return;
}
if (!request.options.headers) {
request.options.headers = new Headers();
}
request.options.headers.Authorization = currentUserToken;
next();
},
}]);
}
return networkInterface;
};
export const meteorClientConfig = (networkInterfaceConfig) => {
return {
networkInterface: createMeteorNetworkInterface(networkInterfaceConfig),
queryTransformer: addTypenameToSelectionSet,
// Default to using Mongo _id, must use _id for queries.
dataIdFromObject: (result) => {
if (result._id && result.__typename) {
const dataId = result.__typename + result._id;
return dataId;
}
},
};
};