UNPKG

2.08 kBPlain TextView Raw
1import {
2 AkteFiles,
3 type FilesBulkDataFn,
4 type FilesDataFn,
5 type FilesDefinition,
6} from "./AkteFiles";
7import type { Empty } from "./types";
8
9type FileDefinition<TGlobalData, TData> = Omit<
10 FilesDefinition<TGlobalData, never[], TData>,
11 "bulkData"
12>;
13
14/**
15 * Creates an Akte files instance for a single file.
16 *
17 * @example
18 * const posts = defineAkteFile().from({
19 * path: "/about",
20 * data() {
21 * return {};
22 * },
23 * render(context) {
24 * return "...";
25 * },
26 * });
27 *
28 * @typeParam TGlobalData - Global data the Akte files expects.
29 * @typeParam TData - Data the Akte files expects (inferred by default)
30 * @returns A factory to create the Akte files from.
31 */
32export const defineAkteFile = <TGlobalData, TData = Empty>(): {
33 /**
34 * Creates an Akte files instance for a single file from a definition.
35 *
36 * @param definition - The definition to create the instance from.
37 * @returns The created Akte files.
38 */
39 from: <
40 _TGlobalData extends TGlobalData,
41 _TData extends TData extends Empty
42 ? _TDataFn extends FilesDataFn<_TGlobalData, never[], unknown>
43 ? Awaited<ReturnType<_TDataFn>>
44 : undefined
45 : TData,
46 _TDataFn extends FilesDataFn<_TGlobalData, never[], unknown> | undefined,
47 >(
48 definition: FileDefinition<_TGlobalData, _TData>,
49 ) => AkteFiles<_TGlobalData, never[], _TData>;
50} => {
51 return {
52 from: (definition) => {
53 type _FileDataFn = Required<typeof definition>["data"];
54
55 // Allows single file to still get build without any data function
56 const data = (() => {}) as unknown as _FileDataFn;
57
58 const bulkData: FilesBulkDataFn<
59 Parameters<_FileDataFn>[0]["globalData"],
60 Awaited<ReturnType<_FileDataFn>>
61 > = async (args) => {
62 if (definition.data) {
63 return {
64 [definition.path]: await definition.data({
65 path: definition.path,
66 params: {},
67 globalData: args.globalData,
68 }),
69 };
70 }
71
72 return { [definition.path]: {} as Awaited<ReturnType<_FileDataFn>> };
73 };
74
75 return new AkteFiles({
76 data,
77 ...definition,
78 bulkData,
79 });
80 },
81 };
82};