API Service
Api Service already created with base design architecture API WIT. Despite that, if there's another design architecture that different this api can be configured as what we need.
API Tools
import { createFetch } from '@vueuse/core'
import { useToast } from 'vue-toastification'
import type { MBase } from '~/core/models'
export const useMyFetch = createFetch({
baseUrl: import.meta.env.VITE_API_URL,
options: {
/**
* Setup header authorization (header name based on API needs)
*/
async beforeFetch({ options }) {
const myToken = localStorage.getItem(import.meta.env.VITE_APP_NAME) || ''
const requestHeaders: HeadersInit = new Headers()
if (myToken) {
requestHeaders.set(import.meta.env.VITE_HEADER_TOKEN, `${myToken}`)
options.headers = requestHeaders
}
return { options }
},
afterFetch(ctx) {
return ctx
},
/**
* Showing toast notification message data from API
* when error response from API http response 4xx
*
* can be OVERRIDED if needed handle error different
* @param ctx
* @returns
*/
onFetchError(ctx) {
const response: MBase.IBaseResponse<any> = ctx.data
const toast = useToast()
toast.error(response.message)
return ctx
},
},
})
API Flow Design
Base Api Service
Base API Class
where located at src > core > services > api.ts
export interface ICrudInterface {
getList<A = any>(body?: A, options?: UseFetchOptions): Promise<UseFetchReturn<MBase.IBaseResponse<any>>>
getListById<A=string, B = any>(id: A, body?: B, options?: UseFetchOptions): Promise<UseFetchReturn<MBase.IBaseResponse<any>>>
create<A = any>(body?: A, options?: UseFetchOptions): Promise<UseFetchReturn<MBase.IBaseResponse<any>>>
createById<A = string, B = any>(id: A, body?: B, options?: UseFetchOptions): Promise<UseFetchReturn<MBase.IBaseResponse<any>>>
update<A = any>(body?: A, options?: UseFetchOptions): Promise<UseFetchReturn<MBase.IBaseResponse<any>>>
updateById<A = string, B = any>(id: A, body?: B, options?: UseFetchOptions): Promise<UseFetchReturn<MBase.IBaseResponse<any>>>
delete<A = any>(body?: A, options?: UseFetchOptions): Promise<UseFetchReturn<MBase.IBaseResponse<any>>>
deleteById<A = string, B = any>(id: A, body?: B, options?: UseFetchOptions): Promise<UseFetchReturn<MBase.IBaseResponse<any>>>
find<A = any>(body?: A, options?: UseFetchOptions): Promise<UseFetchReturn<MBase.IBaseResponse<any>>>
findById<A = string, B = any>(id: A, body?: B, options?: UseFetchOptions): Promise<UseFetchReturn<MBase.IBaseResponse<any>>>
}