Files
pendaftaran/utils/api/client.ts
2024-12-27 16:46:43 +07:00

74 lines
1.8 KiB
TypeScript

import type {FetchOptions} from 'ofetch';
export default class Client {
options?: FetchOptions;
baseUrl: string;
constructor(baseUrl: string, options?: FetchOptions) {
this.options = options;
this.baseUrl = baseUrl;
}
async raw<T>(url: string, method: 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'get' | 'head' | 'patch' | 'post' | 'put' | 'delete' | 'connect' | 'options' | 'trace') {
try {
const response = await $fetch.raw<T>(`${this.baseUrl}${url}`, {
// ...options,
...this.options,
method
})
return response;
} catch (err) {
return Promise.reject(err);
}
}
async post<T>(ur: string, options?: FetchOptions,) {
try {
const response = await $fetch.raw<T>(`${this.baseUrl}${ur}`, {
...options,
...this.options,
method: 'POST'
})
return response;
} catch (err) {
return Promise.reject(err);
}
}
async get<T>(ur: string, options?: FetchOptions,) {
try {
const response = await $fetch.raw<T>(`${this.baseUrl}${ur}`, {
...options,
...this.options,
method: 'GET'
})
return response;
} catch (err) {
return Promise.reject(err);
}
}
async put<T>(ur: string, options?: FetchOptions,) {
try {
const response = await $fetch.raw<T>(`${this.baseUrl}${ur}`, {
...options,
...this.options,
method: 'PUT'
})
return response;
} catch (err) {
return Promise.reject(err);
}
}
async del<T>(ur: string, options?: FetchOptions,) {
try {
const response = await $fetch.raw<T>(`${this.baseUrl}${ur}`, {
...options,
...this.options,
method: 'DELETE'
})
return response;
} catch (err) {
return Promise.reject(err);
}
}
}