-
Notifications
You must be signed in to change notification settings - Fork 0
/
kendo.data.odata-batch.js
362 lines (278 loc) · 11 KB
/
kendo.data.odata-batch.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
/**
* OData Batch Fix for Kendo UI v0.9.5 (http://github.com/advancedrei/kendo-odata-batch)
* Copyright (C) 2016 AdvancedREI, LLC. All Rights Reserved.
*
* Written by Atanas Korchev.
* Licensed under the MIT License: https://opensource.org/licenses/MIT
*/
(function ($, kendo) {
function pack(data, boundary, useTransaction) {
var body = [];
var changeset = kendo.guid();
if (useTransaction) {
body.push('--batch_' + boundary);
body.push('Content-Type: multipart/mixed; boundary=changeset_' + changeset, '');
}
$.each(data, function (i, d) {
var t = d.type.toUpperCase(), noBody = ['GET', 'DELETE'];
if (!useTransaction) {
body.push('--batch_' + boundary);
changeset = kendo.guid();
body.push('Content-Type: multipart/mixed; boundary=changeset_' + changeset, '');
}
body.push('--changeset_' + changeset);
body.push('Content-Type: application/http');
body.push('Content-Transfer-Encoding: binary');
body.push('Content-ID:' + i + 1, '');
body.push(t + ' ' + d.url + ' HTTP/1.1');
/* Don't care about content type for requests that have no body. */
if (noBody.indexOf(t) < 0) {
body.push('Content-Type: ' + (d.contentType || 'application/json; charset=utf-8'));
body.push('Accept: ' + (d.contentType || 'application/json; charset=utf-8'));
}
body.push('Host: ' + location.host);
body.push('', d.data ? JSON.stringify(d.data) : '');
if (!useTransaction) {
body.push('--changeset_' + changeset + '--', '');
}
});
if (useTransaction) {
body.push('--changeset_' + changeset + '--', '');
}
body.push('--batch_' + boundary + '--', '');
return body.join('\r\n');
}
function splitSingleChangeset(responseText) {
return responseText.split(/--changesetresponse_(?:.*)/g).slice(1, -1);
}
function splitMultipleChangeset(responseText) {
var matcher = /--changesetresponse_(.*)/g;
var match;
var responses = []
while (match = matcher.exec(responseText)) {
var start = match.index + match[0].length;
match = matcher.exec(responseText);
if (match) {
var end = match.index;
var response = $.trim(responseText.substring(start, end));
responses.push(response);
}
}
return responses;
}
function unpack(xhr, status, params, useTransaction) {
var complete = params.complete;
var requests = params.data;
if (status != 'success') {
return complete.call(this, xhr, status, xhr.responseText);
}
var responseText = xhr.responseText;
var responses = useTransaction ? splitSingleChangeset(responseText) :
splitMultipleChangeset(responseText);
var result = {
created: [],
updated: [],
destroyed: [],
errors: []
};
requests.forEach(function(request, index) {
var raw = responses[index];
if (!raw) {
// If there is a failure in transactional mode there is only one response
return;
}
var lines = $.trim(raw).split('\r\n\r\n');
var response = {};
response.status = parseInt((function (m) {
return m || [0, 0];
})(/HTTP\/1.1 ([0-9]+)/g.exec(lines[1]))[1], 10);
try {
response.data = JSON.parse(lines[2])
} catch (error) {
response.data = lines[2];
}
var success = response.status >= 200 && response.status < 400;
var payload = success ? $.extend({}, request.data, response.data) : { __error: true };
if (request.type == 'POST') {
if (success || !useTransaction) {
result.created.push(payload);
}
} else if (request.type == 'PUT') {
if (success || !useTransaction) {
result.updated.push(payload);
}
} else if (request.type == 'DELETE') {
if (success || !useTransaction) {
result.destroyed.push(payload);
}
}
if (!success) {
result.errors.push(response.data);
}
});
complete.call(this, xhr, status, result);
}
function ajaxBatch(params, useTransaction) {
var boundary = kendo.guid();
$.ajax({
type: 'POST',
url: params.url,
data: pack(params.data, boundary, useTransaction),
contentType: 'multipart/mixed; boundary=batch_' + boundary,
complete: params.complete ?
function (xhr, status) { unpack(xhr, status, params, useTransaction); } :
null
});
}
var odata = kendo.data.transports['odata'];
var odata4 = kendo.data.transports['odata-v4'];
function convertNumbersToStrings(item) {
for (var key in item) {
var value = item[key];
var type = $.type(value);
// Convert numbers to strings to handle Edm.Decimal
if (type === 'number') {
item[key] = value + '';
} else if (type === 'object') {
convertNumbersToStrings(value)
}
}
}
function enqueue(items, verb, url, type) {
return items.map(function (item) {
if (type) {
item['odata.type'] = type;
}
// Convert numbers to strings to handle Edm.Decimal
convertNumbersToStrings(item);
return {
data: item,
type: verb,
url: typeof url === 'function' ? url(item) : url
}
});
}
function submit(e) {
var requests = [].concat(
enqueue(e.data.created, 'POST', this.options.create.url, this.options.type),
enqueue(e.data.updated, 'PUT', this.options.update.url, this.options.type),
enqueue(e.data.destroyed, 'DELETE', this.options.destroy.url)
);
var batchUrl = this.options.batchUrl || this.options.read.url.substring(0, this.options.read.url.lastIndexOf('/')) + '/$batch'
ajaxBatch({
url: batchUrl,
data: requests,
complete: function (xhr, status, response) {
if (status == 'success') {
if (response.created.length) {
e.success(response.created, 'create')
}
if (response.updated.length) {
e.success(response.updated, 'update');
}
if (response.destroyed.length) {
e.success(response.destroyed, 'destroy');
}
if (response.errors.length) {
e.error(xhr, 'error', response.errors);
}
} else {
e.error(xhr, status, response);
}
}
}, this.options.useTransaction)
}
function data(d) {
var data = d.value || d;
if (!$.isArray(data)) {
data = [data];
}
return data.map(strip);
}
function strip(item) {
var clone = {};
for (var key in item) {
if (key.indexOf('odata') >= 0) {
continue;
}
clone[key] = item[key];
}
return clone;
}
kendo.data.transports['odata-v4'] = kendo.data.RemoteTransport.extend({
init: function (options) {
kendo.data.RemoteTransport.fn.init.call(this, $.extend(true, { useTransaction: false }, odata4, options));
this.useTransaction = this.options.useTransaction;
},
submit: submit,
setBatchDetails: function (batchUrl) {
this.options.batchUrl = batchUrl;
}
});
kendo.data.schemas['odata-v4'].data = data;
kendo.data.transports['odata'] = kendo.data.RemoteTransport.extend({
init: function (options) {
kendo.data.RemoteTransport.fn.init.call(this, $.extend(true, { useTransaction: false }, odata, options));
this.useTransaction = this.options.useTransaction;
},
submit: submit,
setBatchDetails: function (batchUrl, objectType) {
this.options.batchUrl = batchUrl;
this.options.type = objectType;
}
});
kendo.data.transports['odata'].parameterMap = odata.parameterMap;
kendo.data.schemas['odata'] = {
type: 'json',
data: data,
total: function (d) {
return Number(d['odata.count']);
}
};
var transactionalAccept = kendo.data.DataSource.prototype._accept;
// Patching the Kendo UI DataSource to support mixed (success and error) server responses.
kendo.data.DataSource.prototype._accept = function(result) {
var useTransaction = this.transport.useTransaction;
if (typeof useTransaction === 'undefined' || useTransaction === true) {
return transactionalAccept.call(this, result);
}
var that = this;
var models = result.models;
var response = result.response;
var serverGroup = that._isServerGrouped();
var pristine = that._pristineData;
var type = result.type;
that.trigger('requestEnd', { response: response, type: type });
if (response && !$.isEmptyObject(response)) {
response = that.reader.parse(response);
if (that._handleCustomErrors(response)) {
return;
}
response = that.reader.data(response);
if (!$.isArray(response)) {
response = [response];
}
} else {
response = $.map(models, function(model) { return model.toJSON(); } );
}
for (var idx = 0, length = models.length; idx < length; idx++) {
var item = response[idx];
if (item.__error === true) {
// Failed server response - skip everything in this case.
continue;
}
if (type !== 'destroy') {
models[idx].accept(item);
if (type === 'create') {
pristine.push(serverGroup ? that._wrapInEmptyGroup(models[idx]) : item);
} else if (type === 'update') {
that._updatePristineForModel(models[idx], item);
}
} else {
// Remove the item instead of clearing the _destroyed array which the original code does.
that._destroyed.splice($.inArray(that._destroyed, models[idx]), 1);
that._removePristineForModel(models[idx]);
}
}
}
})(jQuery, kendo);