/
client.ts
206 lines (190 loc) · 5.74 KB
/
client.ts
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import uuid from 'uuid';
import { ICache, IClientOptions, IMutation, IQuery } from '../interfaces/index';
import { gankTypeNamesFromResponse } from '../modules/typenames';
import { hashString } from './hash';
// Response from executeQuery call
export interface IQueryResponse {
data: object[];
typeNames?: string[];
}
export const defaultCache = store => {
return {
invalidate: hash =>
new Promise(resolve => {
delete store[hash];
resolve(hash);
}),
invalidateAll: () =>
new Promise(resolve => {
store = {};
resolve();
}),
read: hash =>
new Promise(resolve => {
resolve(store[hash] || null);
}),
update: callback =>
new Promise(resolve => {
if (typeof callback === 'function') {
Object.keys(store).forEach(key => {
callback(store, key, store[key]);
});
}
resolve();
}),
write: (hash, data) =>
new Promise(resolve => {
store[hash] = data;
resolve(hash);
}),
};
};
export default class Client {
url?: string; // Graphql API URL
store: object; // Internal store
fetchOptions: object | (() => object); // Options for fetch call
subscriptions: object; // Map of subscribed Connect components
cache: ICache; // Cache object
constructor(opts?: IClientOptions) {
if (!opts) {
throw new Error('Please provide configuration object');
}
// Set option/internal defaults
if (!opts.url) {
throw new Error('Please provide a URL for your GraphQL API');
}
this.url = opts.url;
this.fetchOptions = opts.fetchOptions || {};
this.store = opts.initialCache || {};
this.cache = opts.cache || defaultCache(this.store);
this.subscriptions = {};
// Bind methods
this.executeQuery = this.executeQuery.bind(this);
this.executeMutation = this.executeMutation.bind(this);
this.updateSubscribers = this.updateSubscribers.bind(this);
this.refreshAllFromCache = this.refreshAllFromCache.bind(this);
}
updateSubscribers(typenames, changes) {
// On mutation, call subscribed callbacks with eligible typenames
for (const sub in this.subscriptions) {
if (this.subscriptions.hasOwnProperty(sub)) {
this.subscriptions[sub](typenames, changes);
}
}
}
subscribe(
callback: (changedTypes: string[], response: object) => void
): string {
// Create an identifier, add callback to subscriptions, return identifier
const id = uuid.v4();
this.subscriptions[id] = callback;
return id;
}
unsubscribe(id: string) {
// Delete from subscriptions by identifier
delete this.subscriptions[id];
}
refreshAllFromCache() {
// On mutation, call subscribed callbacks with eligible typenames
return new Promise(resolve => {
for (const sub in this.subscriptions) {
if (this.subscriptions.hasOwnProperty(sub)) {
this.subscriptions[sub](null, null, true);
}
}
resolve();
});
}
executeQuery(
queryObject: IQuery,
skipCache: boolean
): Promise<IQueryResponse> {
return new Promise<IQueryResponse>((resolve, reject) => {
const { query, variables } = queryObject;
// Create query POST body
const body = JSON.stringify({
query,
variables,
});
// Create hash from serialized body
const hash = hashString(body);
// Check cache for hash
this.cache.read(hash).then(data => {
if (data && !skipCache) {
const typeNames = gankTypeNamesFromResponse(data);
resolve({ data, typeNames });
} else {
const fetchOptions =
typeof this.fetchOptions === 'function'
? this.fetchOptions()
: this.fetchOptions;
// Fetch data
fetch(this.url, {
body,
headers: { 'Content-Type': 'application/json' },
method: 'POST',
...fetchOptions,
})
.then(res => res.json())
.then(response => {
if (response.data) {
// Grab typenames from response data
const typeNames = gankTypeNamesFromResponse(response.data);
// Store data in cache, using serialized query as key
this.cache.write(hash, response.data);
resolve({
data: response.data,
typeNames,
});
} else {
reject({
message: 'No data',
});
}
})
.catch(e => {
reject(e);
});
}
});
});
}
executeMutation(mutationObject: IMutation): Promise<object[]> {
return new Promise<object[]>((resolve, reject) => {
const { query, variables } = mutationObject;
// Convert POST body to string
const body = JSON.stringify({
query,
variables,
});
const fetchOptions =
typeof this.fetchOptions === 'function'
? this.fetchOptions()
: this.fetchOptions;
// Call mutation
fetch(this.url, {
body,
headers: { 'Content-Type': 'application/json' },
method: 'POST',
...fetchOptions,
})
.then(res => res.json())
.then(response => {
if (response.data) {
// Retrieve typenames from response data
const typeNames = gankTypeNamesFromResponse(response.data);
// Notify subscribed Connect wrappers
this.updateSubscribers(typeNames, response);
resolve(response.data);
} else {
reject({
message: 'No data',
});
}
})
.catch(e => {
reject(e);
});
});
}
}