conjure-frontend/src/services/base-service.ts

69 lines
1.7 KiB
TypeScript

export class BaseService {
protected apiUrl: string | undefined = import.meta.env.VITE_CONJUREOS_HOST
protected baseHeaders: Record<string, string> = {
'Accept': 'application/json',
'API-Version': '1'
}
protected jsonHeaders: Record<string, string> = {
'Content-Type': 'application/json',
}
public constructor() {
}
protected async get<T>(path: string, headers?: HeadersInit): Promise<T> {
return await (await fetch(this.apiUrl + path, {
method: 'GET',
headers: {
...headers,
...this.baseHeaders
}
})).json() as T
}
protected async post<T extends object>(path: string, body: T, headers?: HeadersInit): Promise<Response> {
return await fetch(this.apiUrl + path, {
method: 'POST',
body: JSON.stringify(body) as any,
headers: {
...headers,
...this.jsonHeaders,
...this.baseHeaders
}
});
}
protected async postForm(path: string, body: FormData, headers?: HeadersInit): Promise<Response> {
return await fetch(this.apiUrl + path, {
method: 'POST',
body: body,
headers: {
...headers,
...this.baseHeaders
}
});
}
protected async put<T>(path: string, body: T, headers?: HeadersInit): Promise<Response> {
return await fetch(this.apiUrl + path, {
method: 'PUT',
body: JSON.stringify(body),
headers: {
...headers,
...this.jsonHeaders,
...this.baseHeaders
}
});
}
protected async delete(path: string, headers?: HeadersInit): Promise<Response> {
return await fetch(this.apiUrl + path, {
method: 'DELETE',
headers: {
...headers,
...this.baseHeaders
}
});
}
}