improve unnecessary data fetches

This commit is contained in:
Hayden 2023-02-05 11:26:34 -09:00
parent d9dd1e22cb
commit dd7a8099ef
No known key found for this signature in database
GPG key ID: 17CF79474E257545
3 changed files with 17 additions and 10 deletions

View file

@ -4,7 +4,7 @@ import { Requests } from "~~/lib/requests";
import { useAuthStore } from "~~/stores/auth";
export type Observer = {
handler: (r: Response) => void;
handler: (r: Response, req?: RequestInit) => void;
};
export type RemoveObserver = () => void;

View file

@ -181,11 +181,18 @@
},
];
function isMutation(method: string | undefined) {
return method === "POST" || method === "PUT" || method === "DELETE";
}
function isSuccess(status: number) {
return status >= 200 && status < 300;
}
const labelStore = useLabelStore();
const reLabel = /\/api\/v1\/labels\/.*/gm;
const rmLabelStoreObserver = defineObserver("labelStore", {
handler: r => {
if (r.status === 201 || r.url.match(reLabel)) {
handler: (resp, req) => {
if (isMutation(req?.method) && isSuccess(resp.status) && resp.url.match(reLabel)) {
labelStore.refresh();
}
console.debug("labelStore handler called by observer");
@ -195,11 +202,12 @@
const locationStore = useLocationStore();
const reLocation = /\/api\/v1\/locations\/.*/gm;
const rmLocationStoreObserver = defineObserver("locationStore", {
handler: r => {
if (r.status === 201 || r.url.match(reLocation)) {
handler: (resp, req) => {
if (isMutation(req?.method) && isSuccess(resp.status) && resp.url.match(reLocation)) {
locationStore.refreshChildren();
locationStore.refreshParents();
}
console.debug("locationStore handler called by observer");
},
});

View file

@ -5,8 +5,7 @@ export enum Method {
DELETE = "DELETE",
}
export type RequestInterceptor = (r: Response) => void;
export type ResponseInterceptor = (r: Response) => void;
export type ResponseInterceptor = (r: Response, rq?: RequestInit) => void;
export interface TResponse<T> {
status: number;
@ -32,8 +31,8 @@ export class Requests {
this.responseInterceptors.push(interceptor);
}
private callResponseInterceptors(response: Response) {
this.responseInterceptors.forEach(i => i(response));
private callResponseInterceptors(response: Response, request?: RequestInit) {
this.responseInterceptors.forEach(i => i(response, request));
}
private url(rest: string): string {
@ -90,7 +89,7 @@ export class Requests {
}
const response = await fetch(this.url(rargs.url), payload);
this.callResponseInterceptors(response);
this.callResponseInterceptors(response, payload);
const data: T = await (async () => {
if (response.status === 204) {