I'm getting an error when using fetch passed into constructor in a javascript class:
import { browser } from '$app/env';
class Api {
constructor(fetch) {
this.req = fetch;
}
async api(path, body = {}, opts = {}) {
path = import.meta.env.VITE_API_ENDPOINT + path;
body = JSON.stringify(body);
const method = opts.method || 'GET';
const headers = {};
if (browser) {
const token = localStorage.getItem('token');
headers.Authorization = token ? 'Bearer ' + token : '';
}
const res = await this.req(path, {
method: opts.method || 'GET',
body: method === 'GET' ? null : body,
headers
});
if (res.ok) {
return await (opts.raw ? res.text() : res.json());
}
throw res;
}
}
export default Api;
import Api from './create-api';
class Jobs extends Api {
constructor(fetch) {
super(fetch);
}
async getAll() {
return await this.api('/jobs');
}
}
export default Jobs;
Using it in svelte kit with await new Jobs(fetch).getAll()
I've never seen this specific error, but here's what I think is happening:
When you invoke a method on an object in javascript the scope within that method (what this points to) is bound to the object.
Because you're invoking fetch as a method on your Api instance, this likely points to the instance instead of window.
Something in the implementation of fetch expects this to be an instance of Window, hence the error.
I think you could solve this by either:
this.req = (...args) => fetch(...args)
or 2) explicitly binding fetch to window (or global or whatever):
await new Jobs(fetch.bind(window)).getAll()