forked from DuendeArchive/identity-model-oidc-client-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonService.js
More file actions
84 lines (67 loc) · 2.77 KB
/
Copy pathJsonService.js
File metadata and controls
84 lines (67 loc) · 2.77 KB
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
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
import { Log } from './Log';
import { Global } from './Global';
export class JsonService {
constructor(additionalContentTypes = null, XMLHttpRequestCtor = Global.XMLHttpRequest) {
if (additionalContentTypes && Array.isArray(additionalContentTypes))
{
this._contentTypes = additionalContentTypes.slice();
}
else
{
this._contentTypes = [];
}
this._contentTypes.push('application/json');
this._XMLHttpRequest = XMLHttpRequestCtor;
}
getJson(url, token) {
if (!url){
Log.error("JsonService.getJson: No url passed");
throw new Error("url");
}
Log.debug("JsonService.getJson, url: ", url);
return new Promise((resolve, reject) => {
var req = new this._XMLHttpRequest();
req.open('GET', url);
var allowedContentTypes = this._contentTypes;
req.onload = function() {
Log.debug("JsonService.getJson: HTTP response received, status", req.status);
if (req.status === 200) {
var contentType = req.getResponseHeader("Content-Type");
if (contentType) {
var found = allowedContentTypes.find(item=>{
if (contentType.startsWith(item)) {
return true;
}
});
if (found) {
try {
resolve(JSON.parse(req.responseText));
return;
}
catch (e) {
Log.error("JsonService.getJson: Error parsing JSON response", e.message);
reject(e);
return;
}
}
}
reject(Error("Invalid response Content-Type: " + contentType + ", from URL: " + url));
}
else {
reject(Error(req.statusText + " (" + req.status + ")"));
}
};
req.onerror = function() {
Log.error("JsonService.getJson: network error");
reject(Error("Network Error"));
};
if (token) {
Log.debug("JsonService.getJson: token passed, setting Authorization header");
req.setRequestHeader("Authorization", "Bearer " + token);
}
req.send();
});
}
}