@veducio/keja 0.7.0 → 0.8.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veducio/keja",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "description": "Veducio Keja - RESTFUL Web Server, Based on Lightweight Hono Framework, Written in TypeScript, Powered by Bun",
6
6
  "license": "MIT",
@@ -4,9 +4,17 @@ import { runSeed } from "../seed-project.ts";
4
4
  export const seed = defineCommand({
5
5
  meta: {
6
6
  name: "seed",
7
- description: "Insert project seeders",
7
+ description: "Clear seeded tables and insert project seeders",
8
8
  },
9
- async run() {
10
- await runSeed();
9
+ args: {
10
+ yes: {
11
+ type: "boolean",
12
+ description: "Skip the confirmation prompt",
13
+ alias: "y",
14
+ default: false,
15
+ },
16
+ },
17
+ async run({ args }) {
18
+ await runSeed(process.cwd(), { yes: args.yes === true });
11
19
  },
12
20
  });
@@ -1,14 +1,19 @@
1
1
  import path from "node:path";
2
+ import { createInterface } from "node:readline/promises";
2
3
  import { DBCall, setDatabase } from "../db/client.ts";
3
4
  import { connectDatabase } from "../db/postgres.ts";
4
5
  import { DependencyNotMet } from "../errors/framework-errors.ts";
5
6
  import { loadConfig } from "../project/config.ts";
6
- import { applySeeder } from "../seed/apply.ts";
7
+ import { applySeeder, truncateSeedTables } from "../seed/apply.ts";
8
+ import { confirmSeed } from "../seed/confirm.ts";
7
9
  import { loadSeeders } from "../seed/load.ts";
8
10
  import { formatSeed } from "../seed/report.ts";
9
11
  import { formatProjectFailure, readProjectFailure } from "./run-project.ts";
10
12
 
11
- export async function runSeed(root = process.cwd()) {
13
+ export async function runSeed(
14
+ root = process.cwd(),
15
+ options: { yes?: boolean } = {},
16
+ ) {
12
17
  let opened = false;
13
18
  try {
14
19
  const project = await loadConfig(root);
@@ -18,6 +23,24 @@ export async function runSeed(root = process.cwd()) {
18
23
  await connectDatabase(Bun.env.DATABASE_URL ?? "");
19
24
  opened = true;
20
25
  const seeders = await loadSeeders(path.join(root, "seed"));
26
+ const tables = seeders.map((seeder) => seeder.table);
27
+ const confirmed = await confirmSeed({
28
+ yes: options.yes === true,
29
+ interactive:
30
+ process.stdin.isTTY === true && process.stdout.isTTY === true,
31
+ tables,
32
+ ask: askSeedConfirm,
33
+ });
34
+ if (confirmed === "needs-yes") {
35
+ console.error("Pass --yes to seed without a prompt.");
36
+ process.exitCode = 1;
37
+ return;
38
+ }
39
+ if (confirmed === "no") {
40
+ console.log(" Seed cancelled.");
41
+ return;
42
+ }
43
+ await truncateSeedTables(tables);
21
44
  const results = [];
22
45
  for (const seeder of seeders) {
23
46
  results.push({
@@ -44,3 +67,15 @@ export async function runSeed(root = process.cwd()) {
44
67
  process.exit(1);
45
68
  }
46
69
  }
70
+
71
+ async function askSeedConfirm(message: string) {
72
+ const rl = createInterface({
73
+ input: process.stdin,
74
+ output: process.stdout,
75
+ });
76
+ try {
77
+ return await rl.question(` ${message} [y/N] `);
78
+ } finally {
79
+ rl.close();
80
+ }
81
+ }
@@ -60,4 +60,18 @@ describe("runMiddleware", () => {
60
60
  ).rejects.toThrow(`Middleware cannot pass reserved field ${key}`);
61
61
  }
62
62
  });
63
+
64
+ it("rejects next() when the rest of the chain does not return a Response", async () => {
65
+ const step = defineMiddleware(async ({ next }) => {
66
+ const response = await next();
67
+ return response;
68
+ });
69
+ await expect(
70
+ runMiddleware(
71
+ [{ definition: step, allowFields: true }],
72
+ context,
73
+ () => undefined as never,
74
+ ),
75
+ ).rejects.toThrow("next() must resolve to a Response");
76
+ });
63
77
  });
@@ -128,7 +128,11 @@ export async function runMiddleware(
128
128
  }
129
129
  Object.assign(fields, passed);
130
130
  }
131
- return dispatch();
131
+ const nextResponse = await dispatch();
132
+ if (!(nextResponse instanceof Response)) {
133
+ throw new Error("next() must resolve to a Response");
134
+ }
135
+ return nextResponse;
132
136
  },
133
137
  });
