import fetch from 'isomorphic-unfetch' export type Config = { /** * Key to authenticate with the Nevobo API. * Not needed as of Sep. 4 but might be in the future */ apiKey?: string, /** * Run in debug mode: * Print urls before each request. */ debug?: boolean; } export type NevoboResponse = { success: boolean, reason?: string, data?: T, } export type Pagination = { page?: number, limit?: number, } export abstract class Base { private basePath: string = "https://api.nevobo.nl/v1/"; private readonly apiKey: string private readonly debug: boolean; constructor(config: Config = {}) { this.apiKey = config.apiKey this.debug = config.debug ?? false; } getArgumentErrorPromise(reason: string): Promise> { return new Promise((resolve) => { resolve( { success: false, reason: reason, } ); }); } /** * Make a request, return a Promise of a NevoboResponse * * @param endpoint to call * @param options added to the fetch * @param paginated if true some more parsing has to be done after the call */ protected request(endpoint: string, paginated: boolean = false, options?: RequestInit): Promise> { const url = this.basePath + endpoint; if (this.debug) { console.log(`Making request to ${url}`); } const headers = { 'api-key': this.apiKey, 'Content-type': 'application/json', 'Access-Control-Allow-Origin':'*', } const config = { ...options, headers, } return fetch(url, config).then(response => { return response.json(); }).then((json) => { // console.log(json); // If we get a status response, the request was bad. const success = json.status == null; const data = success ? paginated ? json["_embedded"]["items"] as T : json as T : null; return { success: success, data: data, reason: success ? null : json.detail, }; }).catch((error) => { return { success: false, reason: error, } }); } }