Skip to content
Snippets Groups Projects
Select Git revision
  • d09f806a41f8aa2387f44b011cdcd18c2ac3d3ff
  • main default protected
2 results

fanart_api.js

Blame
  • fanart_api.js 1.05 KiB
    import fetch from 'node-fetch';
    
    class FanartApi {
        apiKey;
        baseUrl;
    
        constructor(apiKey, baseUrl) {
            this.apiKey = apiKey;
            this.baseUrl = baseUrl || "http://webservice.fanart.tv/v3/";
        }
    
        request(path, options) {
            const url = new URL(path, this.baseUrl);
            const params = new URLSearchParams(options || {});
            params.append("api_key", this.apiKey);
            url.search = params.toString();
            return fetch(url.href, {
                options: {
                    timeout: 2000,
                },
            }).then((response) => {
                return response.text().then(text => {
                    return {
                        ok: response.ok,
                        body: text,
                    }
                });
            }).then((data) => {
                const {ok, body} = data;
                if (!ok) {
                    throw new Error(`${url}: ${body}`);
                }
                return JSON.parse(body);
            }).catch(err => {
                console.error(err);
                return null;
            });
        }
    }
    
    export default FanartApi;