felicity-lims/frontend/vite/src/composables/api_util.ts

93 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-04-01 04:29:09 +08:00
import { urqlClient } from '../urql';
2022-04-23 14:20:33 +08:00
import { ref } from 'vue'
2022-04-04 02:54:31 +08:00
import { RequestPolicy } from '@urql/vue';
2022-04-01 04:29:09 +08:00
import useNotifyToast from './alert_toast'
const {
toastSuccess, toastInfo, toastWarning, toastError,
swalSuccess, swalInfo, swalWarning, swalError
} = useNotifyToast()
2022-04-23 14:20:33 +08:00
const errors = ref<any[]>([]);
2022-04-01 04:29:09 +08:00
export default function useApiUtil(){
// Automatic Error handling from Graphql backend
const gqlErrorHandler = (error: any) => {
if(typeof(error) == 'object'){
if(error.graphQLErrors) {
const gErrors = new Set()
error.graphQLErrors?.forEach((err :any) => gErrors.add(err.message))
gErrors?.forEach((err :any) => toastError(err))
}
if(error.networkError) {
toastError(error.networkError.message);
swalError("!!OOPS!!: Something just hapenned Please login again :)")
}
}
}
const gqlResponseHandler = (res: any):any => {
2022-04-23 14:20:33 +08:00
if(res.error) {
errors.value.unshift(res.error)
gqlErrorHandler(res.error);
}
2022-04-01 04:29:09 +08:00
return res.data;
}
const gqlOpertionalErrorHandler = (res: any):any => {
2022-04-04 02:54:31 +08:00
if(res?.__typename && res?.__typename === 'OperationError') {
2022-04-23 14:20:33 +08:00
errors.value.unshift(res)
2022-04-01 04:29:09 +08:00
swalError(res.error + "\n" + res.suggestion);
return;
};
return res;
}
const GQLResponseInterceptor = (res: any): any => {
return gqlOpertionalErrorHandler(gqlResponseHandler(res))
}
2022-04-04 02:54:31 +08:00
async function withClientMutation(query, payload, dataKey): Promise<any> {
return await urqlClient
.mutation(query, payload)
.toPromise()
.then(result => {
const data = GQLResponseInterceptor(result)
2022-04-01 04:29:09 +08:00
if(dataKey){
return data[dataKey]
} else {
return data
}
})
}
2022-04-10 19:22:16 +08:00
async function withClientQuery(query, variables, dataKey, requestPolicy: RequestPolicy = 'cache-first'): Promise<any> { // cache-and-network
2022-04-01 04:29:09 +08:00
return await urqlClient
.query(query, variables, { requestPolicy })
.toPromise()
.then(result => {
const data = GQLResponseInterceptor(result)
if(dataKey){
return data[dataKey]
} else {
return data
}
})
}
// --
return {
gqlResponseHandler, gqlErrorHandler, gqlOpertionalErrorHandler,
GQLResponseInterceptor,
2022-04-04 02:54:31 +08:00
withClientMutation, withClientQuery
2022-04-01 04:29:09 +08:00
}
}