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. |
| 5 | function CCApi(method, data, authuser, authenticated = true) { |
| 6 | var authuserPart = |
| 7 | authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser); |
| 8 | |
| 9 | return fetch(CC_API_BASE_URL + method + authuserPart, { |
| 10 | 'headers': { |
| 11 | 'content-type': 'text/plain; charset=utf-8', |
| 12 | }, |
| 13 | 'body': JSON.stringify(data), |
| 14 | 'method': 'POST', |
| 15 | 'mode': 'cors', |
| 16 | 'credentials': (authenticated ? 'include' : 'omit'), |
| 17 | }) |
| 18 | .then(res => { |
| 19 | if (res.status == 200 || res.status == 400) { |
| 20 | return res.json().then(data => ({ |
| 21 | status: res.status, |
| 22 | body: data, |
| 23 | })); |
| 24 | } else { |
| 25 | throw new Error( |
| 26 | 'Status code ' + res.status + ' was not expected when calling ' + |
| 27 | method + '.'); |
| 28 | } |
| 29 | }) |
| 30 | .then(res => { |
| 31 | if (res.status == 400) { |
| 32 | throw new Error( |
| 33 | res.body[4] || |
| 34 | ('Response status 400 for method ' + method + '. ' + |
| 35 | 'Error code: ' + (res.body[2] ?? 'unknown'))); |
| 36 | } |
| 37 | |
| 38 | return res.body; |
| 39 | }); |
| 40 | } |