@databricks/appkit-ui 0.86.0 → 0.88.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/js/database/client.d.ts.map +1 -1
- package/dist/js/database/client.js +41 -9
- package/dist/js/database/client.js.map +1 -1
- package/dist/react/beta.d.ts +14 -1
- package/dist/react/beta.js +9 -1
- package/dist/react/hooks/analytics-request-store.js +1 -1
- package/dist/react/hooks/analytics-request-store.js.map +1 -1
- package/dist/react/hooks/database-request-store.d.ts +33 -0
- package/dist/react/hooks/database-request-store.d.ts.map +1 -0
- package/dist/react/hooks/database-request-store.js +145 -0
- package/dist/react/hooks/database-request-store.js.map +1 -0
- package/dist/react/hooks/request-store.js +26 -5
- package/dist/react/hooks/request-store.js.map +1 -1
- package/dist/react/hooks/use-database-create.d.ts +55 -0
- package/dist/react/hooks/use-database-create.d.ts.map +1 -0
- package/dist/react/hooks/use-database-create.js +45 -0
- package/dist/react/hooks/use-database-create.js.map +1 -0
- package/dist/react/hooks/use-database-delete.d.ts +50 -0
- package/dist/react/hooks/use-database-delete.d.ts.map +1 -0
- package/dist/react/hooks/use-database-delete.js +47 -0
- package/dist/react/hooks/use-database-delete.js.map +1 -0
- package/dist/react/hooks/use-database-list.d.ts +40 -0
- package/dist/react/hooks/use-database-list.d.ts.map +1 -0
- package/dist/react/hooks/use-database-list.js +29 -0
- package/dist/react/hooks/use-database-list.js.map +1 -0
- package/dist/react/hooks/use-database-read.d.ts +75 -0
- package/dist/react/hooks/use-database-read.d.ts.map +1 -0
- package/dist/react/hooks/use-database-read.js +136 -0
- package/dist/react/hooks/use-database-read.js.map +1 -0
- package/dist/react/hooks/use-database-record.d.ts +37 -0
- package/dist/react/hooks/use-database-record.d.ts.map +1 -0
- package/dist/react/hooks/use-database-record.js +53 -0
- package/dist/react/hooks/use-database-record.js.map +1 -0
- package/dist/react/hooks/use-database-update.d.ts +52 -0
- package/dist/react/hooks/use-database-update.d.ts.map +1 -0
- package/dist/react/hooks/use-database-update.js +42 -0
- package/dist/react/hooks/use-database-update.js.map +1 -0
- package/dist/react/hooks/use-database-write.d.ts +32 -0
- package/dist/react/hooks/use-database-write.d.ts.map +1 -0
- package/dist/react/hooks/use-database-write.js +94 -0
- package/dist/react/hooks/use-database-write.js.map +1 -0
- package/docs/development/type-generation.md +11 -0
- package/docs/plugins/database.md +233 -14
- package/package.json +1 -1
- package/sbom.cdx.json +1 -1
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { ExactDatabaseParams } from "../../shared/src/database/api-types.js";
|
|
2
|
+
import "../../shared/src/index.js";
|
|
3
|
+
import { DatabaseEntity, DatabaseInsert, DatabaseRow } from "../../js/database/types.js";
|
|
4
|
+
import { DatabaseApiError } from "../../js/database/errors.js";
|
|
5
|
+
import { UseDatabaseWriteOptions, UseDatabaseWriteState } from "./use-database-write.js";
|
|
6
|
+
|
|
7
|
+
//#region src/react/hooks/use-database-create.d.ts
|
|
8
|
+
/** Options for {@link useDatabaseCreate}. */
|
|
9
|
+
interface UseDatabaseCreateOptions<K extends DatabaseEntity> extends UseDatabaseWriteOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Called for every successful create, once the restarted reads reloaded,
|
|
12
|
+
* even if the component unmounted meanwhile.
|
|
13
|
+
*/
|
|
14
|
+
onSuccess?: (row: DatabaseRow<K>, values: DatabaseInsert<K>) => void;
|
|
15
|
+
/** Called for every failed create, with the error `error` also reports. */
|
|
16
|
+
onError?: (error: DatabaseApiError, values: DatabaseInsert<K>) => void;
|
|
17
|
+
}
|
|
18
|
+
/** What {@link useDatabaseCreate} returns. */
|
|
19
|
+
interface UseDatabaseCreateResult<K extends DatabaseEntity> extends UseDatabaseWriteState<DatabaseRow<K>> {
|
|
20
|
+
/**
|
|
21
|
+
* Send `POST /api/database/<entity>` and resolve with the created row, or
|
|
22
|
+
* with `null` when the write failed; the reason is in `error`. It never
|
|
23
|
+
* rejects, so a handler needs no `try/catch`.
|
|
24
|
+
*/
|
|
25
|
+
create<const V extends DatabaseInsert<K>>(values: V & ExactDatabaseParams<V, DatabaseInsert<K>>): Promise<DatabaseRow<K> | null>;
|
|
26
|
+
/** Return to the idle state; a call in flight no longer reports here. */
|
|
27
|
+
reset(): void;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Create rows through `POST /api/database/<entity>`. Values are typed from the
|
|
31
|
+
* generated `database.d.ts`, so private, generated, and undeclared fields are
|
|
32
|
+
* compile errors. Once a create succeeds, mounted database reads restart, so
|
|
33
|
+
* lists and includes that show the new row refresh without a manual refetch.
|
|
34
|
+
*
|
|
35
|
+
* @param entity - A table the generated registry exposes
|
|
36
|
+
* @param options - `invalidate` to narrow the read restart; `onSuccess` and
|
|
37
|
+
* `onError` to observe every call
|
|
38
|
+
* @returns `create`, the latest call's row, loading and error state, and `reset`
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```tsx
|
|
42
|
+
* const notes = useDatabaseCreate("notes", {
|
|
43
|
+
* onError: (error) => toast(error.message),
|
|
44
|
+
* });
|
|
45
|
+
*
|
|
46
|
+
* async function add(body: string) {
|
|
47
|
+
* const note = await notes.create({ board_id: boardId, author: "ada", body });
|
|
48
|
+
* if (note) setDraft("");
|
|
49
|
+
* }
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
declare function useDatabaseCreate<K extends DatabaseEntity>(entity: K, options?: UseDatabaseCreateOptions<K>): UseDatabaseCreateResult<K>;
|
|
53
|
+
//#endregion
|
|
54
|
+
export { UseDatabaseCreateOptions, UseDatabaseCreateResult, useDatabaseCreate };
|
|
55
|
+
//# sourceMappingURL=use-database-create.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-create.d.ts","names":[],"sources":["../../../src/react/hooks/use-database-create.ts"],"mappings":";;;;;;;;UAkBiB,wBAAA,WACL,cAAA,UACF,uBAAA;;AAFV;;;EAOE,SAAA,IAAa,GAAA,EAAK,WAAA,CAAY,CAAA,GAAI,MAAA,EAAQ,cAAA,CAAe,CAAA;EAA3B;EAE9B,OAAA,IAAW,KAAA,EAAO,gBAAA,EAAkB,MAAA,EAAQ,cAAA,CAAe,CAAA;AAAA;;UAI5C,uBAAA,WACL,cAAA,UACF,qBAAA,CAAsB,WAAA,CAAY,CAAA;EANiB;;;;;EAY3D,MAAA,iBAAuB,cAAA,CAAe,CAAA,GACpC,MAAA,EAAQ,CAAA,GAAI,mBAAA,CAAoB,CAAA,EAAG,cAAA,CAAe,CAAA,KACjD,OAAA,CAAQ,WAAA,CAAY,CAAA;EAtBb;EAwBV,KAAA;AAAA;;;;;;;;;;;;;;;AAZF;;;;;;;;;iBAsCgB,iBAAA,WAA4B,cAAA,CAAA,CAC1C,MAAA,EAAQ,CAAA,EACR,OAAA,GAAS,wBAAA,CAAyB,CAAA,IACjC,uBAAA,CAAwB,CAAA"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createDatabaseRow } from "../../js/database/client.js";
|
|
2
|
+
import { useDatabaseWrite } from "./use-database-write.js";
|
|
3
|
+
import { useCallback } from "react";
|
|
4
|
+
|
|
5
|
+
//#region src/react/hooks/use-database-create.ts
|
|
6
|
+
/**
|
|
7
|
+
* Create rows through `POST /api/database/<entity>`. Values are typed from the
|
|
8
|
+
* generated `database.d.ts`, so private, generated, and undeclared fields are
|
|
9
|
+
* compile errors. Once a create succeeds, mounted database reads restart, so
|
|
10
|
+
* lists and includes that show the new row refresh without a manual refetch.
|
|
11
|
+
*
|
|
12
|
+
* @param entity - A table the generated registry exposes
|
|
13
|
+
* @param options - `invalidate` to narrow the read restart; `onSuccess` and
|
|
14
|
+
* `onError` to observe every call
|
|
15
|
+
* @returns `create`, the latest call's row, loading and error state, and `reset`
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```tsx
|
|
19
|
+
* const notes = useDatabaseCreate("notes", {
|
|
20
|
+
* onError: (error) => toast(error.message),
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* async function add(body: string) {
|
|
24
|
+
* const note = await notes.create({ board_id: boardId, author: "ada", body });
|
|
25
|
+
* if (note) setDraft("");
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
function useDatabaseCreate(entity, options = {}) {
|
|
30
|
+
const send = useCallback((values) => createDatabaseRow(entity, values), [entity]);
|
|
31
|
+
const { onSuccess, onError } = options;
|
|
32
|
+
const { mutate, ...write } = useDatabaseWrite(send, {
|
|
33
|
+
invalidate: options.invalidate,
|
|
34
|
+
onSuccess: onSuccess && ((row, [values]) => onSuccess(row, values)),
|
|
35
|
+
onError: onError && ((error, [values]) => onError(error, values))
|
|
36
|
+
});
|
|
37
|
+
return {
|
|
38
|
+
...write,
|
|
39
|
+
create: mutate
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
//#endregion
|
|
44
|
+
export { useDatabaseCreate };
|
|
45
|
+
//# sourceMappingURL=use-database-create.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-create.js","names":[],"sources":["../../../src/react/hooks/use-database-create.ts"],"sourcesContent":["import { useCallback } from \"react\";\nimport type { ExactDatabaseParams } from \"shared\";\n\nimport { createDatabaseRow } from \"@/js/database/client\";\nimport type { DatabaseApiError } from \"@/js/database/errors\";\nimport type {\n DatabaseEntity,\n DatabaseInsert,\n DatabaseRow,\n} from \"@/js/database/types\";\n\nimport {\n type UseDatabaseWriteOptions,\n type UseDatabaseWriteState,\n useDatabaseWrite,\n} from \"./use-database-write\";\n\n/** Options for {@link useDatabaseCreate}. */\nexport interface UseDatabaseCreateOptions<\n K extends DatabaseEntity,\n> extends UseDatabaseWriteOptions {\n /**\n * Called for every successful create, once the restarted reads reloaded,\n * even if the component unmounted meanwhile.\n */\n onSuccess?: (row: DatabaseRow<K>, values: DatabaseInsert<K>) => void;\n /** Called for every failed create, with the error `error` also reports. */\n onError?: (error: DatabaseApiError, values: DatabaseInsert<K>) => void;\n}\n\n/** What {@link useDatabaseCreate} returns. */\nexport interface UseDatabaseCreateResult<\n K extends DatabaseEntity,\n> extends UseDatabaseWriteState<DatabaseRow<K>> {\n /**\n * Send `POST /api/database/<entity>` and resolve with the created row, or\n * with `null` when the write failed; the reason is in `error`. It never\n * rejects, so a handler needs no `try/catch`.\n */\n create<const V extends DatabaseInsert<K>>(\n values: V & ExactDatabaseParams<V, DatabaseInsert<K>>,\n ): Promise<DatabaseRow<K> | null>;\n /** Return to the idle state; a call in flight no longer reports here. */\n reset(): void;\n}\n\n/**\n * Create rows through `POST /api/database/<entity>`. Values are typed from the\n * generated `database.d.ts`, so private, generated, and undeclared fields are\n * compile errors. Once a create succeeds, mounted database reads restart, so\n * lists and includes that show the new row refresh without a manual refetch.\n *\n * @param entity - A table the generated registry exposes\n * @param options - `invalidate` to narrow the read restart; `onSuccess` and\n * `onError` to observe every call\n * @returns `create`, the latest call's row, loading and error state, and `reset`\n *\n * @example\n * ```tsx\n * const notes = useDatabaseCreate(\"notes\", {\n * onError: (error) => toast(error.message),\n * });\n *\n * async function add(body: string) {\n * const note = await notes.create({ board_id: boardId, author: \"ada\", body });\n * if (note) setDraft(\"\");\n * }\n * ```\n */\nexport function useDatabaseCreate<K extends DatabaseEntity>(\n entity: K,\n options: UseDatabaseCreateOptions<K> = {},\n): UseDatabaseCreateResult<K> {\n const send = useCallback(\n (values: DatabaseInsert<K>) => createDatabaseRow(entity, values as object),\n [entity],\n );\n const { onSuccess, onError } = options;\n const { mutate, ...write } = useDatabaseWrite(send, {\n invalidate: options.invalidate,\n // The server projected the row it holds; the types describe that wire.\n onSuccess:\n onSuccess &&\n ((row, [values]) => onSuccess(row as DatabaseRow<K>, values)),\n onError: onError && ((error, [values]) => onError(error, values)),\n });\n return { ...write, create: mutate } as UseDatabaseCreateResult<K>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,SAAgB,kBACd,QACA,UAAuC,EAAE,EACb;CAC5B,MAAM,OAAO,aACV,WAA8B,kBAAkB,QAAQ,OAAiB,EAC1E,CAAC,OAAO,CACT;CACD,MAAM,EAAE,WAAW,YAAY;CAC/B,MAAM,EAAE,QAAQ,GAAG,UAAU,iBAAiB,MAAM;EAClD,YAAY,QAAQ;EAEpB,WACE,eACE,KAAK,CAAC,YAAY,UAAU,KAAuB,OAAO;EAC9D,SAAS,aAAa,OAAO,CAAC,YAAY,QAAQ,OAAO,OAAO;EACjE,CAAC;AACF,QAAO;EAAE,GAAG;EAAO,QAAQ;EAAQ"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { DatabaseId, DatabaseKeyedEntity } from "../../js/database/types.js";
|
|
2
|
+
import { DatabaseApiError } from "../../js/database/errors.js";
|
|
3
|
+
import { UseDatabaseWriteOptions, UseDatabaseWriteState } from "./use-database-write.js";
|
|
4
|
+
|
|
5
|
+
//#region src/react/hooks/use-database-delete.d.ts
|
|
6
|
+
/** Options for {@link useDatabaseDelete}. */
|
|
7
|
+
interface UseDatabaseDeleteOptions<K extends DatabaseKeyedEntity> extends UseDatabaseWriteOptions {
|
|
8
|
+
/**
|
|
9
|
+
* Called for every successful delete, once the restarted reads reloaded,
|
|
10
|
+
* even if the component unmounted meanwhile.
|
|
11
|
+
*/
|
|
12
|
+
onSuccess?: (id: DatabaseId<K>) => void;
|
|
13
|
+
/** Called for every failed delete, with the error `error` also reports. */
|
|
14
|
+
onError?: (error: DatabaseApiError, id: DatabaseId<K>) => void;
|
|
15
|
+
}
|
|
16
|
+
/** What {@link useDatabaseDelete} returns. A delete answers no row. */
|
|
17
|
+
interface UseDatabaseDeleteResult<K extends DatabaseKeyedEntity> extends Omit<UseDatabaseWriteState<never>, "data"> {
|
|
18
|
+
/**
|
|
19
|
+
* Send `DELETE /api/database/<entity>/:id` and resolve `true` once the row
|
|
20
|
+
* is deleted, or `false` when the write failed; the reason is in `error`,
|
|
21
|
+
* and a missing row is `NOT_FOUND`. It never rejects.
|
|
22
|
+
*/
|
|
23
|
+
remove(id: DatabaseId<K>): Promise<boolean>;
|
|
24
|
+
/** Return to the idle state; a call in flight no longer reports here. */
|
|
25
|
+
reset(): void;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Delete rows through `DELETE /api/database/<entity>/:id`. Only entities with
|
|
29
|
+
* a public primary key have this route. Once a delete succeeds, mounted
|
|
30
|
+
* database reads restart, so lists that showed the row drop it and a record
|
|
31
|
+
* read of it reports `NOT_FOUND` with no `data`.
|
|
32
|
+
*
|
|
33
|
+
* @param entity - A table the generated registry exposes with a public key
|
|
34
|
+
* @param options - `invalidate` to narrow the read restart; `onSuccess` and
|
|
35
|
+
* `onError` to observe every call
|
|
36
|
+
* @returns `remove`, loading and error state, and `reset`
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```tsx
|
|
40
|
+
* const notes = useDatabaseDelete("notes");
|
|
41
|
+
*
|
|
42
|
+
* <button disabled={notes.loading} onClick={() => notes.remove(note.id)}>
|
|
43
|
+
* Delete
|
|
44
|
+
* </button>;
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
declare function useDatabaseDelete<K extends DatabaseKeyedEntity>(entity: K, options?: UseDatabaseDeleteOptions<K>): UseDatabaseDeleteResult<K>;
|
|
48
|
+
//#endregion
|
|
49
|
+
export { UseDatabaseDeleteOptions, UseDatabaseDeleteResult, useDatabaseDelete };
|
|
50
|
+
//# sourceMappingURL=use-database-delete.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-delete.d.ts","names":[],"sources":["../../../src/react/hooks/use-database-delete.ts"],"mappings":";;;;;;UAaiB,wBAAA,WACL,mBAAA,UACF,uBAAA;EAFO;;;;EAOf,SAAA,IAAa,EAAA,EAAI,UAAA,CAAW,CAAA;EAAX;EAEjB,OAAA,IAAW,KAAA,EAAO,gBAAA,EAAkB,EAAA,EAAI,UAAA,CAAW,CAAA;AAAA;;UAIpC,uBAAA,WACL,mBAAA,UACF,IAAA,CAAK,qBAAA;EAbkB;;;;;EAmB/B,MAAA,CAAO,EAAA,EAAI,UAAA,CAAW,CAAA,IAAK,OAAA;EAdV;EAgBjB,KAAA;AAAA;;;;;;;;;AAVF;;;;;;;;;;;;iBAiCgB,iBAAA,WAA4B,mBAAA,CAAA,CAC1C,MAAA,EAAQ,CAAA,EACR,OAAA,GAAS,wBAAA,CAAyB,CAAA,IACjC,uBAAA,CAAwB,CAAA"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { deleteDatabaseRow } from "../../js/database/client.js";
|
|
2
|
+
import { useDatabaseWrite } from "./use-database-write.js";
|
|
3
|
+
import { useCallback } from "react";
|
|
4
|
+
|
|
5
|
+
//#region src/react/hooks/use-database-delete.ts
|
|
6
|
+
/**
|
|
7
|
+
* Delete rows through `DELETE /api/database/<entity>/:id`. Only entities with
|
|
8
|
+
* a public primary key have this route. Once a delete succeeds, mounted
|
|
9
|
+
* database reads restart, so lists that showed the row drop it and a record
|
|
10
|
+
* read of it reports `NOT_FOUND` with no `data`.
|
|
11
|
+
*
|
|
12
|
+
* @param entity - A table the generated registry exposes with a public key
|
|
13
|
+
* @param options - `invalidate` to narrow the read restart; `onSuccess` and
|
|
14
|
+
* `onError` to observe every call
|
|
15
|
+
* @returns `remove`, loading and error state, and `reset`
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```tsx
|
|
19
|
+
* const notes = useDatabaseDelete("notes");
|
|
20
|
+
*
|
|
21
|
+
* <button disabled={notes.loading} onClick={() => notes.remove(note.id)}>
|
|
22
|
+
* Delete
|
|
23
|
+
* </button>;
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
function useDatabaseDelete(entity, options = {}) {
|
|
27
|
+
const send = useCallback(async (id) => {
|
|
28
|
+
await deleteDatabaseRow(entity, id);
|
|
29
|
+
return true;
|
|
30
|
+
}, [entity]);
|
|
31
|
+
const { onSuccess, onError } = options;
|
|
32
|
+
const { mutate, reset, loading, error } = useDatabaseWrite(send, {
|
|
33
|
+
invalidate: options.invalidate,
|
|
34
|
+
onSuccess: onSuccess && ((_deleted, [id]) => onSuccess(id)),
|
|
35
|
+
onError: onError && ((failure, [id]) => onError(failure, id))
|
|
36
|
+
});
|
|
37
|
+
return {
|
|
38
|
+
remove: useCallback(async (id) => await mutate(id) === true, [mutate]),
|
|
39
|
+
reset,
|
|
40
|
+
loading,
|
|
41
|
+
error
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
//#endregion
|
|
46
|
+
export { useDatabaseDelete };
|
|
47
|
+
//# sourceMappingURL=use-database-delete.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-delete.js","names":[],"sources":["../../../src/react/hooks/use-database-delete.ts"],"sourcesContent":["import { useCallback } from \"react\";\n\nimport { deleteDatabaseRow } from \"@/js/database/client\";\nimport type { DatabaseApiError } from \"@/js/database/errors\";\nimport type { DatabaseId, DatabaseKeyedEntity } from \"@/js/database/types\";\n\nimport {\n type UseDatabaseWriteOptions,\n type UseDatabaseWriteState,\n useDatabaseWrite,\n} from \"./use-database-write\";\n\n/** Options for {@link useDatabaseDelete}. */\nexport interface UseDatabaseDeleteOptions<\n K extends DatabaseKeyedEntity,\n> extends UseDatabaseWriteOptions {\n /**\n * Called for every successful delete, once the restarted reads reloaded,\n * even if the component unmounted meanwhile.\n */\n onSuccess?: (id: DatabaseId<K>) => void;\n /** Called for every failed delete, with the error `error` also reports. */\n onError?: (error: DatabaseApiError, id: DatabaseId<K>) => void;\n}\n\n/** What {@link useDatabaseDelete} returns. A delete answers no row. */\nexport interface UseDatabaseDeleteResult<\n K extends DatabaseKeyedEntity,\n> extends Omit<UseDatabaseWriteState<never>, \"data\"> {\n /**\n * Send `DELETE /api/database/<entity>/:id` and resolve `true` once the row\n * is deleted, or `false` when the write failed; the reason is in `error`,\n * and a missing row is `NOT_FOUND`. It never rejects.\n */\n remove(id: DatabaseId<K>): Promise<boolean>;\n /** Return to the idle state; a call in flight no longer reports here. */\n reset(): void;\n}\n\n/**\n * Delete rows through `DELETE /api/database/<entity>/:id`. Only entities with\n * a public primary key have this route. Once a delete succeeds, mounted\n * database reads restart, so lists that showed the row drop it and a record\n * read of it reports `NOT_FOUND` with no `data`.\n *\n * @param entity - A table the generated registry exposes with a public key\n * @param options - `invalidate` to narrow the read restart; `onSuccess` and\n * `onError` to observe every call\n * @returns `remove`, loading and error state, and `reset`\n *\n * @example\n * ```tsx\n * const notes = useDatabaseDelete(\"notes\");\n *\n * <button disabled={notes.loading} onClick={() => notes.remove(note.id)}>\n * Delete\n * </button>;\n * ```\n */\nexport function useDatabaseDelete<K extends DatabaseKeyedEntity>(\n entity: K,\n options: UseDatabaseDeleteOptions<K> = {},\n): UseDatabaseDeleteResult<K> {\n // A delete answers no row, so success is the only result worth reporting.\n const send = useCallback(\n async (id: DatabaseId<K>) => {\n await deleteDatabaseRow(entity, id);\n return true as const;\n },\n [entity],\n );\n const { onSuccess, onError } = options;\n const { mutate, reset, loading, error } = useDatabaseWrite(send, {\n invalidate: options.invalidate,\n onSuccess: onSuccess && ((_deleted, [id]) => onSuccess(id)),\n onError: onError && ((failure, [id]) => onError(failure, id)),\n });\n const remove = useCallback(\n async (id: DatabaseId<K>) => (await mutate(id)) === true,\n [mutate],\n );\n return { remove, reset, loading, error };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,kBACd,QACA,UAAuC,EAAE,EACb;CAE5B,MAAM,OAAO,YACX,OAAO,OAAsB;AAC3B,QAAM,kBAAkB,QAAQ,GAAG;AACnC,SAAO;IAET,CAAC,OAAO,CACT;CACD,MAAM,EAAE,WAAW,YAAY;CAC/B,MAAM,EAAE,QAAQ,OAAO,SAAS,UAAU,iBAAiB,MAAM;EAC/D,YAAY,QAAQ;EACpB,WAAW,eAAe,UAAU,CAAC,QAAQ,UAAU,GAAG;EAC1D,SAAS,aAAa,SAAS,CAAC,QAAQ,QAAQ,SAAS,GAAG;EAC7D,CAAC;AAKF,QAAO;EAAE,QAJM,YACb,OAAO,OAAuB,MAAM,OAAO,GAAG,KAAM,MACpD,CAAC,OAAO,CACT;EACgB;EAAO;EAAS;EAAO"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { DatabaseListPage, ExactDatabaseParams } from "../../shared/src/database/api-types.js";
|
|
2
|
+
import "../../shared/src/index.js";
|
|
3
|
+
import { DatabaseEntity, DatabaseKeyedEntity, DatabaseListParams, DatabaseListRow } from "../../js/database/types.js";
|
|
4
|
+
import { UseDatabaseReadOptions, UseDatabaseReadResult } from "./use-database-read.js";
|
|
5
|
+
|
|
6
|
+
//#region src/react/hooks/use-database-list.d.ts
|
|
7
|
+
/** Options for {@link useDatabaseList}. */
|
|
8
|
+
type UseDatabaseListOptions<Row> = UseDatabaseReadOptions<Row>;
|
|
9
|
+
/** What {@link useDatabaseList} returns: one page of rows and its state. */
|
|
10
|
+
type UseDatabaseListResult<Row> = UseDatabaseReadResult<DatabaseListPage<Row>>;
|
|
11
|
+
/**
|
|
12
|
+
* Subscribe to one page of `GET /api/database/<entity>`. Entity, params, and
|
|
13
|
+
* rows are typed from the generated `database.d.ts`; the route comes from the
|
|
14
|
+
* endpoints the server published.
|
|
15
|
+
*
|
|
16
|
+
* Mounted hooks whose params encode to the same query share one request, so
|
|
17
|
+
* an inline params literal does not refetch on every render. The request is
|
|
18
|
+
* aborted once its last subscriber unmounts.
|
|
19
|
+
*
|
|
20
|
+
* @param entity - A table the generated registry exposes
|
|
21
|
+
* @param params - `where`, `order`, `select`, `include`, `limit`, `offset`;
|
|
22
|
+
* `null` holds the hook idle, for params that depend on another read
|
|
23
|
+
* @param options - `enabled`, `keepPreviousData`, and `shape`
|
|
24
|
+
* @returns The page, loading and error state, and `refetch`
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```tsx
|
|
28
|
+
* const notes = useDatabaseList(
|
|
29
|
+
* "notes",
|
|
30
|
+
* board ? { where: { board_id: board.id }, limit: 20, offset } : null,
|
|
31
|
+
* { keepPreviousData: true },
|
|
32
|
+
* );
|
|
33
|
+
* notes.data?.items.map((note) => note.body);
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
declare function useDatabaseList<K extends DatabaseKeyedEntity, Row = DatabaseListRow<K>>(entity: K, params?: undefined, options?: UseDatabaseListOptions<Row>): UseDatabaseListResult<Row>;
|
|
37
|
+
declare function useDatabaseList<K extends DatabaseEntity, const P extends DatabaseListParams<K>, Row = DatabaseListRow<K, P>>(entity: K, params: (P & ExactDatabaseParams<P, DatabaseListParams<K>>) | null, options?: UseDatabaseListOptions<Row>): UseDatabaseListResult<Row>;
|
|
38
|
+
//#endregion
|
|
39
|
+
export { UseDatabaseListOptions, UseDatabaseListResult, useDatabaseList };
|
|
40
|
+
//# sourceMappingURL=use-database-list.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-list.d.ts","names":[],"sources":["../../../src/react/hooks/use-database-list.ts"],"mappings":";;;;;;;KAwBY,sBAAA,QAA8B,sBAAA,CAAuB,GAAA;;KAGrD,qBAAA,QAA6B,qBAAA,CACvC,gBAAA,CAAiB,GAAA;;;;;;;;;AADnB;;;;;;;;;;;;;;AA6BA;;;iBAAgB,eAAA,WACJ,mBAAA,QACJ,eAAA,CAAgB,CAAA,EAAA,CAEtB,MAAA,EAAQ,CAAA,EACR,MAAA,cACA,OAAA,GAAU,sBAAA,CAAuB,GAAA,IAChC,qBAAA,CAAsB,GAAA;AAAA,iBACT,eAAA,WACJ,cAAA,kBACM,kBAAA,CAAmB,CAAA,SAC7B,eAAA,CAAgB,CAAA,EAAG,CAAA,EAAA,CAEzB,MAAA,EAAQ,CAAA,EACR,MAAA,GAAS,CAAA,GAAI,mBAAA,CAAoB,CAAA,EAAG,kBAAA,CAAmB,CAAA,YACvD,OAAA,GAAU,sBAAA,CAAuB,GAAA,IAChC,qBAAA,CAAsB,GAAA"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { DatabaseQueryEncodingError, encodeDatabaseListQuery } from "../../shared/src/database/query-codec.js";
|
|
2
|
+
import { isDatabaseListPage } from "../../js/database/client.js";
|
|
3
|
+
import { useDatabaseRead } from "./use-database-read.js";
|
|
4
|
+
|
|
5
|
+
//#region src/react/hooks/use-database-list.ts
|
|
6
|
+
function useDatabaseList(entity, params, options = {}) {
|
|
7
|
+
const enabled = (options.enabled ?? true) && params !== null;
|
|
8
|
+
let query = "";
|
|
9
|
+
if (enabled) try {
|
|
10
|
+
query = encodeDatabaseListQuery(params ?? {});
|
|
11
|
+
} catch (error) {
|
|
12
|
+
query = error instanceof DatabaseQueryEncodingError ? error : null;
|
|
13
|
+
}
|
|
14
|
+
return useDatabaseRead({
|
|
15
|
+
entity,
|
|
16
|
+
operation: "list",
|
|
17
|
+
id: void 0,
|
|
18
|
+
query,
|
|
19
|
+
include: params?.include,
|
|
20
|
+
enabled,
|
|
21
|
+
accept: isDatabaseListPage,
|
|
22
|
+
keepPreviousData: options.keepPreviousData ?? false,
|
|
23
|
+
shape: options.shape
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
export { useDatabaseList };
|
|
29
|
+
//# sourceMappingURL=use-database-list.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-list.js","names":[],"sources":["../../../src/react/hooks/use-database-list.ts"],"sourcesContent":["import {\n type DatabaseListPage,\n type DatabaseListQuery,\n DatabaseQueryEncodingError,\n encodeDatabaseListQuery,\n type ExactDatabaseParams,\n} from \"shared\";\n\nimport { isDatabaseListPage } from \"@/js/database/client\";\nimport type {\n DatabaseEntity,\n DatabaseKeyedEntity,\n DatabaseListParams,\n DatabaseListRow,\n} from \"@/js/database/types\";\n\nimport {\n type DatabaseReadRequest,\n type UseDatabaseReadOptions,\n type UseDatabaseReadResult,\n useDatabaseRead,\n} from \"./use-database-read\";\n\n/** Options for {@link useDatabaseList}. */\nexport type UseDatabaseListOptions<Row> = UseDatabaseReadOptions<Row>;\n\n/** What {@link useDatabaseList} returns: one page of rows and its state. */\nexport type UseDatabaseListResult<Row> = UseDatabaseReadResult<\n DatabaseListPage<Row>\n>;\n\n/**\n * Subscribe to one page of `GET /api/database/<entity>`. Entity, params, and\n * rows are typed from the generated `database.d.ts`; the route comes from the\n * endpoints the server published.\n *\n * Mounted hooks whose params encode to the same query share one request, so\n * an inline params literal does not refetch on every render. The request is\n * aborted once its last subscriber unmounts.\n *\n * @param entity - A table the generated registry exposes\n * @param params - `where`, `order`, `select`, `include`, `limit`, `offset`;\n * `null` holds the hook idle, for params that depend on another read\n * @param options - `enabled`, `keepPreviousData`, and `shape`\n * @returns The page, loading and error state, and `refetch`\n *\n * @example\n * ```tsx\n * const notes = useDatabaseList(\n * \"notes\",\n * board ? { where: { board_id: board.id }, limit: 20, offset } : null,\n * { keepPreviousData: true },\n * );\n * notes.data?.items.map((note) => note.body);\n * ```\n */\nexport function useDatabaseList<\n K extends DatabaseKeyedEntity,\n Row = DatabaseListRow<K>,\n>(\n entity: K,\n params?: undefined,\n options?: UseDatabaseListOptions<Row>,\n): UseDatabaseListResult<Row>;\nexport function useDatabaseList<\n K extends DatabaseEntity,\n const P extends DatabaseListParams<K>,\n Row = DatabaseListRow<K, P>,\n>(\n entity: K,\n params: (P & ExactDatabaseParams<P, DatabaseListParams<K>>) | null,\n options?: UseDatabaseListOptions<Row>,\n): UseDatabaseListResult<Row>;\nexport function useDatabaseList(\n entity: string,\n params?: DatabaseListQuery | null,\n options: UseDatabaseListOptions<unknown> = {},\n): UseDatabaseListResult<unknown> {\n const enabled = (options.enabled ?? true) && params !== null;\n // Encode only an enabled read: a held read's params may still be incomplete.\n let query: DatabaseReadRequest[\"query\"] = \"\";\n if (enabled) {\n try {\n query = encodeDatabaseListQuery(params ?? {});\n } catch (error) {\n query = error instanceof DatabaseQueryEncodingError ? error : null;\n }\n }\n const read = useDatabaseRead({\n entity,\n operation: \"list\",\n id: undefined,\n query,\n include: params?.include,\n enabled,\n accept: isDatabaseListPage,\n keepPreviousData: options.keepPreviousData ?? false,\n shape: options.shape,\n });\n return read as UseDatabaseListResult<unknown>;\n}\n"],"mappings":";;;;;AAyEA,SAAgB,gBACd,QACA,QACA,UAA2C,EAAE,EACb;CAChC,MAAM,WAAW,QAAQ,WAAW,SAAS,WAAW;CAExD,IAAI,QAAsC;AAC1C,KAAI,QACF,KAAI;AACF,UAAQ,wBAAwB,UAAU,EAAE,CAAC;UACtC,OAAO;AACd,UAAQ,iBAAiB,6BAA6B,QAAQ;;AAclE,QAXa,gBAAgB;EAC3B;EACA,WAAW;EACX,IAAI;EACJ;EACA,SAAS,QAAQ;EACjB;EACA,QAAQ;EACR,kBAAkB,QAAQ,oBAAoB;EAC9C,OAAO,QAAQ;EAChB,CAAC"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import "../../shared/src/index.js";
|
|
2
|
+
import "../../js/database/client.js";
|
|
3
|
+
import { DatabaseApiError } from "../../js/database/errors.js";
|
|
4
|
+
|
|
5
|
+
//#region src/react/hooks/use-database-read.d.ts
|
|
6
|
+
declare const DATABASE_SHAPE: unique symbol;
|
|
7
|
+
/**
|
|
8
|
+
* Phantom marker for the row a read serializer returns. It only carries a
|
|
9
|
+
* type; build one with {@link serialized}.
|
|
10
|
+
*/
|
|
11
|
+
interface DatabaseShape<T> {
|
|
12
|
+
readonly [DATABASE_SHAPE]: T;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Declare, without checking, the row a read serializer returns. The entity,
|
|
16
|
+
* id, and params stay checked against the generated registry; only the row
|
|
17
|
+
* type is replaced. It is a promise about the server's serializer, not a
|
|
18
|
+
* runtime check: to check each row, pass a parse function as `shape` instead.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```typescript
|
|
22
|
+
* interface NoteCard { id: number; excerpt: string }
|
|
23
|
+
*
|
|
24
|
+
* const notes = useDatabaseList("notes", { limit: 20 }, {
|
|
25
|
+
* shape: serialized<NoteCard>(),
|
|
26
|
+
* });
|
|
27
|
+
* notes.data?.items[0]?.excerpt;
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
declare function serialized<T>(): DatabaseShape<T>;
|
|
31
|
+
/**
|
|
32
|
+
* The row a read answers with: `serialized<T>()` to declare it, or a function
|
|
33
|
+
* that checks one decoded row and returns it typed, such as a zod schema's
|
|
34
|
+
* `parse`. A function that throws fails the read with `INTERNAL`.
|
|
35
|
+
*/
|
|
36
|
+
type DatabaseRowShape<Row> = DatabaseShape<Row> | ((row: unknown) => Row);
|
|
37
|
+
/** Options shared by `useDatabaseList` and `useDatabaseRecord`. */
|
|
38
|
+
interface UseDatabaseReadOptions<Row> {
|
|
39
|
+
/** Send the request. `false` keeps the hook idle and sends nothing. Default true. */
|
|
40
|
+
enabled?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* While new params load, keep showing the previous params' `data` instead
|
|
43
|
+
* of `null`, so a paginated list does not blank between pages. `loading`
|
|
44
|
+
* stays true until the new response arrives. Default false.
|
|
45
|
+
*/
|
|
46
|
+
keepPreviousData?: boolean;
|
|
47
|
+
/**
|
|
48
|
+
* The row a read serializer returns. `serialized<T>()` only declares it; a
|
|
49
|
+
* function checks every row at runtime (each list item, or the record) and
|
|
50
|
+
* its return value becomes the row. It runs once per response.
|
|
51
|
+
*/
|
|
52
|
+
shape?: DatabaseRowShape<Row>;
|
|
53
|
+
}
|
|
54
|
+
/** Latest state of one database read. */
|
|
55
|
+
interface UseDatabaseReadResult<T> {
|
|
56
|
+
/**
|
|
57
|
+
* The last successful response, or `null` before one arrives. A refetch
|
|
58
|
+
* keeps it visible while it loads and after it fails, except a `NOT_FOUND`,
|
|
59
|
+
* which clears it.
|
|
60
|
+
*/
|
|
61
|
+
data: T | null;
|
|
62
|
+
/** Whether a request for the current params is in flight. */
|
|
63
|
+
loading: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Why the latest request failed: `NOT_EXPOSED` when no route exists,
|
|
66
|
+
* `INVALID_REQUEST` for params or an id that cannot be sent, `INTERNAL`
|
|
67
|
+
* when a `shape` function rejected a row. Stable across renders.
|
|
68
|
+
*/
|
|
69
|
+
error: DatabaseApiError | null;
|
|
70
|
+
/** Abort any in-flight request and send it again. No-op while disabled. */
|
|
71
|
+
refetch: () => void;
|
|
72
|
+
}
|
|
73
|
+
//#endregion
|
|
74
|
+
export { DatabaseRowShape, DatabaseShape, UseDatabaseReadOptions, UseDatabaseReadResult, serialized };
|
|
75
|
+
//# sourceMappingURL=use-database-read.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-read.d.ts","names":[],"sources":["../../../src/react/hooks/use-database-read.ts"],"mappings":";;;;;cAyBc,cAAA;;AAXgE;;;UAiB7D,aAAA;EAAA,UACL,cAAA,GAAiB,CAAA;AAAA;;;;;;;;;AAqB7B;;;;;;;;iBAAgB,UAAA,GAAA,CAAA,GAAiB,aAAA,CAAc,CAAA;AAS/C;;;;;AAAA,KAAY,gBAAA,QACR,aAAA,CAAc,GAAA,MACZ,GAAA,cAAiB,GAAA;;UAGN,sBAAA;EALY;EAO3B,OAAA;EANgB;;;;;EAYhB,gBAAA;EARqC;;;;;EAcrC,KAAA,GAAQ,gBAAA,CAAiB,GAAA;AAAA;;UAIV,qBAAA;EAJa;;AAI9B;;;EAME,IAAA,EAAM,CAAA;EAN+B;EAQrC,OAAA;EAFM;;;;;EAQN,KAAA,EAAO,gBAAA;EAEA;EAAP,OAAA;AAAA"}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { DatabaseQueryEncodingError } from "../../shared/src/database/query-codec.js";
|
|
2
|
+
import { DatabaseApiError, invalidDatabaseQuery } from "../../js/database/errors.js";
|
|
3
|
+
import { resolveDatabaseUrl } from "../../js/database/client.js";
|
|
4
|
+
import { IDLE_DATABASE_READ, databaseReadScope, getDatabaseReadSnapshot, retainDatabaseRead, startDatabaseRead, subscribeDatabaseRead } from "./database-request-store.js";
|
|
5
|
+
import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
|
|
6
|
+
|
|
7
|
+
//#region src/react/hooks/use-database-read.ts
|
|
8
|
+
const SERIALIZED = Object.freeze({});
|
|
9
|
+
/**
|
|
10
|
+
* Declare, without checking, the row a read serializer returns. The entity,
|
|
11
|
+
* id, and params stay checked against the generated registry; only the row
|
|
12
|
+
* type is replaced. It is a promise about the server's serializer, not a
|
|
13
|
+
* runtime check: to check each row, pass a parse function as `shape` instead.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* interface NoteCard { id: number; excerpt: string }
|
|
18
|
+
*
|
|
19
|
+
* const notes = useDatabaseList("notes", { limit: 20 }, {
|
|
20
|
+
* shape: serialized<NoteCard>(),
|
|
21
|
+
* });
|
|
22
|
+
* notes.data?.items[0]?.excerpt;
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
function serialized() {
|
|
26
|
+
return SERIALIZED;
|
|
27
|
+
}
|
|
28
|
+
const noop = () => {};
|
|
29
|
+
/** Apply a `shape` function to each row of one response. */
|
|
30
|
+
function shapeResponse(operation, data, parse) {
|
|
31
|
+
if (operation === "detail") return parse(data);
|
|
32
|
+
const page = data;
|
|
33
|
+
return {
|
|
34
|
+
...page,
|
|
35
|
+
items: page.items.map((row) => parse(row))
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Run a `shape` function once per response. The result is cached on the
|
|
40
|
+
* response's identity, not the function's, so an inline arrow does not
|
|
41
|
+
* reparse on every render or give `data` a new identity.
|
|
42
|
+
*/
|
|
43
|
+
function useShapedData(operation, source, shape) {
|
|
44
|
+
const cache = useRef(null);
|
|
45
|
+
if (typeof shape !== "function" || source === null) return {
|
|
46
|
+
source,
|
|
47
|
+
data: source,
|
|
48
|
+
error: null
|
|
49
|
+
};
|
|
50
|
+
const cached = cache.current;
|
|
51
|
+
if (cached !== null && cached.source === source) return cached;
|
|
52
|
+
let shaped;
|
|
53
|
+
try {
|
|
54
|
+
shaped = {
|
|
55
|
+
source,
|
|
56
|
+
data: shapeResponse(operation, source, shape),
|
|
57
|
+
error: null
|
|
58
|
+
};
|
|
59
|
+
} catch (cause) {
|
|
60
|
+
shaped = {
|
|
61
|
+
source,
|
|
62
|
+
data: null,
|
|
63
|
+
error: new DatabaseApiError("INTERNAL", null, "Database response does not match the read's shape", [], { cause })
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
cache.current = shaped;
|
|
67
|
+
return shaped;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* One subscribed read, keyed by the resolved URL so params with equal encoded
|
|
71
|
+
* values share a request whatever their object identity. A route the server
|
|
72
|
+
* did not publish resolves to a stable `NOT_EXPOSED` error without a request,
|
|
73
|
+
* and params that cannot be encoded to a stable `INVALID_REQUEST`.
|
|
74
|
+
*/
|
|
75
|
+
function useDatabaseRead({ entity, operation, id, query, include, enabled, accept, keepPreviousData, shape }) {
|
|
76
|
+
const encodedQuery = typeof query === "string" ? query : null;
|
|
77
|
+
const parameter = query instanceof DatabaseQueryEncodingError ? query.parameter : void 0;
|
|
78
|
+
const message = query instanceof DatabaseQueryEncodingError ? query.message : void 0;
|
|
79
|
+
const route = useMemo(() => {
|
|
80
|
+
if (!enabled) return null;
|
|
81
|
+
if (encodedQuery === null) return { error: invalidDatabaseQuery(parameter !== void 0 && message !== void 0 ? new DatabaseQueryEncodingError(parameter, message) : void 0) };
|
|
82
|
+
try {
|
|
83
|
+
return { url: resolveDatabaseUrl(entity, operation, id, encodedQuery) };
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (error instanceof DatabaseApiError) return { error };
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
}, [
|
|
89
|
+
enabled,
|
|
90
|
+
entity,
|
|
91
|
+
operation,
|
|
92
|
+
id,
|
|
93
|
+
encodedQuery,
|
|
94
|
+
parameter,
|
|
95
|
+
message
|
|
96
|
+
]);
|
|
97
|
+
const url = route !== null && "url" in route ? route.url : null;
|
|
98
|
+
const routeError = route !== null && "error" in route ? route.error : null;
|
|
99
|
+
const scope = useMemo(() => url === null ? null : databaseReadScope(entity, include), [url]);
|
|
100
|
+
const subscribe = useCallback((listener) => url === null ? noop : subscribeDatabaseRead(url, listener), [url]);
|
|
101
|
+
const getSnapshot = useCallback(() => url === null ? IDLE_DATABASE_READ : getDatabaseReadSnapshot(url), [url]);
|
|
102
|
+
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
103
|
+
useEffect(() => {
|
|
104
|
+
if (url === null || scope === null) return;
|
|
105
|
+
return retainDatabaseRead(url, accept, scope);
|
|
106
|
+
}, [
|
|
107
|
+
url,
|
|
108
|
+
accept,
|
|
109
|
+
scope
|
|
110
|
+
]);
|
|
111
|
+
const refetch = useCallback(() => {
|
|
112
|
+
if (url !== null) startDatabaseRead(url);
|
|
113
|
+
}, [url]);
|
|
114
|
+
const shaped = useShapedData(operation, snapshot.data, shape);
|
|
115
|
+
const loading = snapshot.loading || url !== null && snapshot === IDLE_DATABASE_READ;
|
|
116
|
+
const error = routeError ?? snapshot.error ?? shaped.error;
|
|
117
|
+
const previous = useRef(null);
|
|
118
|
+
useEffect(() => {
|
|
119
|
+
if (url !== null && shaped.data !== null) previous.current = {
|
|
120
|
+
url,
|
|
121
|
+
data: shaped.data
|
|
122
|
+
};
|
|
123
|
+
}, [url, shaped.data]);
|
|
124
|
+
let data = shaped.data;
|
|
125
|
+
if (keepPreviousData && data === null && loading && error === null && previous.current !== null && previous.current.url !== url) data = previous.current.data;
|
|
126
|
+
return {
|
|
127
|
+
data,
|
|
128
|
+
loading,
|
|
129
|
+
error,
|
|
130
|
+
refetch
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
//#endregion
|
|
135
|
+
export { serialized, useDatabaseRead };
|
|
136
|
+
//# sourceMappingURL=use-database-read.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-read.js","names":[],"sources":["../../../src/react/hooks/use-database-read.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\nimport { DatabaseQueryEncodingError } from \"shared\";\n\nimport {\n type DatabaseOperation,\n type IdLike,\n resolveDatabaseUrl,\n} from \"@/js/database/client\";\nimport { DatabaseApiError, invalidDatabaseQuery } from \"@/js/database/errors\";\n\nimport {\n databaseReadScope,\n getDatabaseReadSnapshot,\n IDLE_DATABASE_READ,\n retainDatabaseRead,\n startDatabaseRead,\n subscribeDatabaseRead,\n} from \"./database-request-store\";\n\ndeclare const DATABASE_SHAPE: unique symbol;\n\n/**\n * Phantom marker for the row a read serializer returns. It only carries a\n * type; build one with {@link serialized}.\n */\nexport interface DatabaseShape<T> {\n readonly [DATABASE_SHAPE]: T;\n}\n\nconst SERIALIZED = Object.freeze({});\n\n/**\n * Declare, without checking, the row a read serializer returns. The entity,\n * id, and params stay checked against the generated registry; only the row\n * type is replaced. It is a promise about the server's serializer, not a\n * runtime check: to check each row, pass a parse function as `shape` instead.\n *\n * @example\n * ```typescript\n * interface NoteCard { id: number; excerpt: string }\n *\n * const notes = useDatabaseList(\"notes\", { limit: 20 }, {\n * shape: serialized<NoteCard>(),\n * });\n * notes.data?.items[0]?.excerpt;\n * ```\n */\nexport function serialized<T>(): DatabaseShape<T> {\n return SERIALIZED as DatabaseShape<T>;\n}\n\n/**\n * The row a read answers with: `serialized<T>()` to declare it, or a function\n * that checks one decoded row and returns it typed, such as a zod schema's\n * `parse`. A function that throws fails the read with `INTERNAL`.\n */\nexport type DatabaseRowShape<Row> =\n | DatabaseShape<Row>\n | ((row: unknown) => Row);\n\n/** Options shared by `useDatabaseList` and `useDatabaseRecord`. */\nexport interface UseDatabaseReadOptions<Row> {\n /** Send the request. `false` keeps the hook idle and sends nothing. Default true. */\n enabled?: boolean;\n /**\n * While new params load, keep showing the previous params' `data` instead\n * of `null`, so a paginated list does not blank between pages. `loading`\n * stays true until the new response arrives. Default false.\n */\n keepPreviousData?: boolean;\n /**\n * The row a read serializer returns. `serialized<T>()` only declares it; a\n * function checks every row at runtime (each list item, or the record) and\n * its return value becomes the row. It runs once per response.\n */\n shape?: DatabaseRowShape<Row>;\n}\n\n/** Latest state of one database read. */\nexport interface UseDatabaseReadResult<T> {\n /**\n * The last successful response, or `null` before one arrives. A refetch\n * keeps it visible while it loads and after it fails, except a `NOT_FOUND`,\n * which clears it.\n */\n data: T | null;\n /** Whether a request for the current params is in flight. */\n loading: boolean;\n /**\n * Why the latest request failed: `NOT_EXPOSED` when no route exists,\n * `INVALID_REQUEST` for params or an id that cannot be sent, `INTERNAL`\n * when a `shape` function rejected a row. Stable across renders.\n */\n error: DatabaseApiError | null;\n /** Abort any in-flight request and send it again. No-op while disabled. */\n refetch: () => void;\n}\n\n/** What one read hook asks `useDatabaseRead` to subscribe to. */\nexport interface DatabaseReadRequest {\n entity: string;\n operation: Extract<DatabaseOperation, \"list\" | \"detail\">;\n id: IdLike | undefined;\n /** Encoded params, a known validation failure, or `null` for an unknown failure. */\n query: string | DatabaseQueryEncodingError | null;\n /** The params' include tree, to find the tables the read shows. */\n include: unknown;\n enabled: boolean;\n accept: (body: unknown) => body is object;\n keepPreviousData: boolean;\n shape: DatabaseRowShape<unknown> | undefined;\n}\n\ntype Route = { url: string } | { error: DatabaseApiError } | null;\n\nconst noop = () => {};\n\n/** Apply a `shape` function to each row of one response. */\nfunction shapeResponse(\n operation: DatabaseReadRequest[\"operation\"],\n data: unknown,\n parse: (row: unknown) => unknown,\n): unknown {\n if (operation === \"detail\") return parse(data);\n const page = data as { items: unknown[] };\n return { ...page, items: page.items.map((row) => parse(row)) };\n}\n\n/** The shaped response, or why a row failed its `shape`. */\ninterface Shaped {\n source: unknown;\n data: unknown;\n error: DatabaseApiError | null;\n}\n\n/**\n * Run a `shape` function once per response. The result is cached on the\n * response's identity, not the function's, so an inline arrow does not\n * reparse on every render or give `data` a new identity.\n */\nfunction useShapedData(\n operation: DatabaseReadRequest[\"operation\"],\n source: unknown,\n shape: DatabaseRowShape<unknown> | undefined,\n): Shaped {\n const cache = useRef<Shaped | null>(null);\n if (typeof shape !== \"function\" || source === null) {\n return { source, data: source, error: null };\n }\n const cached = cache.current;\n if (cached !== null && cached.source === source) return cached;\n let shaped: Shaped;\n try {\n shaped = {\n source,\n data: shapeResponse(operation, source, shape),\n error: null,\n };\n } catch (cause) {\n // A schema error may quote row values; keep it in `cause` only.\n shaped = {\n source,\n data: null,\n error: new DatabaseApiError(\n \"INTERNAL\",\n null,\n \"Database response does not match the read's shape\",\n [],\n { cause },\n ),\n };\n }\n cache.current = shaped;\n return shaped;\n}\n\n/**\n * One subscribed read, keyed by the resolved URL so params with equal encoded\n * values share a request whatever their object identity. A route the server\n * did not publish resolves to a stable `NOT_EXPOSED` error without a request,\n * and params that cannot be encoded to a stable `INVALID_REQUEST`.\n */\nexport function useDatabaseRead({\n entity,\n operation,\n id,\n query,\n include,\n enabled,\n accept,\n keepPreviousData,\n shape,\n}: DatabaseReadRequest): UseDatabaseReadResult<unknown> {\n const encodedQuery = typeof query === \"string\" ? query : null;\n // Encoding runs every render; only the safe failure fields define its identity.\n const parameter =\n query instanceof DatabaseQueryEncodingError ? query.parameter : undefined;\n const message =\n query instanceof DatabaseQueryEncodingError ? query.message : undefined;\n const route = useMemo((): Route => {\n if (!enabled) return null;\n if (encodedQuery === null) {\n const cause =\n parameter !== undefined && message !== undefined\n ? new DatabaseQueryEncodingError(parameter, message)\n : undefined;\n return { error: invalidDatabaseQuery(cause) };\n }\n try {\n return { url: resolveDatabaseUrl(entity, operation, id, encodedQuery) };\n } catch (error) {\n if (error instanceof DatabaseApiError) return { error };\n throw error;\n }\n }, [enabled, entity, operation, id, encodedQuery, parameter, message]);\n\n const url = route !== null && \"url\" in route ? route.url : null;\n const routeError = route !== null && \"error\" in route ? route.error : null;\n\n // Every subscriber of one URL encodes the same include, so the URL is the\n // include tree's identity; the object passed in may be a fresh literal.\n const scope = useMemo(\n () => (url === null ? null : databaseReadScope(entity, include)),\n [url],\n );\n\n const subscribe = useCallback(\n (listener: () => void) =>\n url === null ? noop : subscribeDatabaseRead(url, listener),\n [url],\n );\n const getSnapshot = useCallback(\n () => (url === null ? IDLE_DATABASE_READ : getDatabaseReadSnapshot(url)),\n [url],\n );\n const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n // The first subscriber of a URL starts the request; later ones share it.\n useEffect(() => {\n if (url === null || scope === null) return;\n return retainDatabaseRead(url, accept, scope);\n }, [url, accept, scope]);\n\n const refetch = useCallback(() => {\n if (url !== null) startDatabaseRead(url);\n }, [url]);\n\n const shaped = useShapedData(operation, snapshot.data, shape);\n\n // Until the effect retains a new URL, its request is about to start.\n const loading =\n snapshot.loading || (url !== null && snapshot === IDLE_DATABASE_READ);\n const error = routeError ?? snapshot.error ?? shaped.error;\n\n // The last data this hook showed for a URL, to hold across a params change.\n const previous = useRef<{ url: string; data: unknown } | null>(null);\n useEffect(() => {\n if (url !== null && shaped.data !== null) {\n previous.current = { url, data: shaped.data };\n }\n }, [url, shaped.data]);\n\n let data = shaped.data;\n if (\n keepPreviousData &&\n data === null &&\n loading &&\n error === null &&\n previous.current !== null &&\n previous.current.url !== url\n ) {\n data = previous.current.data;\n }\n\n return { data, loading, error, refetch };\n}\n"],"mappings":";;;;;;;AAmCA,MAAM,aAAa,OAAO,OAAO,EAAE,CAAC;;;;;;;;;;;;;;;;;AAkBpC,SAAgB,aAAkC;AAChD,QAAO;;AAmET,MAAM,aAAa;;AAGnB,SAAS,cACP,WACA,MACA,OACS;AACT,KAAI,cAAc,SAAU,QAAO,MAAM,KAAK;CAC9C,MAAM,OAAO;AACb,QAAO;EAAE,GAAG;EAAM,OAAO,KAAK,MAAM,KAAK,QAAQ,MAAM,IAAI,CAAC;EAAE;;;;;;;AAehE,SAAS,cACP,WACA,QACA,OACQ;CACR,MAAM,QAAQ,OAAsB,KAAK;AACzC,KAAI,OAAO,UAAU,cAAc,WAAW,KAC5C,QAAO;EAAE;EAAQ,MAAM;EAAQ,OAAO;EAAM;CAE9C,MAAM,SAAS,MAAM;AACrB,KAAI,WAAW,QAAQ,OAAO,WAAW,OAAQ,QAAO;CACxD,IAAI;AACJ,KAAI;AACF,WAAS;GACP;GACA,MAAM,cAAc,WAAW,QAAQ,MAAM;GAC7C,OAAO;GACR;UACM,OAAO;AAEd,WAAS;GACP;GACA,MAAM;GACN,OAAO,IAAI,iBACT,YACA,MACA,qDACA,EAAE,EACF,EAAE,OAAO,CACV;GACF;;AAEH,OAAM,UAAU;AAChB,QAAO;;;;;;;;AAST,SAAgB,gBAAgB,EAC9B,QACA,WACA,IACA,OACA,SACA,SACA,QACA,kBACA,SACsD;CACtD,MAAM,eAAe,OAAO,UAAU,WAAW,QAAQ;CAEzD,MAAM,YACJ,iBAAiB,6BAA6B,MAAM,YAAY;CAClE,MAAM,UACJ,iBAAiB,6BAA6B,MAAM,UAAU;CAChE,MAAM,QAAQ,cAAqB;AACjC,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI,iBAAiB,KAKnB,QAAO,EAAE,OAAO,qBAHd,cAAc,UAAa,YAAY,SACnC,IAAI,2BAA2B,WAAW,QAAQ,GAClD,OACqC,EAAE;AAE/C,MAAI;AACF,UAAO,EAAE,KAAK,mBAAmB,QAAQ,WAAW,IAAI,aAAa,EAAE;WAChE,OAAO;AACd,OAAI,iBAAiB,iBAAkB,QAAO,EAAE,OAAO;AACvD,SAAM;;IAEP;EAAC;EAAS;EAAQ;EAAW;EAAI;EAAc;EAAW;EAAQ,CAAC;CAEtE,MAAM,MAAM,UAAU,QAAQ,SAAS,QAAQ,MAAM,MAAM;CAC3D,MAAM,aAAa,UAAU,QAAQ,WAAW,QAAQ,MAAM,QAAQ;CAItE,MAAM,QAAQ,cACL,QAAQ,OAAO,OAAO,kBAAkB,QAAQ,QAAQ,EAC/D,CAAC,IAAI,CACN;CAED,MAAM,YAAY,aACf,aACC,QAAQ,OAAO,OAAO,sBAAsB,KAAK,SAAS,EAC5D,CAAC,IAAI,CACN;CACD,MAAM,cAAc,kBACX,QAAQ,OAAO,qBAAqB,wBAAwB,IAAI,EACvE,CAAC,IAAI,CACN;CACD,MAAM,WAAW,qBAAqB,WAAW,aAAa,YAAY;AAG1E,iBAAgB;AACd,MAAI,QAAQ,QAAQ,UAAU,KAAM;AACpC,SAAO,mBAAmB,KAAK,QAAQ,MAAM;IAC5C;EAAC;EAAK;EAAQ;EAAM,CAAC;CAExB,MAAM,UAAU,kBAAkB;AAChC,MAAI,QAAQ,KAAM,mBAAkB,IAAI;IACvC,CAAC,IAAI,CAAC;CAET,MAAM,SAAS,cAAc,WAAW,SAAS,MAAM,MAAM;CAG7D,MAAM,UACJ,SAAS,WAAY,QAAQ,QAAQ,aAAa;CACpD,MAAM,QAAQ,cAAc,SAAS,SAAS,OAAO;CAGrD,MAAM,WAAW,OAA8C,KAAK;AACpE,iBAAgB;AACd,MAAI,QAAQ,QAAQ,OAAO,SAAS,KAClC,UAAS,UAAU;GAAE;GAAK,MAAM,OAAO;GAAM;IAE9C,CAAC,KAAK,OAAO,KAAK,CAAC;CAEtB,IAAI,OAAO,OAAO;AAClB,KACE,oBACA,SAAS,QACT,WACA,UAAU,QACV,SAAS,YAAY,QACrB,SAAS,QAAQ,QAAQ,IAEzB,QAAO,SAAS,QAAQ;AAG1B,QAAO;EAAE;EAAM;EAAS;EAAO;EAAS"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ExactDatabaseParams } from "../../shared/src/database/api-types.js";
|
|
2
|
+
import "../../shared/src/index.js";
|
|
3
|
+
import { DatabaseId, DatabaseKeyedEntity, DatabaseRecordParams, DatabaseRecordRow } from "../../js/database/types.js";
|
|
4
|
+
import { UseDatabaseReadOptions, UseDatabaseReadResult } from "./use-database-read.js";
|
|
5
|
+
|
|
6
|
+
//#region src/react/hooks/use-database-record.d.ts
|
|
7
|
+
/** Options for {@link useDatabaseRecord}. */
|
|
8
|
+
type UseDatabaseRecordOptions<Row> = UseDatabaseReadOptions<Row>;
|
|
9
|
+
/** What {@link useDatabaseRecord} returns: one row and its state. */
|
|
10
|
+
type UseDatabaseRecordResult<Row> = UseDatabaseReadResult<Row>;
|
|
11
|
+
/**
|
|
12
|
+
* Subscribe to one row from `GET /api/database/<entity>/:id`. Only entities
|
|
13
|
+
* with a public primary key have this route; a missing row surfaces as a
|
|
14
|
+
* `NOT_FOUND` error, and a refetch that finds the row gone clears `data`.
|
|
15
|
+
*
|
|
16
|
+
* A `null` or `undefined` id holds the hook idle without a request, so a
|
|
17
|
+
* record that depends on another read needs no separate `enabled` flag. An
|
|
18
|
+
* empty, `"."`, or `".."` id reports `INVALID_REQUEST` without a request.
|
|
19
|
+
*
|
|
20
|
+
* @param entity - A table the generated registry exposes with a public key
|
|
21
|
+
* @param id - The row's public key, or `null`/`undefined` to wait
|
|
22
|
+
* @param params - `select` and `include`; pass `{}` to reach `options` alone
|
|
23
|
+
* @param options - `enabled`, `keepPreviousData`, and `shape`
|
|
24
|
+
* @returns The row, loading and error state, and `refetch`
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```tsx
|
|
28
|
+
* const board = useDatabaseRecord("boards", selectedId, {
|
|
29
|
+
* include: { notes: { limit: 20 } },
|
|
30
|
+
* });
|
|
31
|
+
* board.data?.notes.length;
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
declare function useDatabaseRecord<K extends DatabaseKeyedEntity, const P extends DatabaseRecordParams<K> = Record<never, never>, Row = DatabaseRecordRow<K, P>>(entity: K, id: DatabaseId<K> | null | undefined, params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>, options?: UseDatabaseRecordOptions<Row>): UseDatabaseRecordResult<Row>;
|
|
35
|
+
//#endregion
|
|
36
|
+
export { UseDatabaseRecordOptions, UseDatabaseRecordResult, useDatabaseRecord };
|
|
37
|
+
//# sourceMappingURL=use-database-record.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-record.d.ts","names":[],"sources":["../../../src/react/hooks/use-database-record.ts"],"mappings":";;;;;;;KAsBY,wBAAA,QAAgC,sBAAA,CAAuB,GAAA;;KAGvD,uBAAA,QAA+B,qBAAA,CAAsB,GAAA;;;;;;;;;AAAjE;;;;;;;;;AAyBA;;;;;;iBAAgB,iBAAA,WACJ,mBAAA,kBACM,oBAAA,CAAqB,CAAA,IAAK,MAAA,sBACpC,iBAAA,CAAkB,CAAA,EAAG,CAAA,EAAA,CAE3B,MAAA,EAAQ,CAAA,EACR,EAAA,EAAI,UAAA,CAAW,CAAA,sBACf,MAAA,GAAS,CAAA,GAAI,mBAAA,CAAoB,CAAA,EAAG,oBAAA,CAAqB,CAAA,IACzD,OAAA,GAAS,wBAAA,CAAyB,GAAA,IACjC,uBAAA,CAAwB,GAAA"}
|