blob: b2075c31b8a5e9c16a3aa01198a5376ee5633bd9 [file] [log] [blame]
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +02001const CC_API_BASE_URL = 'https://support.google.com/s/community/api/';
2
3// Function to wrap calls to the Community Console API with intelligent error
4// handling.
Adrià Vilanova Martínezc41edf42021-07-18 02:06:55 +02005export function CCApi(
6 method, data, authenticated, authuser = 0,
7 returnUnauthorizedStatus = false) {
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +02008 var authuserPart =
9 authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser);
10
11 return fetch(CC_API_BASE_URL + method + authuserPart, {
12 'headers': {
13 'content-type': 'text/plain; charset=utf-8',
14 },
15 'body': JSON.stringify(data),
16 'method': 'POST',
17 'mode': 'cors',
18 'credentials': (authenticated ? 'include' : 'omit'),
19 })
20 .then(res => {
21 if (res.status == 200 || res.status == 400) {
22 return res.json().then(data => ({
23 status: res.status,
24 body: data,
25 }));
26 } else {
27 throw new Error(
28 'Status code ' + res.status + ' was not expected when calling ' +
29 method + '.');
30 }
31 })
32 .then(res => {
33 if (res.status == 400) {
Adrià Vilanova Martínezc41edf42021-07-18 02:06:55 +020034 // If the canonicalCode is PERMISSION_DENIED:
35 if (returnUnauthorizedStatus && res.body?.[2] == 7)
36 return {
37 unauthorized: true,
38 };
39
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +020040 throw new Error(
41 res.body[4] ||
42 ('Response status 400 for method ' + method + '. ' +
43 'Error code: ' + (res.body[2] ?? 'unknown')));
44 }
45
Adrià Vilanova Martínezc41edf42021-07-18 02:06:55 +020046 if (returnUnauthorizedStatus)
47 return {
48 unauthorized: false,
49 body: res.body,
50 };
51
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +020052 return res.body;
53 });
54}