improved DataApi types

- Added type definitions for entity data in DataApi, improving type safety across CRUD operations.
- Introduced new test cases in DataApi.spec.ts to validate the behavior of read and create operations, ensuring correct data handling and response types.
- Updated various files to accommodate the new type definitions and ensure compatibility with existing functionality.
This commit is contained in:
dswbx
2025-10-17 09:45:22 +02:00
parent f4a7cde487
commit 0a93a4a16c
13 changed files with 235 additions and 80 deletions
+145 -1
View File
@@ -1,4 +1,4 @@
import { afterAll, beforeAll, describe, expect, it } from "bun:test"; import { afterAll, beforeAll, describe, expect, it, expectTypeOf } from "bun:test";
import { Guard } from "../../src/auth/authorize/Guard"; import { Guard } from "../../src/auth/authorize/Guard";
import { DataApi } from "../../src/data/api/DataApi"; import { DataApi } from "../../src/data/api/DataApi";
import { DataController } from "../../src/data/api/DataController"; import { DataController } from "../../src/data/api/DataController";
@@ -7,6 +7,7 @@ import * as proto from "../../src/data/prototype";
import { schemaToEm } from "../helper"; import { schemaToEm } from "../helper";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test"; import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
import { parse } from "core/utils/schema"; import { parse } from "core/utils/schema";
import type { Generated } from "kysely";
beforeAll(disableConsoleLog); beforeAll(disableConsoleLog);
afterAll(enableConsoleLog); afterAll(enableConsoleLog);
@@ -219,4 +220,147 @@ describe("DataApi", () => {
expect(() => api.createMany("posts", [])).toThrow(); expect(() => api.createMany("posts", [])).toThrow();
} }
}); });
describe("types", async () => {
const schema = proto.em(
{
posts: proto.entity("posts", { title: proto.text(), count: proto.number() }),
comments: proto.entity("comments", { text: proto.text() }),
},
(fn, s) => {
fn.relation(s.comments).manyToOne(s.posts);
},
);
const em = schemaToEm(schema);
await em.schema().sync({ force: true });
const data = {
posts: [
{ title: "foo", count: 0 },
{ title: "bar", count: 0 },
{ title: "baz", count: 0 },
{ title: "bla", count: 2 },
],
comments: [
{ text: "comment1", posts_id: 1 },
{ text: "comment2", posts_id: 1 },
{ text: "comment3", posts_id: 2 },
],
};
const ctx: any = { em, guard: new Guard() };
const controller = new DataController(ctx, dataConfig);
const app = controller.getController();
type Posts = {
id: Generated<number>;
title?: string;
count?: number;
comments?: Comments[];
};
type Comments = {
id: Generated<number>;
text?: string;
posts_id?: number;
posts?: Posts;
};
type DB = {
posts: Posts;
comments: Comments;
};
const api = new DataApi<DB>({ basepath: "/" }, app.request);
for (const [entity, payload] of Object.entries(data)) {
await api.createMany(entity as any, payload);
}
it("readOne", async () => {
const result = await api.readOne("posts", 1);
const expected = { id: 1, title: "foo", count: 0 } as any;
expect(result.res).toBeInstanceOf(Response);
expect(result.data).toEqual(expected);
expect(result.body.meta.items).toEqual(1);
expectTypeOf<(typeof result)["data"]>().toEqualTypeOf<Posts | null>();
{
// not found
const result = await api.readOne("posts", 0);
expect(result.res.status).toEqual(404);
expect(result.data).toBeNull();
expect(result.body.meta.items).toEqual(0);
expectTypeOf<(typeof result)["data"]>().toEqualTypeOf<Posts | null>();
}
});
it("readOneBy", async () => {
const result = await api.readOneBy("posts", { where: { title: "foo" } });
const expected = { id: 1, title: "foo", count: 0 } as any;
expect(result.res.status).toEqual(200);
expect(result.data).toEqual(expected);
// @ts-expect-error body data is typed same as data...
expect(result.body.data).toEqual([expected]); // should be array
expect(result.body.meta.items).toEqual(1);
expectTypeOf<(typeof result)["data"]>().toEqualTypeOf<Posts | null>();
{
// not found
const result = await api.readOneBy("posts", { where: { title: "not found" } });
// since we're filtering, the result is okay, but empty
expect(result.res.status).toEqual(200);
expect(result.data).toBeNull();
// @ts-expect-error body data is typed same as data...
expect(result.body.data).toEqual([]);
expect(result.body.meta.items).toEqual(0);
expectTypeOf<(typeof result)["data"]>().toEqualTypeOf<Posts | null>();
}
});
it("readMany", async () => {
const result = await api.readMany("posts", { where: { title: "foo" } });
const expected = [{ id: 1, title: "foo", count: 0 }] as any;
expect(result.res.status).toEqual(200);
expect(result.data).toEqual(expected);
expect(result.body.data).toEqual(expected);
expect(result.body.meta.items).toEqual(1);
expectTypeOf<(typeof result)["data"]>().toEqualTypeOf<Posts[]>();
{
// not found
const result = await api.readMany("posts", { where: { title: "not found" } });
expect(result.res.status).toEqual(200);
expect(result.data).toEqual([]);
expect(result.body.meta.items).toEqual(0);
expectTypeOf<(typeof result)["data"]>().toEqualTypeOf<Posts[]>();
}
});
it("readManyByReference", async () => {
const result = await api.readManyByReference("posts", 1, "comments");
const expected = [
{ id: 1, text: "comment1", posts_id: 1 },
{ id: 2, text: "comment2", posts_id: 1 },
] as any;
expect(result.res.status).toEqual(200);
expect(result.data).toEqual(expected);
expect(result.body.meta.items).toEqual(2);
expectTypeOf<(typeof result)["data"]>().toEqualTypeOf<Comments[]>();
{
// empty
const result = await api.readManyByReference("posts", 3, "comments");
expect(result.res.status).toEqual(200);
expect(result.data).toEqual([]);
expect(result.body.meta.items).toEqual(0);
expectTypeOf<(typeof result)["data"]>().toEqualTypeOf<Comments[]>();
}
{
// non existing (expected, since only 1 query is performed)
const result = await api.readManyByReference("posts", 100, "comments");
expect(result.res.status).toEqual(200);
expect(result.data).toEqual([]);
}
});
});
}); });
+2 -1
View File
@@ -1,6 +1,7 @@
/** /**
* These are package global defaults. * These are package global defaults.
*/ */
import type { EntityData } from "data/entities";
import type { Generated } from "kysely"; import type { Generated } from "kysely";
export type PrimaryFieldType<IdType = number | string> = IdType | Generated<IdType>; export type PrimaryFieldType<IdType = number | string> = IdType | Generated<IdType>;
@@ -16,7 +17,7 @@ export interface DB {
[key: string]: any; [key: string]: any;
}; */ }; */
// @todo: that's not good, but required for admin options // @todo: that's not good, but required for admin options
[key: string]: any; [key: string]: EntityData;
} }
export const config = { export const config = {
+27 -26
View File
@@ -1,4 +1,4 @@
import type { DB, EntityData, RepoQueryIn } from "bknd"; import type { DB as DefaultDB, EntityData, RepoQueryIn } from "bknd";
import type { Insertable, Selectable, Updateable } from "kysely"; import type { Insertable, Selectable, Updateable } from "kysely";
import { type BaseModuleApiOptions, ModuleApi, type PrimaryFieldType } from "modules"; import { type BaseModuleApiOptions, ModuleApi, type PrimaryFieldType } from "modules";
@@ -10,7 +10,9 @@ export type DataApiOptions = BaseModuleApiOptions & {
defaultQuery: Partial<RepoQueryIn>; defaultQuery: Partial<RepoQueryIn>;
}; };
export class DataApi extends ModuleApi<DataApiOptions> { type EntityObject<DB, E> = E extends keyof DB ? DB[E] : EntityData;
export class DataApi<DB = DefaultDB> extends ModuleApi<DataApiOptions> {
protected override getDefaultOptions(): Partial<DataApiOptions> { protected override getDefaultOptions(): Partial<DataApiOptions> {
return { return {
basepath: "/api/data", basepath: "/api/data",
@@ -32,29 +34,26 @@ export class DataApi extends ModuleApi<DataApiOptions> {
id: PrimaryFieldType, id: PrimaryFieldType,
query: Omit<RepoQueryIn, "where" | "limit" | "offset"> = {}, query: Omit<RepoQueryIn, "where" | "limit" | "offset"> = {},
) { ) {
type Data = E extends keyof DB ? Selectable<DB[E]> : EntityData; type T = RepositoryResultJSON<EntityObject<DB, E> | null>;
return this.get<RepositoryResultJSON<Data>>(["entity", entity as any, id], query); return this.get<T>(["entity", entity as any, id], query);
} }
readOneBy<E extends keyof DB | string>( readOneBy<E extends keyof DB | string>(
entity: E, entity: E,
query: Omit<RepoQueryIn, "limit" | "offset" | "sort"> = {}, query: Omit<RepoQueryIn, "limit" | "offset" | "sort"> = {},
) { ) {
type Data = E extends keyof DB ? Selectable<DB[E]> : EntityData; // @todo: if none found, it still returns 200, since it's readMany
type T = RepositoryResultJSON<Data>;
// @todo: if none found, still returns meta...
return this.readMany(entity, { return this.readMany(entity, {
...query, ...query,
limit: 1, limit: 1,
offset: 0, offset: 0,
}).refine((data) => data[0]) as unknown as FetchPromise<ResponseObject<T>>; }).refine((data) => data[0] ?? null) as unknown as FetchPromise<
ResponseObject<RepositoryResultJSON<EntityObject<DB, E> | null>>
>;
} }
readMany<E extends keyof DB | string>(entity: E, query: RepoQueryIn = {}) { readMany<E extends keyof DB | string>(entity: E, query: RepoQueryIn = {}) {
type Data = E extends keyof DB ? Selectable<DB[E]> : EntityData; type T = RepositoryResultJSON<EntityObject<DB, E>[]>;
type T = RepositoryResultJSON<Data[]>;
const input = query ?? this.options.defaultQuery; const input = query ?? this.options.defaultQuery;
const req = this.get<T>(["entity", entity as any], input); const req = this.get<T>(["entity", entity as any], input);
@@ -72,8 +71,7 @@ export class DataApi extends ModuleApi<DataApiOptions> {
reference: R, reference: R,
query: RepoQueryIn = {}, query: RepoQueryIn = {},
) { ) {
type Data = R extends keyof DB ? Selectable<DB[R]> : EntityData; return this.get<RepositoryResultJSON<EntityObject<DB, R>[]>>(
return this.get<RepositoryResultJSON<Data[]>>(
["entity", entity as any, id, reference], ["entity", entity as any, id, reference],
query ?? this.options.defaultQuery, query ?? this.options.defaultQuery,
); );
@@ -83,8 +81,7 @@ export class DataApi extends ModuleApi<DataApiOptions> {
entity: E, entity: E,
input: Insertable<Input>, input: Insertable<Input>,
) { ) {
type Data = E extends keyof DB ? Selectable<DB[E]> : EntityData; return this.post<RepositoryResultJSON<EntityObject<DB, E>>>(["entity", entity as any], input);
return this.post<RepositoryResultJSON<Data>>(["entity", entity as any], input);
} }
createMany<E extends keyof DB | string, Input = E extends keyof DB ? DB[E] : EntityData>( createMany<E extends keyof DB | string, Input = E extends keyof DB ? DB[E] : EntityData>(
@@ -94,8 +91,10 @@ export class DataApi extends ModuleApi<DataApiOptions> {
if (!input || !Array.isArray(input) || input.length === 0) { if (!input || !Array.isArray(input) || input.length === 0) {
throw new Error("input is required"); throw new Error("input is required");
} }
type Data = E extends keyof DB ? Selectable<DB[E]> : EntityData; return this.post<RepositoryResultJSON<EntityObject<DB, E>[]>>(
return this.post<RepositoryResultJSON<Data[]>>(["entity", entity as any], input); ["entity", entity as any],
input,
);
} }
updateOne<E extends keyof DB | string, Input = E extends keyof DB ? DB[E] : EntityData>( updateOne<E extends keyof DB | string, Input = E extends keyof DB ? DB[E] : EntityData>(
@@ -104,8 +103,10 @@ export class DataApi extends ModuleApi<DataApiOptions> {
input: Updateable<Input>, input: Updateable<Input>,
) { ) {
if (!id) throw new Error("ID is required"); if (!id) throw new Error("ID is required");
type Data = E extends keyof DB ? Selectable<DB[E]> : EntityData; return this.patch<RepositoryResultJSON<EntityObject<DB, E>>>(
return this.patch<RepositoryResultJSON<Data>>(["entity", entity as any, id], input); ["entity", entity as any, id],
input,
);
} }
updateMany<E extends keyof DB | string, Input = E extends keyof DB ? DB[E] : EntityData>( updateMany<E extends keyof DB | string, Input = E extends keyof DB ? DB[E] : EntityData>(
@@ -114,8 +115,7 @@ export class DataApi extends ModuleApi<DataApiOptions> {
update: Updateable<Input>, update: Updateable<Input>,
) { ) {
this.requireObjectSet(where); this.requireObjectSet(where);
type Data = E extends keyof DB ? Selectable<DB[E]> : EntityData; return this.patch<RepositoryResultJSON<EntityObject<DB, E>[]>>(["entity", entity as any], {
return this.patch<RepositoryResultJSON<Data[]>>(["entity", entity as any], {
update, update,
where, where,
}); });
@@ -123,14 +123,15 @@ export class DataApi extends ModuleApi<DataApiOptions> {
deleteOne<E extends keyof DB | string>(entity: E, id: PrimaryFieldType) { deleteOne<E extends keyof DB | string>(entity: E, id: PrimaryFieldType) {
if (!id) throw new Error("ID is required"); if (!id) throw new Error("ID is required");
type Data = E extends keyof DB ? Selectable<DB[E]> : EntityData; return this.delete<RepositoryResultJSON<EntityObject<DB, E>>>(["entity", entity as any, id]);
return this.delete<RepositoryResultJSON<Data>>(["entity", entity as any, id]);
} }
deleteMany<E extends keyof DB | string>(entity: E, where: RepoQueryIn["where"]) { deleteMany<E extends keyof DB | string>(entity: E, where: RepoQueryIn["where"]) {
this.requireObjectSet(where); this.requireObjectSet(where);
type Data = E extends keyof DB ? Selectable<DB[E]> : EntityData; return this.delete<RepositoryResultJSON<EntityObject<DB, E>[]>>(
return this.delete<RepositoryResultJSON<Data>>(["entity", entity as any], where); ["entity", entity as any],
where,
);
} }
count<E extends keyof DB | string>(entity: E, where: RepoQueryIn["where"] = {}) { count<E extends keyof DB | string>(entity: E, where: RepoQueryIn["where"] = {}) {
+5 -2
View File
@@ -1,4 +1,4 @@
import { config } from "core/config"; import { config, type PrimaryFieldType } from "core/config";
import { snakeToPascalWithSpaces, transformObject, $console, s, parse } from "bknd/utils"; import { snakeToPascalWithSpaces, transformObject, $console, s, parse } from "bknd/utils";
import { import {
type Field, type Field,
@@ -25,7 +25,10 @@ export const entityConfigSchema = s
export type EntityConfig = s.Static<typeof entityConfigSchema>; export type EntityConfig = s.Static<typeof entityConfigSchema>;
export type EntityData = Record<string, any>; export type EntityData = {
id: PrimaryFieldType;
[key: string]: any;
};
export type EntityJSON = ReturnType<Entity["toJSON"]>; export type EntityJSON = ReturnType<Entity["toJSON"]>;
/** /**
+1 -1
View File
@@ -119,7 +119,7 @@ export class Result<T = unknown> {
const keys = isDebug() ? ["items", "time", "sql", "parameters"] : ["items", "time"]; const keys = isDebug() ? ["items", "time", "sql", "parameters"] : ["items", "time"];
const meta = pick(metaRaw, [...keys, ...this.additionalMetaKeys()] as any); const meta = pick(metaRaw, [...keys, ...this.additionalMetaKeys()] as any);
return { return {
data: this.data, data: this.data ? this.data : ((this.options.single ? null : []) as T),
meta, meta,
}; };
} }
+7 -7
View File
@@ -54,7 +54,7 @@ export class Mutator<
} }
const keys = Object.keys(data as any); const keys = Object.keys(data as any);
const validatedData: EntityData = {}; const validatedData: Partial<EntityData> = {};
// get relational references/keys // get relational references/keys
const relationMutator = new RelationMutator(entity, this.em); const relationMutator = new RelationMutator(entity, this.em);
@@ -101,10 +101,10 @@ export class Mutator<
return validatedData as Given; return validatedData as Given;
} }
protected async performQuery<T = EntityData[]>( protected async performQuery<O extends MutatorResultOptions>(
qb: MutatorQB, qb: MutatorQB,
opts?: MutatorResultOptions, opts?: O,
): Promise<MutatorResult<T>> { ): Promise<MutatorResult<O extends { single: true } ? EntityData : EntityData[]>> {
const result = new MutatorResult(this.em, this.entity, { const result = new MutatorResult(this.em, this.entity, {
silent: false, silent: false,
...opts, ...opts,
@@ -282,7 +282,7 @@ export class Mutator<
entity.getSelect(), entity.getSelect(),
); );
return await this.performQuery(qb); return (await this.performQuery(qb)) as any;
} }
async updateWhere( async updateWhere(
@@ -301,7 +301,7 @@ export class Mutator<
.set(validatedData as any) .set(validatedData as any)
.returning(entity.getSelect()); .returning(entity.getSelect());
return await this.performQuery(query); return (await this.performQuery(query)) as any;
} }
async insertMany(data: Input[]): Promise<MutatorResult<Output[]>> { async insertMany(data: Input[]): Promise<MutatorResult<Output[]>> {
@@ -336,6 +336,6 @@ export class Mutator<
.values(validated) .values(validated)
.returning(entity.getSelect()); .returning(entity.getSelect());
return await this.performQuery(query); return (await this.performQuery(query)) as any;
} }
} }
+11 -3
View File
@@ -180,15 +180,23 @@ export class Repository<TBD extends object = DefaultDB, TB extends keyof TBD = a
private async triggerFindAfter( private async triggerFindAfter(
entity: Entity, entity: Entity,
options: RepoQuery, options: RepoQuery,
data: EntityData[], data: EntityData | EntityData[],
): Promise<void> { ): Promise<void> {
if (options.limit === 1) { if (options.limit === 1) {
await this.emgr.emit( await this.emgr.emit(
new Repository.Events.RepositoryFindOneAfter({ entity, options, data }), new Repository.Events.RepositoryFindOneAfter({
entity,
options,
data: data as EntityData,
}),
); );
} else { } else {
await this.emgr.emit( await this.emgr.emit(
new Repository.Events.RepositoryFindManyAfter({ entity, options, data }), new Repository.Events.RepositoryFindManyAfter({
entity,
options,
data: data as EntityData[],
}),
); );
} }
} }
+7 -5
View File
@@ -4,6 +4,8 @@ import { Event, InvalidEventReturn } from "core/events";
import type { Entity, EntityData } from "../entities"; import type { Entity, EntityData } from "../entities";
import type { RepoQuery } from "data/server/query"; import type { RepoQuery } from "data/server/query";
type PartialEntityData = Omit<EntityData, "id">;
export class MutatorInsertBefore extends Event<{ entity: Entity; data: EntityData }, EntityData> { export class MutatorInsertBefore extends Event<{ entity: Entity; data: EntityData }, EntityData> {
static override slug = "mutator-insert-before"; static override slug = "mutator-insert-before";
@@ -26,7 +28,7 @@ export class MutatorInsertBefore extends Event<{ entity: Entity; data: EntityDat
export class MutatorInsertAfter extends Event<{ export class MutatorInsertAfter extends Event<{
entity: Entity; entity: Entity;
data: EntityData; data: EntityData;
changed: EntityData; changed: PartialEntityData;
}> { }> {
static override slug = "mutator-insert-after"; static override slug = "mutator-insert-after";
} }
@@ -34,7 +36,7 @@ export class MutatorUpdateBefore extends Event<
{ {
entity: Entity; entity: Entity;
entityId: PrimaryFieldType; entityId: PrimaryFieldType;
data: EntityData; data: PartialEntityData;
}, },
EntityData EntityData
> { > {
@@ -61,8 +63,8 @@ export class MutatorUpdateBefore extends Event<
export class MutatorUpdateAfter extends Event<{ export class MutatorUpdateAfter extends Event<{
entity: Entity; entity: Entity;
entityId: PrimaryFieldType; entityId: PrimaryFieldType;
data: EntityData; data: PartialEntityData;
changed: EntityData; changed: PartialEntityData;
}> { }> {
static override slug = "mutator-update-after"; static override slug = "mutator-update-after";
} }
@@ -104,7 +106,7 @@ export class RepositoryFindManyBefore extends Event<{ entity: Entity; options: R
export class RepositoryFindManyAfter extends Event<{ export class RepositoryFindManyAfter extends Event<{
entity: Entity; entity: Entity;
options: RepoQuery; options: RepoQuery;
data: EntityData; data: EntityData[];
}> { }> {
static override slug = "repository-find-many-after"; static override slug = "repository-find-many-after";
} }
+1 -1
View File
@@ -16,7 +16,7 @@ export function getDefaultValues(fields: Field[], data: EntityData): EntityData
export function getChangeSet( export function getChangeSet(
action: string, action: string,
formData: EntityData, formData: EntityData,
data: EntityData, data: EntityData | object,
fields: Field[], fields: Field[],
): EntityData { ): EntityData {
return transform( return transform(
+2 -4
View File
@@ -167,7 +167,6 @@ export type ResponseObject<Body = any, Data = Body extends { data: infer R } ? R
data: Data; data: Data;
body: Body; body: Body;
ok: boolean; ok: boolean;
status: number;
toJSON(): Data; toJSON(): Data;
}; };
@@ -177,10 +176,10 @@ export function createResponseProxy<Body = any, Data = any>(
data?: Data, data?: Data,
): ResponseObject<Body, Data> { ): ResponseObject<Body, Data> {
let actualData: any = typeof data !== "undefined" ? data : body; let actualData: any = typeof data !== "undefined" ? data : body;
const _props = ["raw", "body", "ok", "status", "res", "data", "toJSON"]; const _props = ["raw", "body", "ok", "res", "data", "toJSON"];
// that's okay, since you have to check res.ok anyway // that's okay, since you have to check res.ok anyway
if (typeof actualData !== "object") { if (typeof actualData !== "object" || actualData === null) {
actualData = {}; actualData = {};
} }
@@ -190,7 +189,6 @@ export function createResponseProxy<Body = any, Data = any>(
if (prop === "body") return body; if (prop === "body") return body;
if (prop === "data") return data; if (prop === "data") return data;
if (prop === "ok") return raw.ok; if (prop === "ok") return raw.ok;
if (prop === "status") return raw.status;
if (prop === "toJSON") { if (prop === "toJSON") {
return () => target; return () => target;
} }
+24 -26
View File
@@ -3,13 +3,12 @@ import type {
PrimaryFieldType, PrimaryFieldType,
EntityData, EntityData,
RepoQueryIn, RepoQueryIn,
RepositoryResult,
ResponseObject, ResponseObject,
ModuleApi, ModuleApi,
} from "bknd"; } from "bknd";
import { objectTransform, encodeSearch } from "bknd/utils"; import { objectTransform, encodeSearch } from "bknd/utils";
import type { Insertable, Selectable, Updateable } from "kysely"; import type { Insertable, Updateable } from "kysely";
import useSWR, { type SWRConfiguration, type SWRResponse, mutate } from "swr"; import useSWR, { type SWRConfiguration, type SWRResponse, mutate, type KeyedMutator } from "swr";
import { type Api, useApi } from "ui/client"; import { type Api, useApi } from "ui/client";
export class UseEntityApiError<Payload = any> extends Error { export class UseEntityApiError<Payload = any> extends Error {
@@ -33,18 +32,16 @@ interface UseEntityReturn<
Entity extends keyof DB | string, Entity extends keyof DB | string,
Id extends PrimaryFieldType | undefined, Id extends PrimaryFieldType | undefined,
Data = Entity extends keyof DB ? DB[Entity] : EntityData, Data = Entity extends keyof DB ? DB[Entity] : EntityData,
Response = ResponseObject<RepositoryResult<Selectable<Data>>>, Response = ResponseObject<Data>,
> { > {
create: (input: Insertable<Data>) => Promise<Response>; create: (input: Insertable<Data>) => Promise<Response>;
read: ( read: (query?: RepoQueryIn) => Promise<ResponseObject<Id extends undefined ? Data[] : Data>>;
query?: RepoQueryIn,
) => Promise<
ResponseObject<RepositoryResult<Id extends undefined ? Selectable<Data>[] : Selectable<Data>>>
>;
update: Id extends undefined update: Id extends undefined
? (input: Updateable<Data>, id: Id) => Promise<Response> ? (input: Updateable<Data>, id: PrimaryFieldType) => Promise<Response>
: (input: Updateable<Data>) => Promise<Response>; : (input: Updateable<Data>) => Promise<Response>;
_delete: Id extends undefined ? (id: Id) => Promise<Response> : () => Promise<Response>; _delete: Id extends undefined
? (id: PrimaryFieldType) => Promise<Response>
: () => Promise<Response>;
} }
export const useEntity = < export const useEntity = <
@@ -60,14 +57,14 @@ export const useEntity = <
return { return {
create: async (input: Insertable<Data>) => { create: async (input: Insertable<Data>) => {
const res = await api.createOne(entity, input as any); const res = await api.createOne(entity, input as any);
if (!res.ok) { if (!res.res.ok) {
throw new UseEntityApiError(res, `Failed to create entity "${entity}"`); throw new UseEntityApiError(res, `Failed to create entity "${entity}"`);
} }
return res as any; return res as any;
}, },
read: async (query?: RepoQueryIn) => { read: async (query?: RepoQueryIn) => {
const res = id ? await api.readOne(entity, id!, query) : await api.readMany(entity, query); const res = id ? await api.readOne(entity, id!, query) : await api.readMany(entity, query);
if (!res.ok) { if (!res.res.ok) {
throw new UseEntityApiError(res as any, `Failed to read entity "${entity}"`); throw new UseEntityApiError(res as any, `Failed to read entity "${entity}"`);
} }
return res as any; return res as any;
@@ -78,7 +75,7 @@ export const useEntity = <
throw new Error("id is required"); throw new Error("id is required");
} }
const res = await api.updateOne(entity, _id, input); const res = await api.updateOne(entity, _id, input);
if (!res.ok) { if (!res.res.ok) {
throw new UseEntityApiError(res, `Failed to update entity "${entity}"`); throw new UseEntityApiError(res, `Failed to update entity "${entity}"`);
} }
return res as any; return res as any;
@@ -90,7 +87,7 @@ export const useEntity = <
} }
const res = await api.deleteOne(entity, _id); const res = await api.deleteOne(entity, _id);
if (!res.ok) { if (!res.res.ok) {
throw new UseEntityApiError(res, `Failed to delete entity "${entity}"`); throw new UseEntityApiError(res, `Failed to delete entity "${entity}"`);
} }
return res as any; return res as any;
@@ -117,12 +114,12 @@ export function makeKey(
export interface UseEntityQueryReturn< export interface UseEntityQueryReturn<
Entity extends keyof DB | string, Entity extends keyof DB | string,
Id extends PrimaryFieldType | undefined = undefined, Id extends PrimaryFieldType | undefined = undefined,
Data = Entity extends keyof DB ? Selectable<DB[Entity]> : EntityData, Data = DB[Entity],
Return = Id extends undefined ? ResponseObject<Data[]> : ResponseObject<Data>, Return = Id extends undefined ? Data[] : Data,
> extends Omit<SWRResponse<Return>, "mutate">, > extends Omit<SWRResponse<Return>, "mutate">,
Omit<ReturnType<typeof useEntity<Entity, Id>>, "read"> { Omit<ReturnType<typeof useEntity<Entity, Id>>, "read"> {
mutate: (id?: PrimaryFieldType) => Promise<any>; mutate: (id?: PrimaryFieldType) => Promise<any>;
mutateRaw: SWRResponse<Return>["mutate"]; mutateRaw: KeyedMutator<Data | Data[]>;
api: Api["data"]; api: Api["data"];
key: string; key: string;
} }
@@ -169,21 +166,23 @@ export const useEntityQuery = <
}; };
}) as Omit<ReturnType<typeof useEntity<Entity, Id>>, "read">; }) as Omit<ReturnType<typeof useEntity<Entity, Id>>, "read">;
const data = swr.data ? swr.data.data : id ? null : [];
return { return {
...swr, ...swr,
...mapped, ...mapped,
data,
mutate: mutateFn, mutate: mutateFn,
// @ts-ignore
mutateRaw: swr.mutate, mutateRaw: swr.mutate,
api, api,
key, key,
}; } as any;
}; };
export async function mutateEntityCache< export async function mutateEntityCache<
Entity extends keyof DB | string, Entity extends keyof DB | string,
Data = Entity extends keyof DB ? DB[Entity] : EntityData, Data = Entity extends keyof DB ? DB[Entity] : EntityData,
>(api: Api["data"], entity: Entity, id: PrimaryFieldType, partialData: Partial<Selectable<Data>>) { >(api: Api["data"], entity: Entity, id: PrimaryFieldType, partialData: Partial<Data>) {
function update(prev: any, partialNext: any) { function update(prev: any, partialNext: any) {
if ( if (
typeof prev !== "undefined" && typeof prev !== "undefined" &&
@@ -220,8 +219,8 @@ interface UseEntityMutateReturn<
Data = Entity extends keyof DB ? DB[Entity] : EntityData, Data = Entity extends keyof DB ? DB[Entity] : EntityData,
> extends Omit<ReturnType<typeof useEntityQuery<Entity, Id>>, "mutate"> { > extends Omit<ReturnType<typeof useEntityQuery<Entity, Id>>, "mutate"> {
mutate: Id extends undefined mutate: Id extends undefined
? (id: PrimaryFieldType, data: Partial<Selectable<Data>>) => Promise<void> ? (id: PrimaryFieldType, data: Partial<Data>) => Promise<void>
: (data: Partial<Selectable<Data>>) => Promise<void>; : (data: Partial<Data>) => Promise<void>;
} }
export const useEntityMutate = < export const useEntityMutate = <
@@ -239,9 +238,8 @@ export const useEntityMutate = <
}); });
const _mutate = id const _mutate = id
? (data: Partial<Selectable<Data>>) => mutateEntityCache($q.api, entity, id, data) ? (data: Partial<Data>) => mutateEntityCache($q.api, entity, id, data)
: (id: PrimaryFieldType, data: Partial<Selectable<Data>>) => : (id: PrimaryFieldType, data: Partial<Data>) => mutateEntityCache($q.api, entity, id, data);
mutateEntityCache($q.api, entity, id, data);
return { return {
...$q, ...$q,
@@ -5,7 +5,7 @@ import { getChangeSet, getDefaultValues } from "data/helper";
type EntityFormProps = { type EntityFormProps = {
action: "create" | "update"; action: "create" | "update";
entity: Entity; entity: Entity;
initialData?: EntityData | null; initialData?: EntityData | object | null;
onSubmitted?: (changeSet?: EntityData) => Promise<void>; onSubmitted?: (changeSet?: EntityData) => Promise<void>;
}; };
@@ -20,7 +20,7 @@ export function useEntityForm({
const fields = entity.getFillableFields(action, true); const fields = entity.getFillableFields(action, true);
// filter defaultValues to only contain fillable fields // filter defaultValues to only contain fillable fields
const defaultValues = getDefaultValues(fields, data); const defaultValues = getDefaultValues(fields, data as any);
//console.log("useEntityForm", { data, defaultValues }); //console.log("useEntityForm", { data, defaultValues });
const Form = useForm({ const Form = useForm({
@@ -120,7 +120,7 @@ export function DataEntityCreate({ params }) {
entity={entity} entity={entity}
handleSubmit={handleSubmit} handleSubmit={handleSubmit}
fieldsDisabled={fieldsDisabled} fieldsDisabled={fieldsDisabled}
data={search.value} data={search.value as any}
Form={Form} Form={Form}
action="create" action="create"
className="flex flex-grow flex-col gap-3 p-3" className="flex flex-grow flex-col gap-3 p-3"