mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-19 05:46:04 +00:00
updated admin to use swr hooks instead of react-query
This commit is contained in:
@@ -1,5 +1,10 @@
|
||||
import { getDefaultConfig, getDefaultSchema } from "modules/ModuleManager";
|
||||
import { createContext, startTransition, useContext, useEffect, useRef, useState } from "react";
|
||||
import { Logo } from "ui/components/display/Logo";
|
||||
import { Link } from "ui/components/wouter/Link";
|
||||
import * as AppShell from "ui/layouts/AppShell/AppShell";
|
||||
import { HeaderNavigation } from "ui/layouts/AppShell/Header";
|
||||
import { Root } from "ui/routes/root";
|
||||
import type { ModuleConfigs, ModuleSchemas } from "../../modules";
|
||||
import { useClient } from "./ClientProvider";
|
||||
import { type TSchemaActions, getSchemaActions } from "./schema/actions";
|
||||
@@ -22,8 +27,12 @@ export type { TSchemaActions };
|
||||
export function BkndProvider({
|
||||
includeSecrets = false,
|
||||
adminOverride,
|
||||
children
|
||||
}: { includeSecrets?: boolean; children: any } & Pick<BkndContext, "adminOverride">) {
|
||||
children,
|
||||
fallback = null
|
||||
}: { includeSecrets?: boolean; children: any; fallback?: React.ReactNode } & Pick<
|
||||
BkndContext,
|
||||
"adminOverride"
|
||||
>) {
|
||||
const [withSecrets, setWithSecrets] = useState<boolean>(includeSecrets);
|
||||
const [schema, setSchema] =
|
||||
useState<Pick<BkndContext, "version" | "schema" | "config" | "permissions">>();
|
||||
@@ -37,7 +46,7 @@ export function BkndProvider({
|
||||
|
||||
async function fetchSchema(_includeSecrets: boolean = false, force?: boolean) {
|
||||
if (withSecrets && !force) return;
|
||||
const { body, res } = await client.api.system.readSchema({
|
||||
const res = await client.api.system.readSchema({
|
||||
config: true,
|
||||
secrets: _includeSecrets
|
||||
});
|
||||
@@ -57,7 +66,7 @@ export function BkndProvider({
|
||||
}
|
||||
|
||||
const schema = res.ok
|
||||
? body
|
||||
? res.body
|
||||
: ({
|
||||
version: 0,
|
||||
schema: getDefaultSchema(),
|
||||
@@ -89,7 +98,7 @@ export function BkndProvider({
|
||||
fetchSchema(includeSecrets);
|
||||
}, []);
|
||||
|
||||
if (!fetched || !schema) return null;
|
||||
if (!fetched || !schema) return fallback;
|
||||
const app = new AppReduced(schema?.config as any);
|
||||
const actions = getSchemaActions({ client, setSchema, reloadSchema });
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Api } from "Api";
|
||||
import type { FetchPromise } from "modules/ModuleApi";
|
||||
import useSWR, { type SWRConfiguration, useSWRConfig } from "swr";
|
||||
import type { FetchPromise, ResponseObject } from "modules/ModuleApi";
|
||||
import useSWR, { type SWRConfiguration } from "swr";
|
||||
import { useClient } from "ui/client/ClientProvider";
|
||||
|
||||
export const useApi = () => {
|
||||
@@ -8,13 +8,16 @@ export const useApi = () => {
|
||||
return client.api;
|
||||
};
|
||||
|
||||
export const useApiQuery = <Data, RefineFn extends (data: Data) => any = (data: Data) => Data>(
|
||||
export const useApiQuery = <
|
||||
Data,
|
||||
RefineFn extends (data: ResponseObject<Data>) => any = (data: ResponseObject<Data>) => Data
|
||||
>(
|
||||
fn: (api: Api) => FetchPromise<Data>,
|
||||
options?: SWRConfiguration & { enabled?: boolean; refine?: RefineFn }
|
||||
) => {
|
||||
const api = useApi();
|
||||
const promise = fn(api);
|
||||
const refine = options?.refine ?? ((data: Data) => data);
|
||||
const refine = options?.refine ?? ((data: ResponseObject<Data>) => data);
|
||||
const fetcher = () => promise.execute().then(refine);
|
||||
const key = promise.key();
|
||||
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { PrimaryFieldType } from "core";
|
||||
import { objectTransform } from "core/utils";
|
||||
import type { EntityData, RepoQuery } from "data";
|
||||
import type { ResponseObject } from "modules/ModuleApi";
|
||||
import useSWR, { type SWRConfiguration } from "swr";
|
||||
import { useApi } from "ui/client";
|
||||
|
||||
export class UseEntityApiError<Payload = any> extends Error {
|
||||
constructor(
|
||||
public payload: Payload,
|
||||
public response: Response,
|
||||
message?: string
|
||||
) {
|
||||
super(message ?? "UseEntityApiError");
|
||||
}
|
||||
}
|
||||
|
||||
export const useEntity = <
|
||||
Entity extends string,
|
||||
Id extends PrimaryFieldType | undefined = undefined
|
||||
@@ -16,18 +27,27 @@ export const useEntity = <
|
||||
return {
|
||||
create: async (input: EntityData) => {
|
||||
const res = await api.createOne(entity, input);
|
||||
return res.data;
|
||||
if (!res.ok) {
|
||||
throw new UseEntityApiError(res.data, res.res, "Failed to create entity");
|
||||
}
|
||||
return res;
|
||||
},
|
||||
read: async (query: Partial<RepoQuery> = {}) => {
|
||||
const res = id ? await api.readOne(entity, id!, query) : await api.readMany(entity, query);
|
||||
return res.data;
|
||||
if (!res.ok) {
|
||||
throw new UseEntityApiError(res.data, res.res, "Failed to read entity");
|
||||
}
|
||||
return res;
|
||||
},
|
||||
update: async (input: Partial<EntityData>, _id: PrimaryFieldType | undefined = id) => {
|
||||
if (!_id) {
|
||||
throw new Error("id is required");
|
||||
}
|
||||
const res = await api.updateOne(entity, _id, input);
|
||||
return res.data;
|
||||
if (!res.ok) {
|
||||
throw new UseEntityApiError(res.data, res.res, "Failed to update entity");
|
||||
}
|
||||
return res;
|
||||
},
|
||||
_delete: async (_id: PrimaryFieldType | undefined = id) => {
|
||||
if (!_id) {
|
||||
@@ -35,7 +55,10 @@ export const useEntity = <
|
||||
}
|
||||
|
||||
const res = await api.deleteOne(entity, _id);
|
||||
return res.data;
|
||||
if (!res.ok) {
|
||||
throw new UseEntityApiError(res.data, res.res, "Failed to delete entity");
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -47,24 +70,30 @@ export const useEntityQuery = <
|
||||
entity: Entity,
|
||||
id?: Id,
|
||||
query?: Partial<RepoQuery>,
|
||||
options?: SWRConfiguration
|
||||
options?: SWRConfiguration & { enabled?: boolean }
|
||||
) => {
|
||||
const api = useApi().data;
|
||||
const key = [...(api.options?.basepath?.split("/") ?? []), entity, ...(id ? [id] : [])].filter(
|
||||
Boolean
|
||||
);
|
||||
const key =
|
||||
options?.enabled !== false
|
||||
? [...(api.options?.basepath?.split("/") ?? []), entity, ...(id ? [id] : [])].filter(
|
||||
Boolean
|
||||
)
|
||||
: null;
|
||||
const { read, ...actions } = useEntity(entity, id) as any;
|
||||
const fetcher = id ? () => read(query) : () => null;
|
||||
const swr = useSWR<EntityData>(id ? key : null, fetcher, options);
|
||||
const fetcher = () => read(query);
|
||||
|
||||
type T = Awaited<ReturnType<(typeof api)[Id extends undefined ? "readMany" : "readOne"]>>;
|
||||
const swr = useSWR<T>(key, fetcher, {
|
||||
revalidateOnFocus: false,
|
||||
keepPreviousData: false,
|
||||
...options
|
||||
});
|
||||
|
||||
const mapped = objectTransform(actions, (action) => {
|
||||
if (action === "read") return;
|
||||
|
||||
return async (...args) => {
|
||||
return swr.mutate(async () => {
|
||||
const res = await action(...args);
|
||||
return res;
|
||||
});
|
||||
return swr.mutate(action(...args)) as any;
|
||||
};
|
||||
}) as Omit<ReturnType<typeof useEntity<Entity, Id>>, "read">;
|
||||
|
||||
@@ -74,3 +103,18 @@ export const useEntityQuery = <
|
||||
key
|
||||
};
|
||||
};
|
||||
|
||||
export const useEntityMutate = <
|
||||
Entity extends string,
|
||||
Id extends PrimaryFieldType | undefined = undefined
|
||||
>(
|
||||
entity: Entity,
|
||||
id?: Id,
|
||||
options?: SWRConfiguration
|
||||
) => {
|
||||
const { data, ...$q } = useEntityQuery(entity, id, undefined, {
|
||||
...options,
|
||||
enabled: false
|
||||
});
|
||||
return $q;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { type NotificationData, notifications } from "@mantine/notifications";
|
||||
import { ucFirst } from "core/utils";
|
||||
import type { ApiResponse, ModuleConfigs } from "../../../modules";
|
||||
import type { ModuleConfigs } from "modules";
|
||||
import type { ResponseObject } from "modules/ModuleApi";
|
||||
import type { ConfigUpdateResponse } from "modules/server/SystemController";
|
||||
import type { AppQueryClient } from "../utils/AppQueryClient";
|
||||
|
||||
export type SchemaActionsProps = {
|
||||
@@ -14,10 +16,10 @@ export type TSchemaActions = ReturnType<typeof getSchemaActions>;
|
||||
export function getSchemaActions({ client, setSchema, reloadSchema }: SchemaActionsProps) {
|
||||
const api = client.api;
|
||||
|
||||
async function handleConfigUpdate(
|
||||
async function handleConfigUpdate<Module extends keyof ModuleConfigs>(
|
||||
action: string,
|
||||
module: string,
|
||||
res: ApiResponse,
|
||||
module: Module,
|
||||
res: ResponseObject<ConfigUpdateResponse<Module>>,
|
||||
path?: string
|
||||
): Promise<boolean> {
|
||||
const base: Partial<NotificationData> = {
|
||||
@@ -26,7 +28,7 @@ export function getSchemaActions({ client, setSchema, reloadSchema }: SchemaActi
|
||||
autoClose: 3000
|
||||
};
|
||||
|
||||
if (res.res.ok && res.body.success) {
|
||||
if (res.success === true) {
|
||||
console.log("update config", action, module, path, res.body);
|
||||
if (res.body.success) {
|
||||
setSchema((prev) => {
|
||||
@@ -35,7 +37,7 @@ export function getSchemaActions({ client, setSchema, reloadSchema }: SchemaActi
|
||||
...prev,
|
||||
config: {
|
||||
...prev.config,
|
||||
[module]: res.body.config
|
||||
[module]: res.config
|
||||
}
|
||||
};
|
||||
});
|
||||
@@ -47,18 +49,18 @@ export function getSchemaActions({ client, setSchema, reloadSchema }: SchemaActi
|
||||
color: "blue",
|
||||
message: `Operation ${action.toUpperCase()} at ${module}${path ? "." + path : ""}`
|
||||
});
|
||||
return true;
|
||||
} else {
|
||||
notifications.show({
|
||||
...base,
|
||||
title: `Config Update failed: ${ucFirst(module)}${path ? "." + path : ""}`,
|
||||
color: "red",
|
||||
withCloseButton: true,
|
||||
autoClose: false,
|
||||
message: res.error ?? "Failed to complete config update"
|
||||
});
|
||||
}
|
||||
|
||||
notifications.show({
|
||||
...base,
|
||||
title: `Config Update failed: ${ucFirst(module)}${path ? "." + path : ""}`,
|
||||
color: "red",
|
||||
withCloseButton: true,
|
||||
autoClose: false,
|
||||
message: res.body.error ?? "Failed to complete config update"
|
||||
});
|
||||
return false;
|
||||
return res.success;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -72,7 +74,7 @@ export function getSchemaActions({ client, setSchema, reloadSchema }: SchemaActi
|
||||
return await handleConfigUpdate("set", module, res);
|
||||
},
|
||||
patch: async <Module extends keyof ModuleConfigs>(
|
||||
module: keyof ModuleConfigs,
|
||||
module: Module,
|
||||
path: string,
|
||||
value: any
|
||||
): Promise<boolean> => {
|
||||
@@ -80,25 +82,18 @@ export function getSchemaActions({ client, setSchema, reloadSchema }: SchemaActi
|
||||
return await handleConfigUpdate("patch", module, res, path);
|
||||
},
|
||||
overwrite: async <Module extends keyof ModuleConfigs>(
|
||||
module: keyof ModuleConfigs,
|
||||
module: Module,
|
||||
path: string,
|
||||
value: any
|
||||
) => {
|
||||
const res = await api.system.overwriteConfig(module, path, value);
|
||||
return await handleConfigUpdate("overwrite", module, res, path);
|
||||
},
|
||||
add: async <Module extends keyof ModuleConfigs>(
|
||||
module: keyof ModuleConfigs,
|
||||
path: string,
|
||||
value: any
|
||||
) => {
|
||||
add: async <Module extends keyof ModuleConfigs>(module: Module, path: string, value: any) => {
|
||||
const res = await api.system.addConfig(module, path, value);
|
||||
return await handleConfigUpdate("add", module, res, path);
|
||||
},
|
||||
remove: async <Module extends keyof ModuleConfigs>(
|
||||
module: keyof ModuleConfigs,
|
||||
path: string
|
||||
) => {
|
||||
remove: async <Module extends keyof ModuleConfigs>(module: Module, path: string) => {
|
||||
const res = await api.system.removeConfig(module, path);
|
||||
return await handleConfigUpdate("remove", module, res, path);
|
||||
}
|
||||
|
||||
@@ -36,12 +36,10 @@ export class AppQueryClient {
|
||||
state: (): (AuthResponse & { verified: boolean }) | undefined => {
|
||||
return this.api.getAuthState() as any;
|
||||
},
|
||||
login: async (data: { email: string; password: string }): Promise<
|
||||
ApiResponse<AuthResponse>
|
||||
> => {
|
||||
login: async (data: { email: string; password: string }) => {
|
||||
return await this.api.auth.loginWithPassword(data);
|
||||
},
|
||||
register: async (data: any): Promise<ApiResponse<AuthResponse>> => {
|
||||
register: async (data: any) => {
|
||||
return await this.api.auth.registerWithPassword(data);
|
||||
},
|
||||
logout: async () => {
|
||||
@@ -57,7 +55,7 @@ export class AppQueryClient {
|
||||
//console.log("verifiying");
|
||||
const res = await this.api.auth.me();
|
||||
//console.log("verifying result", res);
|
||||
if (!res.res.ok || !res.body.user) {
|
||||
if (!res.ok || !res.body.user) {
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
@@ -90,7 +88,7 @@ export class AppQueryClient {
|
||||
typeof filename === "string" ? filename : filename.path
|
||||
);
|
||||
|
||||
if (res.res.ok) {
|
||||
if (res.ok) {
|
||||
queryClient.invalidateQueries({ queryKey: ["data", "entity", "media"] });
|
||||
return true;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user