134
138
  if (!(response instanceof Response)) {
@@ -1,11 +1,11 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import { setDatabase } from "../db/client.ts";
3
3
  import { createTypeId } from "../typeid/id.ts";
4
- import { applySeeder } from "./apply.ts";
4
+ import { applySeeder, truncateSeedTables } from "./apply.ts";
5
5
  import { defineSeeder } from "./define.ts";
6
6
 
7
7
  describe("applySeeder", () => {
8
- it("inserts owned rows and skips an existing _id", async () => {
8
+ it("inserts owned rows after a clear", async () => {
9
9
  const calls: unknown[][] = [];
10
10
  setDatabase(((...args: unknown[]) => {
11
11
  calls.push(args);
@@ -41,8 +41,29 @@ describe("applySeeder", () => {
41
41
  const statement = Array.from(template?.[0] as ArrayLike<string>).join(
42
42
  " ",
43
43
  );
44
- expect(statement).toContain("on conflict (_id) do nothing");
45
44
  expect(statement).toContain("returning _id");
45
+ expect(statement).not.toContain("on conflict");
46
+ } finally {
47
+ setDatabase(null);
48
+ }
49
+ });
50
+ });
51
+
52
+ describe("truncateSeedTables", () => {
53
+ it("truncates each seeded table once", async () => {
54
+ const statements: string[] = [];
55
+ setDatabase({
56
+ unsafe(statement: string) {
57
+ statements.push(statement);
58
+ },
59
+ } as never);
60
+ try {
61
+ await truncateSeedTables(["users", "notes", "users"]);
62
+ expect(statements).toEqual([
63
+ 'truncate "users", "notes" restart identity cascade',
64
+ ]);
65
+ await truncateSeedTables([]);
66
+ expect(statements).toHaveLength(1);
46
67
  } finally {
47
68
  setDatabase(null);
48
69
  }
package/src/seed/apply.ts CHANGED
@@ -1,11 +1,23 @@
1
1
  import { DBCall } from "../db/client.ts";
2
2
  import type { Seeder } from "./define.ts";
3
3
 
4
+ export async function truncateSeedTables(tables: readonly string[]) {
5
+ const unique = [...new Set(tables)];
6
+ if (unique.length === 0) {
7
+ return;
8
+ }
9
+ const list = unique.map((table) => quote(table)).join(", ");
10
+ await DBCall.unsafe(`truncate ${list} restart identity cascade`);
11
+ }
12
+
4
13
  export async function applySeeder(seeder: Seeder) {
5
14
  const inserted = await DBCall`
6
15
  insert into ${DBCall(seeder.table)} ${DBCall(seeder.objects)}
7
- on conflict (_id) do nothing
8
16
  returning _id
9
17
  `;
10
18
  return Array.isArray(inserted) ? inserted.length : 0;
11
19
  }
20
+
21
+ function quote(name: string) {
22
+ return `"${name.replaceAll('"', '""')}"`;
23
+ }
@@ -0,0 +1,56 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { confirmSeed, confirmSeedMessage } from "./confirm.ts";
3
+
4
+ describe("confirmSeed", () => {
5
+ it("names the tables that will be cleared", () => {
6
+ expect(confirmSeedMessage(["users", "notes", "users"])).toBe(
7
+ "This will clear users, notes and insert seed data. Continue?",
8
+ );
9
+ });
10
+
11
+ it("accepts --yes without asking", async () => {
12
+ let asked = false;
13
+ await expect(
14
+ confirmSeed({
15
+ yes: true,
16
+ interactive: true,
17
+ tables: ["users"],
18
+ ask: async () => {
19
+ asked = true;
20
+ return "n";
21
+ },
22
+ }),
23
+ ).resolves.toBe("yes");
24
+ expect(asked).toBe(false);
25
+ });
26
+
27
+ it("requires --yes when there is no terminal", async () => {
28
+ await expect(
29
+ confirmSeed({
30
+ yes: false,
31
+ interactive: false,
32
+ tables: ["users"],
33
+ ask: async () => "y",
34
+ }),
35
+ ).resolves.toBe("needs-yes");
36
+ });
37
+
38
+ it("accepts y or yes from the prompt", async () => {
39
+ await expect(
40
+ confirmSeed({
41
+ yes: false,
42
+ interactive: true,
43
+ tables: ["users"],
44
+ ask: async () => " Y ",
45
+ }),
46
+ ).resolves.toBe("yes");
47
+ await expect(
48
+ confirmSeed({
49
+ yes: false,
50
+ interactive: true,
51
+ tables: ["users"],
52
+ ask: async () => "no",
53
+ }),
54
+ ).resolves.toBe("no");
55
+ });
56
+ });
@@ -0,0 +1,25 @@
1
+ export function confirmSeedMessage(tables: readonly string[]) {
2
+ const unique = [...new Set(tables)];
3
+ const list = unique.length > 0 ? unique.join(", ") : "no tables";
4
+ return `This will clear ${list} and insert seed data. Continue?`;
5
+ }
6
+
7
+ export async function confirmSeed(options: {
8
+ yes: boolean;
9
+ interactive: boolean;
10
+ tables: readonly string[];
11
+ ask: (message: string) => Promise<string>;
12
+ }) {
13
+ if (options.yes) {
14
+ return "yes" as const;
15
+ }
16
+ if (!options.interactive) {
17
+ return "needs-yes" as const;
18
+ }
19
+ const answer = (await options.ask(confirmSeedMessage(options.tables)))
20
+ .trim()
21
+ .toLowerCase();
22
+ return answer === "y" || answer === "yes"
23
+ ? ("yes" as const)
24
+ : ("no" as const);
25
+ }