-
Notifications
You must be signed in to change notification settings - Fork 14
/
make-ajax-request.ts
72 lines (62 loc) · 1.99 KB
/
make-ajax-request.ts
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
import { parse as parseContentType } from 'content-type'
import isLocal from './is-local'
const makeAjaxRequest = (
url: string,
httpRequestWithCredentials: boolean,
callback: (error: Error | null, httpRequest: XMLHttpRequest) => void,
) => {
const httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = () => {
try {
if (!/\.svg/i.test(url) && httpRequest.readyState === 2) {
const contentType = httpRequest.getResponseHeader('Content-Type')
if (!contentType) {
throw new Error('Content type not found')
}
const { type } = parseContentType(contentType)
if (!(type === 'image/svg+xml' || type === 'text/plain')) {
throw new Error(`Invalid content type: ${type}`)
}
}
if (httpRequest.readyState === 4) {
if (httpRequest.status === 404 || httpRequest.responseXML === null) {
throw new Error(
isLocal()
? 'Note: SVG injection ajax calls do not work locally without ' +
'adjusting security settings in your browser. Or consider ' +
'using a local webserver.'
: 'Unable to load SVG file: ' + url,
)
}
if (
httpRequest.status === 200 ||
(isLocal() && httpRequest.status === 0)
) {
callback(null, httpRequest)
} else {
throw new Error(
'There was a problem injecting the SVG: ' +
httpRequest.status +
' ' +
httpRequest.statusText,
)
}
}
} catch (error) {
httpRequest.abort()
if (error instanceof Error) {
callback(error, httpRequest)
} else {
throw error
}
}
}
httpRequest.open('GET', url)
httpRequest.withCredentials = httpRequestWithCredentials
/* istanbul ignore else */
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml')
}
httpRequest.send()
}
export default makeAjaxRequest