-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.coffee
79 lines (61 loc) · 1.82 KB
/
main.coffee
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
require "./shims"
module.exports = ->
ajax = (options={}) ->
{data, headers, method, overrideMimeType, password, url, responseType, timeout, user, withCredentials} = options
data ?= ""
method ?= "GET"
password ?= ""
responseType ?= ""
timeout ?= 0
user ?= ""
withCredentials ?= false
new ProgressPromise (resolve, reject, progress) ->
xhr = new XMLHttpRequest()
xhr.open(method, url, true, user, password)
xhr.responseType = responseType
xhr.timeout = timeout
xhr.withCredentialls = withCredentials
if headers
Object.keys(headers).forEach (header) ->
value = headers[header]
xhr.setRequestHeader header, value
if overrideMimeType
xhr.overrideMimeType overrideMimeType
xhr.onload = (e) ->
if (200 <= this.status < 300) or this.status is 304
resolve this.response
complete e, xhr, options
else
reject xhr
complete e, xhr, options
xhr.onerror = (e) ->
reject xhr
complete e, xhr, options
xhr.onprogress = progress
xhr.send(data)
complete = (args...) ->
completeHandlers.forEach (handler) ->
handler args...
configure = (optionDefaults) ->
(url, options={}) ->
if typeof url is "object"
options = url
else
options.url = url
defaults options, optionDefaults
ajax(options)
completeHandlers = []
Object.assign ajax,
ajax: configure {}
complete: (handler) ->
completeHandlers.push handler
getJSON: configure
responseType: "json"
getBlob: configure
responseType: "blob"
defaults = (target, objects...) ->
for object in objects
for name of object
unless target.hasOwnProperty(name)
target[name] = object[name]
return target