templates.ts51 lines · main
1import { brivenError } from '@briven/shared';
2
3import { getTemplate } from '../templates/index.js';
4
5import { createTable, insertRow } from './studio.js';
6
7export interface SeedTemplateResult {
8 readonly templateId: string;
9 readonly tablesCreated: number;
10 readonly rowsInserted: number;
11}
12
13/**
14 * Stand up a starter template inside an already-provisioned project: create
15 * each table (in FK order) then seed its sample rows. Uses the same studio
16 * services the UI uses, so every identifier + value is schema-validated and
17 * the result is indistinguishable from a user who built it by hand.
18 *
19 * Not transactional across tables — each createTable/insertRow is its own
20 * statement. A template is fixed, validated data (not user input), so partial
21 * failure should not happen in practice; if it does, the caller surfaces the
22 * error and the half-seeded project can be deleted + recreated.
23 */
24export async function seedTemplate(
25 projectId: string,
26 templateId: string,
27): Promise<SeedTemplateResult> {
28 const tpl = getTemplate(templateId);
29 if (!tpl) {
30 throw new brivenError('not_found', `unknown template: ${templateId}`, { status: 404 });
31 }
32
33 let tablesCreated = 0;
34 let rowsInserted = 0;
35
36 for (const table of tpl.tables) {
37 await createTable({
38 projectId,
39 tableName: table.tableName,
40 columns: table.columns,
41 });
42 tablesCreated++;
43
44 for (const values of table.rows ?? []) {
45 await insertRow({ projectId, tableName: table.tableName, values });
46 rowsInserted++;
47 }
48 }
49
50 return { templateId: tpl.id, tablesCreated, rowsInserted };
51}