@meghjs/cli 0.5.0 → 0.5.1

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.
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readModelSchema = readModelSchema;
4
+ exports.renderResourceDto = renderResourceDto;
5
+ const orm_model_1 = require("./orm-model");
6
+ const stubs_1 = require("../utils/stubs");
7
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
8
+ /** The string value of `static readonly <name> = "..."`. */
9
+ function staticString(source, name) {
10
+ return source.match(new RegExp(`static\\s+(?:readonly\\s+)?${name}\\s*=\\s*["'\`]([^"'\`]+)["'\`]`))?.[1];
11
+ }
12
+ function staticTrue(source, name) {
13
+ return new RegExp(`static\\s+(?:readonly\\s+)?${name}\\s*=\\s*true\\b`).test(source);
14
+ }
15
+ /** `static generated = [...]` as a list, or `undefined` when not declared. */
16
+ function staticList(source, name) {
17
+ const m = source.match(new RegExp(`static\\s+(?:readonly\\s+)?${name}\\s*=\\s*\\[([^\\]]*)\\]`));
18
+ if (!m)
19
+ return undefined;
20
+ return (m[1].match(/["'`][^"'`]+["'`]/g) ?? []).map((s) => s.slice(1, -1));
21
+ }
22
+ /** Split leading decorators off a line: `@PrimaryKey() @AutoIncrement() id?: number;`. */
23
+ function leadingDecorators(line) {
24
+ const decorators = [];
25
+ let rest = line;
26
+ for (;;) {
27
+ const head = rest.match(/^@(\w+)\s*/);
28
+ if (!head)
29
+ break;
30
+ let end = head[0].length;
31
+ if (rest[end] === "(") {
32
+ // Up to the matching ")", or the end of the line for a decorator that
33
+ // continues on the next lines.
34
+ end = rest.length;
35
+ let depth = 0;
36
+ for (let i = head[0].length; i < rest.length; i++) {
37
+ const ch = rest[i];
38
+ if (ch === '"' || ch === "'" || ch === "`") {
39
+ const close = rest.indexOf(ch, i + 1);
40
+ i = close === -1 ? rest.length : close;
41
+ }
42
+ else if (ch === "(" || ch === "{" || ch === "[")
43
+ depth++;
44
+ else if (ch === ")" || ch === "}" || ch === "]") {
45
+ depth--;
46
+ if (depth === 0) {
47
+ end = i + 1;
48
+ break;
49
+ }
50
+ }
51
+ }
52
+ }
53
+ decorators.push(head[1] + rest.slice(head[0].length, end));
54
+ rest = rest.slice(end).trim();
55
+ }
56
+ return { decorators, rest };
57
+ }
58
+ /**
59
+ * Property declarations of the model class (`name!: string;`), with the
60
+ * decorators above each one. Initialised properties (relations such as
61
+ * `posts = hasMany(...)`), statics and methods are skipped.
62
+ */
63
+ function declaredProperties(source) {
64
+ const out = [];
65
+ let decorators = [];
66
+ // Bracket depth at the start of each line: properties sit directly in the
67
+ // class body (depth 1), not inside object literals or decorator arguments.
68
+ let depth = 0;
69
+ for (const raw of source.split(/\r?\n/)) {
70
+ const line = withoutLineComment(raw).trim();
71
+ const atDepth = depth;
72
+ depth += bracketDelta(line);
73
+ if (atDepth !== 1) {
74
+ // The rest of a multi-line decorator, e.g. `@Column({ nullable: true })`.
75
+ if (decorators.length > 0)
76
+ decorators[decorators.length - 1] += " " + line;
77
+ continue;
78
+ }
79
+ const split = leadingDecorators(line);
80
+ decorators.push(...split.decorators);
81
+ // A decorator on its own line, possibly continued on the next lines.
82
+ if (split.decorators.length > 0 && !split.rest)
83
+ continue;
84
+ const prop = split.rest.match(/^(?:(?:public|declare|readonly)\s+)*(\w+|"[^"]+"|'[^']+')\s*([!?])?\s*:\s*([^=;]+?)\s*;?$/);
85
+ if (prop && !/^(static|private|protected|get|set|async)\b/.test(split.rest)) {
86
+ const name = prop[1].replace(/^["']|["']$/g, "");
87
+ const parts = prop[3].split("|").map((p) => p.trim());
88
+ const nullInType = parts.includes("null") || parts.includes("undefined");
89
+ const optional = prop[2] === "?";
90
+ const ts = parts.filter((p) => p !== "null" && p !== "undefined").join(" | ") || "unknown";
91
+ out.push({ name, ts, nullable: optional || nullInType, optional, nullInType, decorators });
92
+ }
93
+ if (line && !line.startsWith("//") && !line.startsWith("*") && !line.startsWith("/*"))
94
+ decorators = [];
95
+ }
96
+ return out;
97
+ }
98
+ /** A line without its trailing `//` comment (a `//` inside a string is kept). */
99
+ function withoutLineComment(line) {
100
+ for (let i = 0; i < line.length; i++) {
101
+ const ch = line[i];
102
+ if (ch === '"' || ch === "'" || ch === "`") {
103
+ const end = line.indexOf(ch, i + 1);
104
+ if (end === -1)
105
+ return line;
106
+ i = end;
107
+ }
108
+ else if (ch === "/" && line[i + 1] === "/")
109
+ return line.slice(0, i);
110
+ }
111
+ return line;
112
+ }
113
+ /** Opening minus closing brackets on a line (already without its comment), ignoring strings. */
114
+ function bracketDelta(line) {
115
+ let delta = 0;
116
+ for (let i = 0; i < line.length; i++) {
117
+ const ch = line[i];
118
+ if (ch === '"' || ch === "'" || ch === "`") {
119
+ const end = line.indexOf(ch, i + 1);
120
+ if (end === -1)
121
+ break;
122
+ i = end;
123
+ }
124
+ else if (ch === "{" || ch === "(" || ch === "[")
125
+ delta++;
126
+ else if (ch === "}" || ch === ")" || ch === "]")
127
+ delta--;
128
+ }
129
+ return delta;
130
+ }
131
+ /** Read a model (Megh ORM or TypeORM) for resource generation. */
132
+ function readModelSchema(source, table) {
133
+ const byName = new Map((table?.columns ?? []).map((c) => [c.name, c]));
134
+ const withSql = (f) => {
135
+ const column = byName.get(f.name);
136
+ return column?.type ? { ...f, sqlType: column.type } : f;
137
+ };
138
+ if (/@Entity\s*\(/.test(source)) {
139
+ const props = declaredProperties(source);
140
+ const skip = /^(PrimaryGeneratedColumn|CreateDateColumn|UpdateDateColumn|DeleteDateColumn|VersionColumn|OneToMany|ManyToOne|OneToOne|ManyToMany|JoinColumn|JoinTable|RelationId)\b/;
141
+ const pk = props.find((p) => p.decorators.some((d) => /^Primary(Generated)?Column\b/.test(d)));
142
+ const columns = props.filter((p) => p.decorators.some((d) => /^(Primary)?Column\b/.test(d)));
143
+ return {
144
+ kind: "typeorm",
145
+ table: source.match(/@Entity\s*\(\s*(?:\{[^}]*name\s*:\s*)?["'`]([^"'`]+)/)?.[1],
146
+ primaryKey: pk?.name ?? "id",
147
+ primaryKeyType: pk?.ts ?? "number",
148
+ inputFields: columns
149
+ .filter((p) => !p.decorators.some((d) => skip.test(d)))
150
+ .map((p) => withSql({
151
+ name: p.name,
152
+ ts: p.ts,
153
+ nullable: p.nullable || p.decorators.some((d) => /nullable\s*:\s*true/.test(d)),
154
+ generated: p.decorators.some((d) => /default\s*:/.test(d)),
155
+ })),
156
+ };
157
+ }
158
+ if (/@Table\s*\(/.test(source))
159
+ return readDecoratedModel(source, withSql);
160
+ const primaryKey = staticString(source, "primaryKey") ?? "id";
161
+ const generated = new Set(staticList(source, "generated") ?? ["id"]);
162
+ const implicit = new Set();
163
+ if (staticTrue(source, "timestamps")) {
164
+ implicit.add(staticString(source, "createdAt") ?? "created_at");
165
+ implicit.add(staticString(source, "updatedAt") ?? "updated_at");
166
+ }
167
+ if (staticTrue(source, "softDeletes"))
168
+ implicit.add(staticString(source, "deletedAt") ?? "deleted_at");
169
+ const props = declaredProperties(source);
170
+ const pk = props.find((p) => p.name === primaryKey);
171
+ return {
172
+ kind: "megh",
173
+ table: staticString(source, "table"),
174
+ primaryKey,
175
+ primaryKeyType: pk?.ts ?? "number",
176
+ inputFields: props
177
+ // An auto-generated key and the timestamps are never sent by clients.
178
+ .filter((p) => !implicit.has(p.name) && !(p.name === primaryKey && generated.has(p.name)))
179
+ .map((p) => withSql({ name: p.name, ts: p.ts, nullable: p.nullable, generated: generated.has(p.name) })),
180
+ };
181
+ }
182
+ /**
183
+ * A model described with decorators. Only decorated columns count; fields
184
+ * declared with `?` (auto-increment, defaults) are filled in by the database.
185
+ */
186
+ function readDecoratedModel(source, withSql) {
187
+ const has = (p, name) => p.decorators.some((d) => name.test(d));
188
+ const columns = declaredProperties(source).filter((p) => has(p, /^(Column|PrimaryKey|AutoIncrement|Identity|CreatedAt|UpdatedAt|DeletedAt)\b/));
189
+ const pk = columns.find((p) => has(p, /^PrimaryKey\b/));
190
+ const primaryKey = pk?.name ?? "id";
191
+ const generated = (p) => p.optional || has(p, /^(AutoIncrement|Identity)\b/);
192
+ return {
193
+ kind: "megh",
194
+ table: source.match(/@Table\s*\(\s*["'`]([^"'`]+)["'`]/)?.[1],
195
+ primaryKey,
196
+ primaryKeyType: pk?.ts ?? "number",
197
+ inputFields: columns
198
+ // The timestamps and an auto-generated key are never sent by clients.
199
+ .filter((p) => !has(p, /^(CreatedAt|UpdatedAt|DeletedAt)\b/))
200
+ .filter((p) => !(p.name === primaryKey && generated(p)))
201
+ .map((p) => withSql({ name: p.name, ts: p.ts, nullable: p.nullInType, generated: generated(p) })),
202
+ };
203
+ }
204
+ const INTEGER = /^(int\d?|integer|smallint|mediumint|tinyint|bigint|serial\d?|smallserial|bigserial)$/;
205
+ /** class-validator decorators (and the type to declare) for one DTO field. */
206
+ function validators(field) {
207
+ const sql = field.sqlType ?? "";
208
+ const base = sql.replace(/\(.*$/, "").trim();
209
+ const ts = field.sqlType && field.ts === "unknown" ? (0, orm_model_1.fieldType)(sql).ts : field.ts;
210
+ const d = [];
211
+ switch (ts) {
212
+ case "string": {
213
+ if (/(^|_)email$/i.test(field.name))
214
+ d.push("IsEmail()");
215
+ else if (base === "uuid")
216
+ d.push("IsUUID()");
217
+ else
218
+ d.push("IsString()");
219
+ const length = sql.match(/^(?:n?varchar|n?char|character varying|character)\s*\((\d+)\)/)?.[1];
220
+ if (length)
221
+ d.push(`MaxLength(${length})`);
222
+ break;
223
+ }
224
+ case "number":
225
+ d.push(INTEGER.test(base) ? "IsInt()" : "IsNumber()");
226
+ break;
227
+ case "boolean":
228
+ d.push("IsBoolean()");
229
+ break;
230
+ case "Date":
231
+ d.push("Type(() => Date)", "IsDate()");
232
+ break;
233
+ default:
234
+ if (/^Record<|^\{/.test(ts))
235
+ d.push("IsObject()");
236
+ // Anything else (Buffer, unknown, unions) is accepted as sent.
237
+ else
238
+ d.push("Allow()");
239
+ }
240
+ return { decorators: d, ts };
241
+ }
242
+ const key = (name) => (IDENTIFIER.test(name) ? name : JSON.stringify(name));
243
+ function renderFields(fields, allOptional) {
244
+ return fields
245
+ .map((f) => {
246
+ const { decorators, ts } = validators(f);
247
+ const optional = allOptional || f.nullable || f.generated;
248
+ const lines = [...(optional ? ["@IsOptional()"] : []), ...decorators.map((x) => `@${x}`)];
249
+ const type = f.nullable ? `${ts} | null` : ts;
250
+ lines.push(`${key(f.name)}${optional ? "?" : "!"}: ${type};`);
251
+ return lines.map((l) => ` ${l}`).join("\n");
252
+ })
253
+ .join("\n\n");
254
+ }
255
+ /** `src/dtos/<model>.dto.ts`: create, update and list-query DTOs. */
256
+ function renderResourceDto(model, plural, route, schema) {
257
+ const create = renderFields(schema.inputFields, false);
258
+ const update = renderFields(schema.inputFields, true);
259
+ // The list query always uses these.
260
+ const used = new Set(["IsInt", "IsOptional", "Max", "Min"]);
261
+ for (const f of schema.inputFields) {
262
+ for (const d of validators(f).decorators) {
263
+ const name = d.match(/^\w+/)[0];
264
+ if (name !== "Type")
265
+ used.add(name);
266
+ }
267
+ }
268
+ const empty = " // No writable columns were found on the model.";
269
+ return (0, stubs_1.renderStub)("dtos/resource-dto.stub", {
270
+ validators: [...used].sort().join(", "),
271
+ Model: model,
272
+ Plural: plural,
273
+ route,
274
+ createFields: create || empty,
275
+ updateFields: update || empty,
276
+ });
277
+ }
package/dist/program.js CHANGED
@@ -68,6 +68,7 @@ function createProgram(run = {}) {
68
68
  .option("-y, --yes", "Skip prompts and use defaults (npm, openapi)")
69
69
  .option("--pm <manager>", `Package manager: ${new_1.PACKAGE_MANAGERS.join(", ")}`)
70
70
  .option("--features <list>", `Comma-separated features: ${new_1.FEATURES.join(", ")}`, parseList)
71
+ .option("--database <name>", `Set up MeghORM (the orm feature) for ${new_1.DATABASES.join(", ")}. Defaults to sqlite with orm`)
71
72
  .option("--skip-install", "Do not install dependencies (or set MEGH_SKIP_INSTALL=1)")
72
73
  .action(async (name, o) => {
73
74
  await (0, new_1.createApplication)(name, { cwd: cwd(), ...o });
@@ -105,9 +106,10 @@ function createProgram(run = {}) {
105
106
  (0, route_list_1.routeList)({ cwd: cwd(), json: o.json, static: o.static });
106
107
  });
107
108
  // ── Database ────────────────────────────────────────────────────────────
108
- const db = (name, description) => sub(name, description).addHelpText("after", "\nThe Kysely instance is the default (or `db`) export of src/database/connection.ts and\n" +
109
- "migrations live in src/database/migrations; set megh.database / megh.migrations in\n" +
110
- "package.json to change them. Sources are compiled with SWC first, and .env is loaded.");
109
+ const db = (name, description) => sub(name, description).addHelpText("after", "\nConnects the way app.useMeghORM() does: from DATABASE_URL (or DB_DIALECT, DB_HOST,\n" +
110
+ "DB_NAME, ...) in the environment or .env, with optional settings in megh.database in\n" +
111
+ "package.json. Migrations live in src/database/migrations; set megh.migrations to\n" +
112
+ "change it. Sources are compiled with SWC first.");
111
113
  db("migrate", "Run pending migrations").action(() => {
112
114
  (0, migrate_1.migrate)({ cwd: cwd() });
113
115
  });
@@ -141,15 +143,26 @@ function createProgram(run = {}) {
141
143
  .aliases(aliases)
142
144
  .argument("<name>", "Name, optionally nested (e.g. admin/User)")
143
145
  .option("-f, --force", "Overwrite the file if it exists");
144
- make("make:model", ["m:m"], "Create a model in src/models/<name>.model.ts")
146
+ make("make:model", ["m:m"], "Create a model in src/models/<name>.model.ts, with columns read from its migrations")
147
+ .option("-t, --table <table>", "Table name (default: plural snake_case name, e.g. blog_posts)")
145
148
  .option("--orm", "Generate a TypeORM entity")
146
149
  .option("--root <dir>", "Folder under src/ to write to (also -rt)")
147
150
  .action((name, o) => {
148
151
  (0, make_1.makeModel)(name, { cwd: cwd(), ...o });
149
152
  });
153
+ make("make:resource", ["m:r", "m:res"], "Create a REST resource for a model: its DTOs, a CRUD service and a controller")
154
+ .option("-t, --table <table>", "Table to read the columns from when the model is missing (default: plural snake_case name)")
155
+ .addHelpText("after", "\nThe model in src/models/<name>.model.ts is reused if it exists; otherwise it is\n" +
156
+ "generated from the migration that creates its table (and the command fails if\n" +
157
+ "there is none). Then src/dtos/<name>.dto.ts, src/services/<name>.service.ts and\n" +
158
+ "src/controllers/<name>.controller.ts are written, e.g. for `make:resource user`:\n" +
159
+ " GET /users?page=&perPage= POST /users GET|PUT|DELETE /users/:id")
160
+ .action((name, o) => {
161
+ (0, make_1.makeResource)(name, { cwd: cwd(), force: o.force, table: o.table });
162
+ });
150
163
  make("make:controller", ["m:c"], "Create a controller in src/controllers/<name>.controller.ts")
151
164
  .option("-r, --resource", "Generate a REST skeleton (also --rest)")
152
- .option("-m, --model <model>", "Back a REST controller with <model>: also creates its service and model if missing")
165
+ .option("-m, --model <model>", "Back a REST controller with <model>: also creates its DTOs, service and model (from its migration) if missing")
153
166
  .option("--orm", "With -m, back the service with a TypeORM repository and entity")
154
167
  .option("--root <dir>", "Folder under src/ to write to (also -rt)")
155
168
  .option("--base-path", "Use @ApiController without a path prefix")
@@ -158,7 +171,7 @@ function createProgram(run = {}) {
158
171
  });
159
172
  make("make:service", ["m:s"], "Create a service in src/services/<name>.service.ts")
160
173
  .option("-r, --resource", "Generate a resource (CRUD) service; requires -m (also --rest)")
161
- .option("-m, --model <model>", "Model for a resource service; creates the model if missing")
174
+ .option("-m, --model <model>", "Model for a resource service; creates the model from its migration if missing")
162
175
  .option("--orm", "Back the resource service with a TypeORM repository and entity")
163
176
  .option("--root <dir>", "Folder under src/ to write to (also -rt)")
164
177
  .action((name, o) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meghjs/cli",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "CLI for scaffolding and running Megh applications",
5
5
  "author": "Tareq Hossain",
6
6
  "license": "MIT",
@@ -16,7 +16,7 @@
16
16
  "LICENSE"
17
17
  ],
18
18
  "engines": {
19
- "node": ">=20"
19
+ "node": ">=22"
20
20
  },
21
21
  "scripts": {
22
22
  "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
@@ -39,12 +39,12 @@
39
39
  "inquirer": "^12.6.0"
40
40
  },
41
41
  "devDependencies": {
42
- "@types/node": "^22.9.3",
42
+ "@types/node": "^22.20.5",
43
43
  "typescript": "^5.7.2",
44
44
  "vitest": "^4.1.12"
45
45
  },
46
46
  "peerDependencies": {
47
- "@meghjs/core": "^0.5.0"
47
+ "@meghjs/core": "^0.5.1"
48
48
  },
49
49
  "peerDependenciesMeta": {
50
50
  "@meghjs/core": {
@@ -59,5 +59,5 @@
59
59
  "publishConfig": {
60
60
  "access": "public"
61
61
  },
62
- "gitHead": "b7dce1958b00ef1921c09461591e6379ea71e5a2"
62
+ "gitHead": "77cdb018997e7907d58d4877aa855e5e3bd2be3c"
63
63
  }
@@ -0,0 +1,34 @@
1
+ import { ApiController, Body, Delete, Get, Param, Post, Put, Query } from '@meghjs/core';
2
+ import { Create{Model}Dto, List{Plural}Query, Update{Model}Dto } from '{dtoImport}';
3
+ import { {ServiceClass} } from '{serviceImport}';
4
+
5
+ @ApiController('/{route}')
6
+ export class {ClassName} {
7
+ constructor(private readonly {serviceVar}: {ServiceClass}) {}
8
+
9
+ @Get()
10
+ index(@Query() query: List{Plural}Query) {
11
+ return this.{serviceVar}.paginate(query);
12
+ }
13
+
14
+ @Get('/:id')
15
+ show(@Param('id') id: {primaryKeyType}) {
16
+ return this.{serviceVar}.findOrFail({idArg});
17
+ }
18
+
19
+ @Post()
20
+ create(@Body() body: Create{Model}Dto) {
21
+ return this.{serviceVar}.create(body);
22
+ }
23
+
24
+ @Put('/:id')
25
+ update(@Param('id') id: {primaryKeyType}, @Body() body: Update{Model}Dto) {
26
+ return this.{serviceVar}.update({idArg}, body);
27
+ }
28
+
29
+ @Delete('/:id')
30
+ async delete(@Param('id') id: {primaryKeyType}) {
31
+ await this.{serviceVar}.delete({idArg});
32
+ return { message: '{Model} deleted.' };
33
+ }
34
+ }
@@ -0,0 +1,28 @@
1
+ import { Type } from 'class-transformer';
2
+ import { {validators} } from 'class-validator';
3
+
4
+ /** `POST /{route}` body. Columns the database fills in are optional. */
5
+ export class Create{Model}Dto {
6
+ {createFields}
7
+ }
8
+
9
+ /** `PUT /{route}/:id` body: only the columns sent are changed. */
10
+ export class Update{Model}Dto {
11
+ {updateFields}
12
+ }
13
+
14
+ /** `GET /{route}?page=1&perPage=10` */
15
+ export class List{Plural}Query {
16
+ @IsOptional()
17
+ @Type(() => Number)
18
+ @IsInt()
19
+ @Min(1)
20
+ page?: number;
21
+
22
+ @IsOptional()
23
+ @Type(() => Number)
24
+ @IsInt()
25
+ @Min(1)
26
+ @Max(100)
27
+ perPage?: number;
28
+ }
@@ -1,9 +1,15 @@
1
- import type { Kysely } from "kysely";
1
+ import { defineMigration } from "@meghjs/core";
2
2
 
3
- export async function up(db: Kysely<any>): Promise<void> {
4
- // await db.schema.alterTable("{table}").addColumn("column", "text").execute();
5
- }
3
+ export default defineMigration({
4
+ async up(schema) {
5
+ await schema.table("{table}", (table) => {
6
+ // table.string("column").nullable();
7
+ });
8
+ },
6
9
 
7
- export async function down(db: Kysely<any>): Promise<void> {
8
- // await db.schema.alterTable("{table}").dropColumn("column").execute();
9
- }
10
+ async down(schema) {
11
+ await schema.table("{table}", (table) => {
12
+ // table.dropColumn("column");
13
+ });
14
+ },
15
+ });
@@ -1,15 +1,15 @@
1
- import type { Kysely } from "kysely";
1
+ import { defineMigration } from "@meghjs/core";
2
2
 
3
- export async function up(db: Kysely<any>): Promise<void> {
4
- await db.schema
5
- .createTable("{table}")
6
- {idColumn}
7
- // .addColumn("name", "text", (col) => col.notNull())
8
- .addColumn("created_at", "timestamp")
9
- .addColumn("updated_at", "timestamp")
10
- .execute();
11
- }
3
+ export default defineMigration({
4
+ async up(schema) {
5
+ await schema.create("{table}", (table) => {
6
+ table.id();
7
+ // table.string("name");
8
+ table.timestamps();
9
+ });
10
+ },
12
11
 
13
- export async function down(db: Kysely<any>): Promise<void> {
14
- await db.schema.dropTable("{table}").execute();
15
- }
12
+ async down(schema) {
13
+ await schema.drop("{table}");
14
+ },
15
+ });
@@ -1,9 +1,11 @@
1
- import type { Kysely } from "kysely";
1
+ import { defineMigration } from "@meghjs/core";
2
2
 
3
- export async function up(db: Kysely<any>): Promise<void> {
4
- // Schema changes: https://kysely.dev/docs/migrations
5
- }
3
+ export default defineMigration({
4
+ async up(schema) {
5
+ // await schema.create(...), schema.table(...), schema.drop(...) or schema.raw(...)
6
+ },
6
7
 
7
- export async function down(db: Kysely<any>): Promise<void> {
8
- // Undo the changes made in up().
9
- }
8
+ async down(schema) {
9
+ // Undo the changes made in up().
10
+ },
11
+ });
@@ -0,0 +1,10 @@
1
+ import { AutoIncrement, Column, Model, PrimaryKey, Table } from "@meghjs/core";
2
+
3
+ @Table({table})
4
+ export class {Model} extends Model {
5
+ @PrimaryKey() @AutoIncrement() id?: number;
6
+
7
+ // One decorated field per column, e.g.:
8
+ // @Column() email!: string;
9
+ // @Column({ nullable: true }) name!: string | null;
10
+ }
@@ -0,0 +1,7 @@
1
+ import { {imports} } from "@meghjs/core";
2
+
3
+ // Columns read from the migrations (the table is created in {source}).
4
+ @Table({table})
5
+ export class {Model} extends Model {
6
+ {fields}
7
+ }
@@ -0,0 +1,42 @@
1
+ import { AppService, type CreateInput, type PageRequest, type UpdateInput } from '@meghjs/core';
2
+ import { {Model} } from '{modelImport}';
3
+
4
+ @AppService
5
+ export class {ClassName} {
6
+ /** Every {modelVar}, ordered by {primaryKey}. */
7
+ findAll() {
8
+ return {Model}.query().orderBy('{primaryKey}').get();
9
+ }
10
+
11
+ /** One page of {modelVar} rows: `{ data, meta }`. */
12
+ paginate(request: PageRequest = {}) {
13
+ return {Model}.query().orderBy('{primaryKey}').paginate(request);
14
+ }
15
+
16
+ /** The {modelVar} with this {primaryKey}, or `undefined`. */
17
+ find(id: {primaryKeyType}) {
18
+ return {Model}.find(id);
19
+ }
20
+
21
+ /** The {modelVar} with this {primaryKey}; throws a 404 when there is none. */
22
+ findOrFail(id: {primaryKeyType}) {
23
+ return {Model}.findOrFail(id);
24
+ }
25
+
26
+ create(input: CreateInput<typeof {Model}>) {
27
+ return {Model}.create(input);
28
+ }
29
+
30
+ /** `save()` writes only the columns that changed. */
31
+ async update(id: {primaryKeyType}, changes: UpdateInput<{Model}>) {
32
+ const {modelVar} = await {Model}.findOrFail(id);
33
+ // A DTO instance holds `undefined` for every field that was not sent.
34
+ const sent = Object.fromEntries(Object.entries(changes).filter(([, value]) => value !== undefined));
35
+ return {modelVar}.fill(sent).save();
36
+ }
37
+
38
+ async delete(id: {primaryKeyType}) {
39
+ const {modelVar} = await {Model}.findOrFail(id);
40
+ await {modelVar}.delete();
41
+ }
42
+ }
@@ -1,4 +0,0 @@
1
- export class {Model} {
2
- id!: number;
3
- name!: string;
4
- }
@@ -1,34 +0,0 @@
1
- import { AppService, Collection } from '@meghjs/core';
2
- import { {Model} } from '{modelImport}';
3
-
4
- @AppService
5
- export class {ClassName} {
6
- private readonly {modelVar}Collection = Collection.from<{Model}>([]);
7
-
8
- async findAll() {
9
- return this.{modelVar}Collection.find();
10
- }
11
-
12
- async paginate(page = 1, take = 10) {
13
- const skip = page > 1 ? (page - 1) * take : 0;
14
- return this.{modelVar}Collection.paginate({ take, skip });
15
- }
16
-
17
- async findByPk(id: number) {
18
- return this.{modelVar}Collection.findOne((item) => item.id === id);
19
- }
20
-
21
- async create(createBody: Partial<{Model}>) {
22
- return this.{modelVar}Collection.add(createBody);
23
- }
24
-
25
- async update(id: number, updateBody: Partial<{Model}>) {
26
- this.{modelVar}Collection.update((item) => item.id === id, updateBody);
27
- return true;
28
- }
29
-
30
- async delete(id: number) {
31
- this.{modelVar}Collection.delete((item) => item.id === id);
32
- return true;
33
- }
34
- }