/
xhr.js
358 lines (274 loc) · 10 KB
/
xhr.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
/*
* This file is part of the QuidPHP package <https://quidphp.com>
* Author: Pierre-Philippe Emond <emondpph@gmail.com>
* License: https://github.com/quidphp/browser/blob/master/LICENSE
*/
// xhr
// script with some logic for ajax calls and xhr object
// import
import { ArrLike, Dom, Ele, Func, Integer, Json, Nod, Pojo, Request, Str, Target, Uri, Vari } from '../index.js';
// export
export default new function()
{
// inst
const $inst = this;
// isStatusSuccess
// retourne vrai si le statut est un succès
this.isStatusSuccess = function(value)
{
return (Integer.is(value) && value >= 200 && value < 400);
}
// isResponseJson
// retourne vrai si la réponse du xhr a un content type de json
this.isResponseJson = function(xhr)
{
let r = false;
if(xhr instanceof XMLHttpRequest)
{
const contentType = xhr.getResponseHeader('Content-Type');
if(Str.in('/json',contentType))
r = true;
}
return r;
}
// trigger
// fonction utilisé pour lancer une requête ajax
// retourne null ou un objet promise ajax
this.trigger = function(config,extraEvents)
{
config = prepareConfig.call(this,config);
Str.typecheck(config.url,true);
const xhr = new XMLHttpRequest();
xhr.open(config.method, config.url, true);
xhr.timeout = config.timeout;
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.ontimeout = function() {
callEvent('error',xhr,config,extraEvents);
};
xhr.onreadystatechange = function() {
if(this.readyState === XMLHttpRequest.DONE)
{
const isSuccess = $inst.isStatusSuccess(this.status);
if(isSuccess === false)
callEvent('error',xhr,config,extraEvents);
else if(isSuccess === true)
callEvent('success',xhr,config,extraEvents);
callEvent('complete',xhr,config,extraEvents);
}
};
if(xhr.upload != null)
{
xhr.upload.addEventListener("progress",function(event) {
if(Func.is(config.progress) && event.lengthComputable === true)
{
const percent = parseInt((event.loaded / event.total * 100));
callEvent('progress',xhr,config,extraEvents,percent,event);
}
});
}
// before
callEvent('before',xhr,config,extraEvents);
xhr.send(config.data);
return xhr;
}
// configFromString
// retounre un tableau avec la string comme url
this.configFromString = function(value)
{
Str.typecheck(value,true);
return {
url: value
};
}
// callEvent
// function utilisé pour faire les appels aux callbacks de la requête ajax
// pour les callbacks, this est xhr mais xhr est aussi envoyé en dernier argument
const callEvent = function(type,xhr,config,extraEvents)
{
const configCallback = Pojo.get(type,config);
const extraCallback = (Pojo.is(extraEvents))? Pojo.get(type,extraEvents):null;
const args = ArrLike.sliceStart(4,arguments);
args.push(xhr);
if(Func.is(configCallback))
configCallback.apply(xhr,args);
if(Func.is(extraCallback))
extraCallback.apply(xhr,args);
}
// defaultConfig
// retourne la configuration par défaut pour une requête ajax
const defaultConfig = function()
{
return {
url: undefined,
method: undefined,
data: undefined,
timeout: 10000
};
}
// prepareConfig
// dernière préparation à la configuration ajax
const prepareConfig = function(config)
{
if(Pojo.is(config) && Str.is(config.uri))
config.url = config.uri;
config = Pojo.replace(defaultConfig(),config);
if(!Str.is(config.method))
config.method = 'get';
config.method = config.method.toUpperCase();
if(Pojo.is(config.data))
{
if(config.method === 'POST')
config.data = this.pojoToFormData(config.data);
else
{
const parse = Uri.parse(config.url);
const query = Uri.makeQuery(config.data).toString();
parse.search = query;
config.url = parse.toString();
}
}
if(!config.data instanceof FormData)
config.data = null;
return config;
}
// configFromNode
// met à jour le tableau de config à partir de la tag
// retourne null si ajax:confirm est false
this.configFromNode = function(node,config,events)
{
Ele.typecheck(node);
let r = (Pojo.is(config))? config:{};
const tagName = Ele.tag(node);
if(r.method == null)
r = configNodeMethod(r,node,tagName);
r = configNodeUrl(r,node,tagName);
if(r.data == null)
r = configNodeData(r,node,tagName);
if(events === true)
r = this.configNodeEvents(node,r);
r = prepareConfig.call(this,r);
return r;
}
// configNodeEvents
// fait la configuration des événements à envoyer à la node pour la requête ajax
this.configNodeEvents = function(node,config)
{
const $this = this;
Ele.typecheck(node);
Pojo.typecheck(config);
config.before = function(xhr) {
Target.triggerHandler(node,'ajax:before',xhr);
};
config.progress = function(percent,event,xhr) {
Target.triggerHandler(node,'ajax:progress',percent,event,xhr);
};
config.success = function(xhr) {
const responseText = (Str.isNotEmpty(xhr.responseText) && $this.isResponseJson(xhr))? Json.decode(xhr.responseText):xhr.responseText;
Target.triggerHandler(node,'ajax:success',responseText,xhr);
};
config.error = function(xhr) {
const parsedError = $inst.parseError(xhr.responseText);
Target.triggerHandler(node,'ajax:error',parsedError,xhr);
};
config.complete = function(xhr) {
Target.triggerHandler(node,'ajax:complete',xhr);
};
return config;
}
// pojoToFormData
// permet de transformer un pojo en formData
this.pojoToFormData = function(value)
{
Pojo.typecheck(value);
const r = new FormData();
Pojo.each(value,function(val,key) {
r.append(key,val);
});
return r;
}
// parseError
// cette méthode gère l'affichage pour un xhr en erreur
this.parseError = function(responseText)
{
let r = '';
if(Str.isNotEmpty(responseText))
{
r = responseText;
let html;
const parse = Dom.parseOne(responseText);
if(parse != null)
{
const ajaxParse = Nod.scopedQuery(parse,".ajax-parse-error");
if(ajaxParse != null)
html = Ele.getOuterHtml(ajaxParse);
if(Vari.isEmpty(html))
{
const body = Nod.scopedQuery(parse,"body,[data-tag='body']");
if(body != null)
html = Ele.getHtml(body);
}
if(Str.isNotEmpty(html))
r = html;
}
}
return r;
}
// configNodeUrl
// fait la configuration de l'url pour une node
// pour un form get, ajoute les données du formulaire comme query
const configNodeUrl = function(r,node,tagName)
{
if(r.url == null)
r.url = Target.triggerHandler(node,'ajax:getUrl');
if(r.url == null)
r.url = Ele.getUri(node);
if(r.url != null && tagName === 'form' && Str.icompare(r.method,'get'))
{
const query = Ele.triggerHandler(node,'form:serialize');
const parse = Uri.parse(r.url);
if(query != null && parse != null)
{
parse.search = query;
r.url = Uri.build(parse);
}
}
return r;
}
// configNodeMethod
// fait la configuration de la méthode pour une node
const configNodeMethod = function(r,node,tagName)
{
r.method = Target.triggerHandler(node,'ajax:getMethod');
if(r.method == null)
{
if(tagName === 'form')
r.method = Ele.getAttr(node,"method") || 'get';
else
r.method = Ele.getAttr(node,'data-method') || 'get';
}
return r;
}
// configNodeData
// fait la configuration des datas pour une node
// pour un formulaire seulement si c'est post
const configNodeData = function(r,node,tagName)
{
r.data = Target.triggerHandler(node,'ajax:getData');
if(r.data == null && tagName === 'form' && Str.icompare(r.method,'post'))
{
const formData = new FormData(node);
const clicked = Target.triggerHandler(node,'form:getClickedSubmit');
if(clicked != null)
{
const clickedName = Ele.getAttr(clicked,'name');
if(Str.isNotEmpty(clickedName))
{
const clickedVal = Ele.getValue(clicked);
formData.append(clickedName,clickedVal);
}
}
r.data = formData;
}
return r;
}
}