| 1 |
export default class CampaignsApi { |
| 2 |
private readonly apiRoot: string; |
| 3 |
private readonly headers: {'X-WP-Nonce': string; 'Content-Type': string}; |
| 4 |
|
| 5 |
constructor({apiNonce, apiRoot}) { |
| 6 |
this.apiRoot = apiRoot; |
| 7 |
this.headers = { |
| 8 |
'Content-Type': 'application/json', |
| 9 |
'X-WP-Nonce': apiNonce, |
| 10 |
}; |
| 11 |
} |
| 12 |
|
| 13 |
fetchWithArgs = (endpoint, args, method = 'GET', signal = null) => { |
| 14 |
const url = new URL(this.apiRoot + endpoint); |
| 15 |
for (const [param, value] of Object.entries(args)) { |
| 16 |
value !== '' && url.searchParams.set(param, value as string); |
| 17 |
} |
| 18 |
return fetch(url.href, { |
| 19 |
method: method, |
| 20 |
signal: signal, |
| 21 |
headers: this.headers, |
| 22 |
}) |
| 23 |
.then((res) => { |
| 24 |
if (!res.ok) { |
| 25 |
throw new Error(); |
| 26 |
} |
| 27 |
return res.text(); |
| 28 |
}) |
| 29 |
.then((text) => { |
| 30 |
try { |
| 31 |
return text ? JSON.parse(text) : {}; |
| 32 |
} catch (error) { |
| 33 |
console.error('Failed to parse JSON:', error); |
| 34 |
return {}; |
| 35 |
} |
| 36 |
}); |
| 37 |
}; |
| 38 |
} |
| 39 |
|