-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathresponse.ts
80 lines (79 loc) · 2.52 KB
/
response.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
73
74
75
76
77
78
79
80
import { parseXml } from '../../components/AppResources/parseXml';
import { handleAjaxError } from '../../components/Errors/FormatError';
import type { RA, ValueOf } from '../types';
import { filterArray } from '../types';
import { Http, httpCodeToErrorMessage } from './definitions';
import type { AjaxErrorMode, AjaxResponseObject, MimeType } from './index';
/**
* Handle network response (parse the data, handle possible errors)
*/
export function handleAjaxResponse<RESPONSE_TYPE = string>({
expectedErrors,
accept,
response,
errorMode,
text,
}: {
readonly expectedErrors: RA<number>;
readonly accept: MimeType | undefined;
readonly response: Response;
readonly errorMode: AjaxErrorMode;
readonly text: string;
}): AjaxResponseObject<RESPONSE_TYPE> {
// BUG: silence all errors if the page begun reloading
try {
if (response.ok || expectedErrors.includes(response.status)) {
if (response.ok && accept === 'application/json') {
try {
return { data: JSON.parse(text), response, status: response.status };
} catch {
throw {
type: 'jsonParseFailure',
statusText: 'Failed parsing JSON response:',
responseText: text,
};
}
} else if (response.ok && accept === 'text/xml') {
const parsed = parseXml(text);
if (typeof parsed === 'object')
return {
// Assuming that RESPONSE_TYPE extends Document
data: parsed as unknown as RESPONSE_TYPE,
response,
status: response.status,
};
else
throw {
type: 'xmlParseFailure',
statusText: `Failed parsing XML response: ${parsed}`,
responseText: text,
};
} else
return {
// Assuming that RESPONSE_TYPE extends string
data: text as unknown as RESPONSE_TYPE,
response,
status: response.status,
};
} else if (response.status === Http.FORBIDDEN)
throw {
type: 'permissionDenied',
statusText: "You don't have a permission to do this action",
responseText: text,
};
else {
throw {
type: 'invalidResponseCode',
statusText: filterArray([
`Invalid response code ${response.status}.`,
httpCodeToErrorMessage[response.status as ValueOf<typeof Http>],
'Response:',
]),
responseText: text,
};
}
} catch (error) {
console.error(error);
handleAjaxError(error, response, errorMode);
}
}