Adrià Vilanova Martínez | a10fff2 | 2021-06-29 21:07:40 +0200 | [diff] [blame] | 1 | const 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ínez | c41edf4 | 2021-07-18 02:06:55 +0200 | [diff] [blame] | 5 | export function CCApi( |
| 6 | method, data, authenticated, authuser = 0, |
| 7 | returnUnauthorizedStatus = false) { |
Adrià Vilanova Martínez | a10fff2 | 2021-06-29 21:07:40 +0200 | [diff] [blame] | 8 | 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ínez | c41edf4 | 2021-07-18 02:06:55 +0200 | [diff] [blame] | 34 | // If the canonicalCode is PERMISSION_DENIED: |
| 35 | if (returnUnauthorizedStatus && res.body?.[2] == 7) |
| 36 | return { |
| 37 | unauthorized: true, |
| 38 | }; |
| 39 | |
Adrià Vilanova Martínez | a10fff2 | 2021-06-29 21:07:40 +0200 | [diff] [blame] | 40 | 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ínez | c41edf4 | 2021-07-18 02:06:55 +0200 | [diff] [blame] | 46 | if (returnUnauthorizedStatus) |
| 47 | return { |
| 48 | unauthorized: false, |
| 49 | body: res.body, |
| 50 | }; |
| 51 | |
Adrià Vilanova Martínez | a10fff2 | 2021-06-29 21:07:40 +0200 | [diff] [blame] | 52 | return res.body; |
| 53 | }); |
| 54 | } |