keryx 0.46.0 → 0.47.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/README.md +1 -1
- package/actions/status.ts +9 -7
- package/config/database.ts +2 -1
- package/index.ts +1 -1
- package/initializers/db.ts +28 -0
- package/initializers/redis.ts +23 -1
- package/initializers/resque.ts +14 -3
- package/middleware/transaction.ts +3 -1
- package/package.json +7 -5
- package/templates/scaffold/env.example.mustache +16 -1
- package/testing/index.ts +2 -2
- package/util/cli.ts +9 -1
- package/util/connectionString.ts +26 -1
- package/util/scaffold.ts +24 -3
- package/util/transaction.ts +19 -1
- package/util/zodMixins.ts +2 -0
package/README.md
CHANGED
|
@@ -123,7 +123,7 @@ bun install
|
|
|
123
123
|
bun dev
|
|
124
124
|
```
|
|
125
125
|
|
|
126
|
-
Requires Bun, PostgreSQL, and Redis. See the [Getting Started guide](https://keryxjs.com/guide/) for full setup instructions.
|
|
126
|
+
Requires Bun, PostgreSQL, and Redis. See the [Getting Started guide](https://keryxjs.com/guide/) for full setup instructions (including running without Postgres or Redis for quick prototypes).
|
|
127
127
|
|
|
128
128
|
### Developing the framework itself
|
|
129
129
|
|
package/actions/status.ts
CHANGED
|
@@ -7,7 +7,7 @@ import packageJSON from "../package.json";
|
|
|
7
7
|
export class Status implements Action {
|
|
8
8
|
name = "status";
|
|
9
9
|
description =
|
|
10
|
-
"Returns server health and runtime information including the server name, process ID, package version, uptime in milliseconds, memory consumption in MB, and dependency health checks for the database and Redis. Does not require authentication.";
|
|
10
|
+
"Returns server health and runtime information including the server name, process ID, package version, uptime in milliseconds, memory consumption in MB, and dependency health checks for the database and Redis. A check is `null` when that dependency is disabled (e.g. no `DATABASE_URL`), and disabled checks do not affect `healthy`. Does not require authentication.";
|
|
11
11
|
inputs = z.object({});
|
|
12
12
|
web = { route: "/status", method: HTTP_METHOD.GET };
|
|
13
13
|
tracing = false;
|
|
@@ -16,13 +16,15 @@ export class Status implements Action {
|
|
|
16
16
|
const consumedMemoryMB =
|
|
17
17
|
Math.round((process.memoryUsage().heapUsed / 1024 / 1024) * 100) / 100;
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
// `null` = the database is disabled, so it is not part of the health verdict.
|
|
20
|
+
let databaseHealthy: boolean | null = null;
|
|
21
|
+
if (api.db?.enabled) {
|
|
22
|
+
databaseHealthy = false;
|
|
23
|
+
try {
|
|
22
24
|
await api.db.db.execute(sql`SELECT NOW()`);
|
|
23
25
|
databaseHealthy = true;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
+
} catch {}
|
|
27
|
+
}
|
|
26
28
|
|
|
27
29
|
let redisHealthy = false;
|
|
28
30
|
try {
|
|
@@ -32,7 +34,7 @@ export class Status implements Action {
|
|
|
32
34
|
}
|
|
33
35
|
} catch {}
|
|
34
36
|
|
|
35
|
-
const healthy = databaseHealthy && redisHealthy;
|
|
37
|
+
const healthy = databaseHealthy !== false && redisHealthy;
|
|
36
38
|
|
|
37
39
|
return {
|
|
38
40
|
name: api.process.name,
|
package/config/database.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { loadFromEnvIfSet } from "../util/config";
|
|
2
2
|
|
|
3
3
|
export const configDatabase = {
|
|
4
|
-
|
|
4
|
+
/** Postgres connection URL. Empty (the default) or `"none"` runs without a database. */
|
|
5
|
+
connectionString: await loadFromEnvIfSet("DATABASE_URL", ""),
|
|
5
6
|
autoMigrate: await loadFromEnvIfSet("DATABASE_AUTO_MIGRATE", true),
|
|
6
7
|
pool: {
|
|
7
8
|
max: await loadFromEnvIfSet("DATABASE_POOL_MAX", 10),
|
package/index.ts
CHANGED
|
@@ -86,7 +86,7 @@ export {
|
|
|
86
86
|
} from "./util/swaggerSchemaGenerator";
|
|
87
87
|
export { toMarkdown } from "./util/toMarkdown";
|
|
88
88
|
export type { DbOrTransaction, Transaction } from "./util/transaction";
|
|
89
|
-
export { withTransaction } from "./util/transaction";
|
|
89
|
+
export { assertDatabaseEnabled, withTransaction } from "./util/transaction";
|
|
90
90
|
export {
|
|
91
91
|
isSecret,
|
|
92
92
|
paginationInputs,
|
package/initializers/db.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { ErrorType, TypedError } from "../classes/TypedError";
|
|
|
14
14
|
import { config } from "../config";
|
|
15
15
|
import {
|
|
16
16
|
formatConnectionStringForLogging,
|
|
17
|
+
isDatabaseDisabled,
|
|
17
18
|
throwConnectionError,
|
|
18
19
|
} from "../util/connectionString";
|
|
19
20
|
import { globModuleExports } from "../util/glob";
|
|
@@ -72,6 +73,15 @@ declare module "keryx" {
|
|
|
72
73
|
}
|
|
73
74
|
}
|
|
74
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Initializer that connects Drizzle ORM to Postgres, runs migrations, and exposes
|
|
78
|
+
* `api.db.db` (the Drizzle instance), `api.db.pool` and `api.db.schema`.
|
|
79
|
+
*
|
|
80
|
+
* An empty `DATABASE_URL` (or `"none"`) disables the database: nothing connects, no
|
|
81
|
+
* migrations run, `api.db.enabled` is `false`, and `api.db.db` / `api.db.pool` stay
|
|
82
|
+
* unset. Helpers that need a database (`withTransaction`, `TransactionMiddleware`,
|
|
83
|
+
* `zIdOrModel`) then throw a clear `TypedError` instead.
|
|
84
|
+
*/
|
|
75
85
|
export class DB extends Initializer {
|
|
76
86
|
constructor() {
|
|
77
87
|
super(namespace);
|
|
@@ -91,12 +101,27 @@ export class DB extends Initializer {
|
|
|
91
101
|
generateMigrations: this.generateMigrations,
|
|
92
102
|
clearDatabase: this.clearDatabase,
|
|
93
103
|
schema,
|
|
104
|
+
/** `false` when `DATABASE_URL` is empty or `"none"` and no database is connected. */
|
|
105
|
+
enabled: false,
|
|
94
106
|
},
|
|
95
107
|
dbContainer,
|
|
96
108
|
);
|
|
97
109
|
}
|
|
98
110
|
|
|
99
111
|
async start() {
|
|
112
|
+
if (isDatabaseDisabled(config.database.connectionString)) {
|
|
113
|
+
api.db.enabled = false;
|
|
114
|
+
logger.warn('database disabled (DATABASE_URL is empty or "none")');
|
|
115
|
+
const tableCount = Object.keys(api.db.schema).length;
|
|
116
|
+
if (tableCount > 0) {
|
|
117
|
+
logger.warn(
|
|
118
|
+
`${tableCount} table(s) found in ${SCHEMA_DIR}/ will not be available without a database`,
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
api.db.enabled = true;
|
|
100
125
|
api.db.pool = new Pool({
|
|
101
126
|
connectionString: config.database.connectionString,
|
|
102
127
|
...config.database.pool,
|
|
@@ -216,6 +241,7 @@ export class DB extends Initializer {
|
|
|
216
241
|
|
|
217
242
|
/**
|
|
218
243
|
* Erase all the tables in the active database. Will fail on production environments.
|
|
244
|
+
* A no-op when the database is disabled.
|
|
219
245
|
*/
|
|
220
246
|
async clearDatabase(restartIdentity = true, cascade = true) {
|
|
221
247
|
if (Bun.env.NODE_ENV === "production") {
|
|
@@ -225,6 +251,8 @@ export class DB extends Initializer {
|
|
|
225
251
|
});
|
|
226
252
|
}
|
|
227
253
|
|
|
254
|
+
if (!api.db.enabled) return;
|
|
255
|
+
|
|
228
256
|
const { rows } = await api.db.db.execute(
|
|
229
257
|
sql`SELECT tablename FROM pg_tables WHERE schemaname = CURRENT_SCHEMA`,
|
|
230
258
|
);
|
package/initializers/redis.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { config } from "../config";
|
|
|
5
5
|
|
|
6
6
|
import {
|
|
7
7
|
formatConnectionStringForLogging,
|
|
8
|
+
isMemoryRedis,
|
|
8
9
|
throwConnectionError,
|
|
9
10
|
} from "../util/connectionString";
|
|
10
11
|
|
|
@@ -21,6 +22,12 @@ declare module "keryx" {
|
|
|
21
22
|
* Initializer that manages two Redis connections: `redis` for general commands and
|
|
22
23
|
* `subscription` for PubSub. Both are created during `start()` and closed during `stop()`.
|
|
23
24
|
* Exposes `api.redis.redis` and `api.redis.subscription` as ioredis `RedisClient` instances.
|
|
25
|
+
*
|
|
26
|
+
* When `REDIS_URL` uses the `memory:` scheme (e.g. `memory://`), both clients are
|
|
27
|
+
* in-process `ioredis-mock` instances that share one dataset instead of connections to
|
|
28
|
+
* a Redis server. Tasks, PubSub, presence, sessions and rate limiting all keep working,
|
|
29
|
+
* but state lives only in this process: it is not shared with other processes and is
|
|
30
|
+
* lost when the process exits. `api.redis.inMemory` reports which mode is active.
|
|
24
31
|
*/
|
|
25
32
|
export class Redis extends Initializer {
|
|
26
33
|
constructor() {
|
|
@@ -28,14 +35,29 @@ export class Redis extends Initializer {
|
|
|
28
35
|
}
|
|
29
36
|
|
|
30
37
|
async initialize() {
|
|
31
|
-
const redisContainer = {} as {
|
|
38
|
+
const redisContainer = { inMemory: false } as {
|
|
32
39
|
redis: RedisClient;
|
|
33
40
|
subscription: RedisClient;
|
|
41
|
+
/** `true` when `REDIS_URL` selected the in-process `memory://` Redis. */
|
|
42
|
+
inMemory: boolean;
|
|
34
43
|
};
|
|
35
44
|
return redisContainer;
|
|
36
45
|
}
|
|
37
46
|
|
|
38
47
|
async start() {
|
|
48
|
+
api.redis.inMemory = isMemoryRedis(config.redis.connectionString);
|
|
49
|
+
|
|
50
|
+
if (api.redis.inMemory) {
|
|
51
|
+
// Loaded on demand so apps using a real Redis never pay for ioredis-mock's Lua VM.
|
|
52
|
+
const { default: RedisMock } = await import("ioredis-mock");
|
|
53
|
+
api.redis.redis = new RedisMock();
|
|
54
|
+
api.redis.subscription = new RedisMock();
|
|
55
|
+
logger.warn(
|
|
56
|
+
"using in-memory redis (REDIS_URL=memory://): state is kept in this process only, is not shared with other processes, and is lost on restart",
|
|
57
|
+
);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
39
61
|
api.redis.redis = new RedisClient(config.redis.connectionString);
|
|
40
62
|
api.redis.subscription = new RedisClient(config.redis.connectionString);
|
|
41
63
|
|
package/initializers/resque.ts
CHANGED
|
@@ -100,10 +100,21 @@ export class Resque extends Initializer {
|
|
|
100
100
|
this.dependsOn = ["redis", "db", "actions", "process", "hooks"];
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
+
/**
|
|
104
|
+
* Connection options shared by the resque Queue, Scheduler and Workers. They all reuse
|
|
105
|
+
* `api.redis.redis`. With the in-memory Redis, `pkg: "ioredis-mock"` tells node-resque
|
|
106
|
+
* to skip its `cjson`-based Lua script (unsupported by ioredis-mock) and fall back to
|
|
107
|
+
* plain commands when workers pop jobs.
|
|
108
|
+
*/
|
|
109
|
+
connectionOptions = () => ({
|
|
110
|
+
redis: api.redis.redis,
|
|
111
|
+
...(api.redis.inMemory ? { pkg: "ioredis-mock" } : {}),
|
|
112
|
+
});
|
|
113
|
+
|
|
103
114
|
/** Create and connect the resque `Queue` instance (used for enqueuing jobs). */
|
|
104
115
|
startQueue = async () => {
|
|
105
116
|
api.resque.queue = new Queue(
|
|
106
|
-
{ connection:
|
|
117
|
+
{ connection: this.connectionOptions() },
|
|
107
118
|
api.resque.jobs,
|
|
108
119
|
);
|
|
109
120
|
|
|
@@ -125,7 +136,7 @@ export class Resque extends Initializer {
|
|
|
125
136
|
startScheduler = async () => {
|
|
126
137
|
if (config.tasks.enabled === true) {
|
|
127
138
|
api.resque.scheduler = new Scheduler({
|
|
128
|
-
connection:
|
|
139
|
+
connection: this.connectionOptions(),
|
|
129
140
|
timeout: config.tasks.timeout,
|
|
130
141
|
stuckWorkerTimeout: config.tasks.stuckWorkerTimeout,
|
|
131
142
|
retryStuckJobs: config.tasks.retryStuckJobs,
|
|
@@ -177,7 +188,7 @@ export class Resque extends Initializer {
|
|
|
177
188
|
while (id < config.tasks.taskProcessors) {
|
|
178
189
|
const worker = new Worker(
|
|
179
190
|
{
|
|
180
|
-
connection:
|
|
191
|
+
connection: this.connectionOptions(),
|
|
181
192
|
queues: Array.isArray(config.tasks.queues)
|
|
182
193
|
? config.tasks.queues
|
|
183
194
|
: await config.tasks.queues(),
|
|
@@ -4,7 +4,7 @@ import { api, logger } from "../api";
|
|
|
4
4
|
import type { ActionMiddleware } from "../classes/Action";
|
|
5
5
|
import type { Connection } from "../classes/Connection";
|
|
6
6
|
import type { TypedError } from "../classes/TypedError";
|
|
7
|
-
import type
|
|
7
|
+
import { assertDatabaseEnabled, type Transaction } from "../util/transaction";
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Action middleware that wraps the entire action execution in a database transaction.
|
|
@@ -50,6 +50,8 @@ export const TransactionMiddleware: ActionMiddleware = {
|
|
|
50
50
|
_params: Record<string, unknown>,
|
|
51
51
|
connection: Connection,
|
|
52
52
|
) => {
|
|
53
|
+
assertDatabaseEnabled("TransactionMiddleware");
|
|
54
|
+
|
|
53
55
|
// If a parent action already opened a transaction, reuse it.
|
|
54
56
|
// Track depth so only the outermost middleware commits/rolls back.
|
|
55
57
|
const depth = (connection.metadata._txDepth as number | undefined) ?? 0;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keryx",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.0",
|
|
4
4
|
"module": "index.ts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -87,15 +87,17 @@
|
|
|
87
87
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
88
88
|
"@opentelemetry/api": "^1.9.1",
|
|
89
89
|
"@opentelemetry/sdk-metrics": "^2.7.0",
|
|
90
|
+
"@types/ioredis-mock": "^8.2.8",
|
|
91
|
+
"@types/mustache": "^4.2.6",
|
|
92
|
+
"@types/pg": "^8.20.0",
|
|
93
|
+
"commander": "^14.0.3",
|
|
90
94
|
"ioredis": "^5.10.1",
|
|
95
|
+
"ioredis-mock": "^8.13.1",
|
|
91
96
|
"mustache": "^4.2.0",
|
|
92
97
|
"node-resque": "^9.5.2",
|
|
93
98
|
"pg": "^8.20.0",
|
|
94
99
|
"ts-morph": "^28.0.0",
|
|
95
|
-
"typescript": "^7.0.2"
|
|
96
|
-
"commander": "^14.0.3",
|
|
97
|
-
"@types/mustache": "^4.2.6",
|
|
98
|
-
"@types/pg": "^8.20.0"
|
|
100
|
+
"typescript": "^7.0.2"
|
|
99
101
|
},
|
|
100
102
|
"peerDependencies": {
|
|
101
103
|
"drizzle-orm": "^0.45.2",
|
|
@@ -20,12 +20,27 @@ MCP_SERVER_ENABLED=true
|
|
|
20
20
|
SESSION_TTL=86400
|
|
21
21
|
SESSION_COOKIE_NAME="__session"
|
|
22
22
|
|
|
23
|
+
{{#includeDb}}
|
|
23
24
|
DATABASE_URL="postgres://$USER@localhost:5432/{{projectName}}"
|
|
24
25
|
DATABASE_URL_TEST="postgres://$USER@localhost:5432/{{projectName}}-test"
|
|
25
26
|
DATABASE_AUTO_MIGRATE=true
|
|
26
|
-
|
|
27
|
+
{{/includeDb}}
|
|
28
|
+
{{^includeDb}}
|
|
29
|
+
# No database: an empty DATABASE_URL (or "none") runs without PostgreSQL.
|
|
30
|
+
# Set a postgres:// URL here to add one later.
|
|
31
|
+
DATABASE_URL=""
|
|
32
|
+
{{/includeDb}}
|
|
33
|
+
|
|
34
|
+
{{#includeRedis}}
|
|
27
35
|
REDIS_URL="redis://localhost:6379/0"
|
|
28
36
|
REDIS_URL_TEST="redis://localhost:6379/1"
|
|
37
|
+
{{/includeRedis}}
|
|
38
|
+
{{^includeRedis}}
|
|
39
|
+
# In-memory Redis: tasks, PubSub, sessions and caching work without a Redis server,
|
|
40
|
+
# but state lives in this process only and is lost on restart.
|
|
41
|
+
# Use a redis:// URL to run more than one process or keep state across restarts.
|
|
42
|
+
REDIS_URL="memory://"
|
|
43
|
+
{{/includeRedis}}
|
|
29
44
|
|
|
30
45
|
RATE_LIMIT_ENABLED=true
|
|
31
46
|
RATE_LIMIT_WINDOW_MS=60000
|
package/testing/index.ts
CHANGED
|
@@ -65,8 +65,8 @@ export function serverUrl(): string {
|
|
|
65
65
|
* start/stop pair rather than splitting it, or handle cleanup in `afterEach`.
|
|
66
66
|
*
|
|
67
67
|
* @param opts.clearDatabase - Truncate all tables in `beforeAll`. Default `false`.
|
|
68
|
-
* Requires the `db` initializer to be active
|
|
69
|
-
* persistent state.
|
|
68
|
+
* Requires the `db` initializer to be active; a no-op when the database is
|
|
69
|
+
* disabled (empty `DATABASE_URL`). Opt in for tests that mutate persistent state.
|
|
70
70
|
* @param opts.clearRedis - Flush the current Redis DB in `beforeAll`. Default
|
|
71
71
|
* `false`. Requires the `redis` initializer to be active. Opt in for tests
|
|
72
72
|
* that exercise pub/sub so messages from prior tests don't leak in.
|
package/util/cli.ts
CHANGED
|
@@ -39,7 +39,14 @@ export async function buildProgram(opts: {
|
|
|
39
39
|
.description("Scaffold a new Keryx application with project boilerplate")
|
|
40
40
|
.option("-y, --yes", "Skip prompts and use defaults")
|
|
41
41
|
.option("--no-interactive", "Skip prompts and use defaults")
|
|
42
|
-
.option(
|
|
42
|
+
.option(
|
|
43
|
+
"--no-db",
|
|
44
|
+
"Run without PostgreSQL (no database files, empty DATABASE_URL)",
|
|
45
|
+
)
|
|
46
|
+
.option(
|
|
47
|
+
"--no-redis",
|
|
48
|
+
"Run without a Redis server (in-memory Redis, REDIS_URL=memory://)",
|
|
49
|
+
)
|
|
43
50
|
.option("--no-example", "Skip example action")
|
|
44
51
|
.option(
|
|
45
52
|
"--force",
|
|
@@ -52,6 +59,7 @@ export async function buildProgram(opts: {
|
|
|
52
59
|
projectName = projectName || "my-keryx-app";
|
|
53
60
|
options = {
|
|
54
61
|
includeDb: cmdOpts.db !== false,
|
|
62
|
+
includeRedis: cmdOpts.redis !== false,
|
|
55
63
|
includeExample: cmdOpts.example !== false,
|
|
56
64
|
force: cmdOpts.force === true,
|
|
57
65
|
};
|
package/util/connectionString.ts
CHANGED
|
@@ -1,7 +1,32 @@
|
|
|
1
1
|
import { ErrorType, TypedError } from "../classes/TypedError";
|
|
2
2
|
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* Whether a Redis connection string selects the in-process, in-memory Redis
|
|
5
|
+
* (`ioredis-mock`) instead of a real server. Any URL with the `memory:` scheme
|
|
6
|
+
* qualifies, e.g. `memory://`.
|
|
7
|
+
*
|
|
8
|
+
* @param connectionString - The configured `REDIS_URL`.
|
|
9
|
+
* @returns `true` for `memory:` URLs.
|
|
10
|
+
*/
|
|
11
|
+
export function isMemoryRedis(connectionString: string) {
|
|
12
|
+
return connectionString.trim().toLowerCase().startsWith("memory:");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Whether a database connection string turns the database off. An empty string
|
|
17
|
+
* or the literal `"none"` (case-insensitive) means "run without Postgres".
|
|
18
|
+
*
|
|
19
|
+
* @param connectionString - The configured `DATABASE_URL`.
|
|
20
|
+
* @returns `true` when no database should be connected.
|
|
21
|
+
*/
|
|
22
|
+
export function isDatabaseDisabled(connectionString: string) {
|
|
23
|
+
const value = connectionString.trim().toLowerCase();
|
|
24
|
+
return value === "" || value === "none";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Strip the password from a connection string for safe logging. Preserves protocol, user, host, port, and path. Unparseable strings are returned as `"(invalid connection string)"`. */
|
|
4
28
|
export function formatConnectionStringForLogging(connectionString: string) {
|
|
29
|
+
if (!URL.canParse(connectionString)) return "(invalid connection string)";
|
|
5
30
|
const connectionStringParsed = new URL(connectionString);
|
|
6
31
|
const connectionStringInfo = `${connectionStringParsed.protocol ? `${connectionStringParsed.protocol}//` : ""}${connectionStringParsed.username ? `${connectionStringParsed.username}@` : ""}${connectionStringParsed.hostname}:${connectionStringParsed.port}${connectionStringParsed.pathname}`;
|
|
7
32
|
return connectionStringInfo;
|
package/util/scaffold.ts
CHANGED
|
@@ -7,8 +7,17 @@ import pkg from "../package.json";
|
|
|
7
7
|
import { loadScaffoldTemplate as loadTemplate } from "./componentRegistry";
|
|
8
8
|
|
|
9
9
|
export interface ScaffoldOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Generate Postgres/Drizzle files and point `DATABASE_URL` at a local database. When
|
|
12
|
+
* false, `DATABASE_URL` is left empty so the app runs without a database.
|
|
13
|
+
*/
|
|
10
14
|
includeDb: boolean;
|
|
11
15
|
includeExample: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Point `REDIS_URL` at a local Redis server. When false, `REDIS_URL` is `memory://`,
|
|
18
|
+
* which runs an in-process Redis (single process, not persisted). Defaults to `true`.
|
|
19
|
+
*/
|
|
20
|
+
includeRedis?: boolean;
|
|
12
21
|
/**
|
|
13
22
|
* When true, scaffold into an existing directory instead of refusing.
|
|
14
23
|
* Files that already exist on disk are left untouched (merge-skip); only
|
|
@@ -46,10 +55,17 @@ export async function interactiveScaffold(
|
|
|
46
55
|
projectName = await prompt("Project name:", "my-keryx-app");
|
|
47
56
|
}
|
|
48
57
|
|
|
49
|
-
const includeDb = await promptYesNo(
|
|
58
|
+
const includeDb = await promptYesNo(
|
|
59
|
+
"Include database setup? (PostgreSQL — if no, the app runs without a database)",
|
|
60
|
+
true,
|
|
61
|
+
);
|
|
62
|
+
const includeRedis = await promptYesNo(
|
|
63
|
+
"Use a Redis server? (if no, an in-memory Redis is used: single process, not persisted)",
|
|
64
|
+
true,
|
|
65
|
+
);
|
|
50
66
|
const includeExample = await promptYesNo("Include example action?", true);
|
|
51
67
|
|
|
52
|
-
return { projectName, options: { includeDb, includeExample } };
|
|
68
|
+
return { projectName, options: { includeDb, includeRedis, includeExample } };
|
|
53
69
|
}
|
|
54
70
|
|
|
55
71
|
/**
|
|
@@ -280,7 +296,12 @@ export async function scaffoldProject(
|
|
|
280
296
|
|
|
281
297
|
fs.mkdirSync(targetDir, { recursive: true });
|
|
282
298
|
|
|
283
|
-
const view = {
|
|
299
|
+
const view = {
|
|
300
|
+
projectName,
|
|
301
|
+
keryxVersion,
|
|
302
|
+
includeDb: options.includeDb,
|
|
303
|
+
includeRedis: options.includeRedis !== false,
|
|
304
|
+
};
|
|
284
305
|
|
|
285
306
|
const write = async (filePath: string, content: string) => {
|
|
286
307
|
const fullPath = path.join(targetDir, filePath);
|
package/util/transaction.ts
CHANGED
|
@@ -28,6 +28,22 @@ export type Transaction = NodePgDatabase<Record<string, never>>;
|
|
|
28
28
|
*/
|
|
29
29
|
export type DbOrTransaction = NodePgDatabase<Record<string, never>>;
|
|
30
30
|
|
|
31
|
+
/**
|
|
32
|
+
* Throw a clear error when code that needs Postgres runs while the database is
|
|
33
|
+
* disabled (`DATABASE_URL` empty or `"none"`). Without this, callers would fail with
|
|
34
|
+
* an opaque `cannot read properties of undefined` on `api.db.pool` / `api.db.db`.
|
|
35
|
+
*
|
|
36
|
+
* @param feature - What needed the database, included in the error message.
|
|
37
|
+
* @throws {TypedError} With `ErrorType.SERVER_INITIALIZATION` when `api.db.enabled` is `false`.
|
|
38
|
+
*/
|
|
39
|
+
export function assertDatabaseEnabled(feature: string) {
|
|
40
|
+
if (api.db?.enabled) return;
|
|
41
|
+
throw new TypedError({
|
|
42
|
+
message: `${feature} requires a database, but the database is disabled (DATABASE_URL is empty or "none")`,
|
|
43
|
+
type: ErrorType.SERVER_INITIALIZATION,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
31
47
|
/**
|
|
32
48
|
* Run a callback inside a database transaction with automatic commit/rollback.
|
|
33
49
|
*
|
|
@@ -44,7 +60,8 @@ export type DbOrTransaction = NodePgDatabase<Record<string, never>>;
|
|
|
44
60
|
* All queries executed through `tx` participate in the same transaction.
|
|
45
61
|
* @returns The value returned by `fn`.
|
|
46
62
|
* @throws {TypedError} Re-throws `TypedError` directly. Wraps other errors in
|
|
47
|
-
* a `TypedError` with `ErrorType.CONNECTION_ACTION_RUN`.
|
|
63
|
+
* a `TypedError` with `ErrorType.CONNECTION_ACTION_RUN`. Throws
|
|
64
|
+
* `ErrorType.SERVER_INITIALIZATION` when the database is disabled.
|
|
48
65
|
*
|
|
49
66
|
* @example
|
|
50
67
|
* ```ts
|
|
@@ -58,6 +75,7 @@ export type DbOrTransaction = NodePgDatabase<Record<string, never>>;
|
|
|
58
75
|
export async function withTransaction<T>(
|
|
59
76
|
fn: (tx: Transaction) => Promise<T>,
|
|
60
77
|
): Promise<T> {
|
|
78
|
+
assertDatabaseEnabled("withTransaction");
|
|
61
79
|
const client = await api.db.pool.connect();
|
|
62
80
|
try {
|
|
63
81
|
await client.query("BEGIN");
|
package/util/zodMixins.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { type AnyColumn, eq, type Table } from "drizzle-orm";
|
|
|
2
2
|
import { z } from "zod/v4";
|
|
3
3
|
import { api } from "../api";
|
|
4
4
|
import { ErrorType, TypedError } from "../classes/TypedError";
|
|
5
|
+
import { assertDatabaseEnabled } from "./transaction";
|
|
5
6
|
|
|
6
7
|
// Zod v4: Extend GlobalMeta to support custom 'isSecret' metadata
|
|
7
8
|
// This allows using .meta({ isSecret: true }) on any zod schema
|
|
@@ -100,6 +101,7 @@ export function zIdOrModel<TModel>(
|
|
|
100
101
|
if (isModel(val)) {
|
|
101
102
|
return val;
|
|
102
103
|
}
|
|
104
|
+
assertDatabaseEnabled(`Loading ${entityName} by id`);
|
|
103
105
|
const [record] = await api.db.db
|
|
104
106
|
.select()
|
|
105
107
|
.from(table)
|