-
Notifications
You must be signed in to change notification settings - Fork 26
/
adapter.js
394 lines (335 loc) · 10.8 KB
/
adapter.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
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import { get } from '@ember/object';
import $ from 'jquery';
import { join } from '@ember/runloop';
import { Promise as EmberPromise } from 'rsvp';
import { camelize } from '@ember/string';
import DS from 'ember-data';
import Compiler from './compiler';
import request from 'ember-ajax/request';
import { pluralize } from 'ember-inflector';
export default DS.Adapter.extend({
endpoint: null,
httpMethod: 'GET',
param: 'query',
defaultSerializer: '-graphql',
coalesceFindRequests: false,
/**
This function controls the normalization of all compound words.
@method normalizeCase
@param {String} string
@return {String} string
*/
normalizeCase: function(string) {
return camelize(string);
},
/**
Normalizes query parameters to avoid ParseErrors on the server side.
@method normalizeQuery
@param {Object} query
@return {Object} normalized query
*/
normalizeQuery: function(query) {
let normalizedQuery = {};
Object.keys(query).forEach((key) => {
let value = query[key];
if (typeof value === 'string') {
normalizedQuery[key] = value
.replace(/\\/g, '\\\\')
.replace(/\"/g, '\\"'); //eslint-disable-line no-useless-escape
} else {
normalizedQuery[key] = value;
}
});
return normalizedQuery;
},
/**
Called by the store in order to fetch the JSON for a given
type and ID.
The `findRecord` method makes an Ajax request to the GraphQL
endpoint, and returns a promise for the resulting payload.
@method findRecord
@param {DS.Store} store
@param {DS.Model} type
@param {String} id
@return {Promise} promise
*/
findRecord: function(store, type, id) {
let operationName = this.normalizeCase(type.modelName);
return this.request(store, type, {
'operationName': operationName,
'operationType': 'query',
'parseSelectionSet': true,
'rootFieldName': operationName,
'rootFieldQuery': { 'id': id }
});
},
/**
Called by the store in order to fetch a JSON array for all
of the records for a given type.
The `findAll` method makes an Ajax request to the GraphQL
endpoint, and returns a promise for the resulting payload.
@method findAll
@param {DS.Store} store
@param {DS.Model} type
@return {Promise} promise
*/
findAll: function(store, type) {
let operationName = this.normalizeCase(pluralize(type.modelName));
return this.request(store, type, {
'operationName': operationName,
'operationType': 'query',
'parseSelectionSet': true,
'rootFieldName': operationName
});
},
/**
Called by the store in order to fetch JSON for
the records that match a particular query.
The `query` method makes an Ajax request to the GraphQL
endpoint, and returns a promise for the resulting payload.
The `query` argument is a simple JavaScript object that will be
passed to the GraphQL compiler and becomes arguments for the
GraphQL query.
@method query
@param {DS.Store} store
@param {DS.Model} type
@param {Object} query
@return {Promise} promise
*/
query: function(store, type, query) {
let operationName = this.normalizeCase(pluralize(type.modelName));
return this.request(store, type, {
'operationName': operationName,
'operationType': 'query',
'parseSelectionSet': true,
'rootFieldName': operationName,
'rootFieldQuery': this.normalizeQuery(query)
});
},
/**
Called by the store in order to fetch JSON for a single record that
matches a particular query.
The `query` method makes an Ajax request to the GraphQL
endpoint, and returns a promise for the resulting payload.
The `query` argument is a simple JavaScript object that will be
passed to the GraphQL compiler and becomes arguments for the
GraphQL query.
@method queryRecord
@param {DS.Store} store
@param {DS.Model} type
@param {Object} query
@return {Promise} promise
*/
queryRecord: function(store, type, query) {
let operationName = this.normalizeCase(type.modelName);
return this.request(store, type, {
'operationName': operationName,
'operationType': 'query',
'parseSelectionSet': true,
'rootFieldName': operationName,
'rootFieldQuery': this.normalizeQuery(query)
});
},
/**
Called by the store in order to fetch several records together if `coalesceFindRequests` is true
@method findMany
@param {DS.Store} store
@param {DS.Model} type
@param {Array} ids
@return {Promise} promise
*/
findMany(store, type, ids) {
let operationName = this.normalizeCase(pluralize(type.modelName));
return this.request(store, type, {
'operationName': operationName,
'operationType': 'query',
'parseSelectionSet': true,
'rootFieldName': operationName,
'rootFieldQuery': { 'ids': ids }
});
},
saveRecord: function(store, type, snapshot, options) {
let data = {};
let serializer = store.serializerFor(type.modelName);
let modelName = this.normalizeCase(type.modelName);
let operationName = this.normalizeCase(modelName + options.action);
serializer.serializeIntoHash(data, type, snapshot);
let payload = { id: data['id'] };
Object.keys(snapshot.changedAttributes()).forEach(key => {
let payloadKey = serializer.keyForAttribute(key);
payload[payloadKey] = data[payloadKey];
});
snapshot.eachRelationship((key, {kind, options}) => {
let payloadKey = serializer.keyForRelationship(key, kind, options);
payload[payloadKey] = data[payloadKey];
});
return this.request(store, type, {
'operationName': operationName,
'operationType': 'mutation',
'parseSelectionSet': true,
'rootFieldAlias': modelName,
'rootFieldName': operationName,
'rootFieldQuery': payload
});
},
/**
Called by the store when a newly created record is
saved via the `save` method on a model record instance.
@method createRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
createRecord: function(store, type, snapshot) {
return this.saveRecord(store, type, snapshot, { action: 'Create' });
},
/**
Called by the store when an existing record is saved
via the `save` method on a model record instance.
The `updateRecord` method makes an Ajax request to the GraphQL endpoint.
@method updateRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord: function(store, type, snapshot) {
return this.saveRecord(store, type, snapshot, { action: 'Update' });
},
/**
Called by the store when a record is deleted.
The `deleteRecord` method makes an Ajax request to the GraphQL endpoint.
@method deleteRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
deleteRecord: function(store, type, snapshot) {
let data = this.serialize(snapshot, { includeId: true });
let modelName = this.normalizeCase(type.modelName);
let operationName = this.normalizeCase(`${modelName}Delete`);
return this.request(store, type, {
'operationName': operationName,
'operationType': 'mutation',
'parseSelectionSet': false,
'rootFieldAlias': modelName,
'rootFieldName': operationName,
'rootFieldQuery': { 'id': data.id },
});
},
/**
@method compile
@private
@param {DS.Store} store
@param {DS.Model} type
@params {Object} options
@return {String} result
*/
compile: function(store, type, options) {
options['normalizeCaseFn'] = this.normalizeCase;
return Compiler.compile(type, store, options);
},
/**
@method request
@private
@param {DS.Store} store
@param {DS.Model} type
@params {Object} options
@return {Promise} promise
*/
request: function(store, type, options) {
let compiledQuery = this.compile(store, type, options);
let url = this.endpoint;
let ajaxOpts = this.ajaxOptions({ query: compiledQuery });
return this.ajax(url, ajaxOpts);
},
/**
@method ajax
@private
@params {Object} options
@return {Promise} promise
*/
ajax: function(url, options) {
let adapter = this;
return new EmberPromise((resolve, reject) => {
return request(url, options).then(response => {
const adapterResponse = adapter.handleResponse(null, null, response);
if (response && adapterResponse.isAdapterError) {
join(null, reject, response);
} else {
join(null, resolve, response);
}
}, error => {
join(null, reject, error);
});
});
},
/**
@method parseErrorResponse
@private
@param {String} responseText
@return {Object}
*/
parseErrorResponse(responseText) {
var json = responseText;
try {
json = $.parseJSON(responseText);
} catch (e) {
// empty
}
return json;
},
/**
@method ajaxOptions
@private
@param {String} url
@return {Object}
*/
ajaxOptions: function(data) {
let opts = {
'dataType': 'json',
'data': data,
'type': this.httpMethod,
'context': this
};
let headers = get(this, 'headers');
if (headers !== undefined) {
opts.beforeSend = function (xhr) {
Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key]));
};
}
return opts;
},
/**
Takes an ajax response, and returns the json payload or an error.
By default this hook just returns the json payload passed to it.
You might want to override it in two cases:
1. Your API might return useful results in the response headers.
Response headers are passed in as the second argument.
2. Your API might return errors as successful responses with status code
200 and an Errors text or object. You can return a `DS.InvalidError` or a
`DS.AdapterError` (or a sub class) from this hook and it will automatically
reject the promise and put your record into the invalid or error state.
Returning a `DS.InvalidError` from this method will cause the
record to transition into the `invalid` state and make the
`errors` object available on the record. When returning an
`DS.InvalidError` the store will attempt to normalize the error data
returned from the server using the serializer's `extractErrors`
method.
@method handleResponse
@param {Number} status
@param {Object} headers
@param {Object} payload
@param {Object} options
@return {Object | DS.AdapterError} response
*/
handleResponse: function(status, headers, payload) {
if (payload['errors']) {
return new DS.InvalidError(payload['errors']);
} else {
return payload;
}
}
});