-
Notifications
You must be signed in to change notification settings - Fork 4
/
backbone.fetch.js
75 lines (64 loc) · 1.98 KB
/
backbone.fetch.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
// Backbone.Fetch.js 0.2.4
// ---------------
// (c) 2016 Adam Krebs
// Backbone.Fetch may be freely distributed under the MIT license.
// For all details and documentation:
// https://github.com/akre54/Backbone.Fetch
(function() {
'use strict';
var defaults = function(obj, source) {
for (var prop in source) {
if (obj[prop] === undefined) obj[prop] = source[prop];
}
return obj;
};
var stringifyGETParams = function(url, data) {
var query = '';
for (var key in data) {
if (data[key] == null) continue;
query += '&'
+ encodeURIComponent(key) + '='
+ encodeURIComponent(data[key]);
}
if (query) url += (~url.indexOf('?') ? '&' : '?') + query.substring(1);
return url;
};
var getData = function(response, dataType) {
return dataType === 'json' ? response.json() : response.text();
};
var ajax = function(options) {
if (options.type === 'GET' && typeof options.data === 'object') {
options.url = stringifyGETParams(options.url, options.data);
delete options.data;
}
defaults(options, {
method: options.type,
headers: defaults(options.headers || {}, {
'Accept': 'application/json',
'Content-Type': 'application/json'
}),
body: options.data
});
return fetch(options.url, options)
.then(function(response) {
var promise = getData(response, options.dataType);
if (response.ok) return promise;
var error = new Error(response.statusText);
return promise.then(function(responseData) {
error.response = response;
error.responseData = responseData;
if (options.error) options.error(error);
throw error;
});
})
.then(function(responseData) {
if (options.success) options.success(responseData);
return responseData;
});
};
if (typeof exports === 'object') {
module.exports = ajax;
} else {
Backbone.ajax = ajax;
}
})();