@meghjs/cli 0.5.2 → 0.5.4
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/dist/commands/migrate.d.ts +23 -5
- package/dist/commands/migrate.js +44 -6
- package/dist/commands/new.js +7 -1
- package/dist/generators/auth-files.d.ts +37 -0
- package/dist/generators/auth-files.js +198 -0
- package/dist/generators/auth.d.ts +26 -0
- package/dist/generators/auth.js +542 -0
- package/dist/generators/factory.d.ts +25 -0
- package/dist/generators/factory.js +159 -0
- package/dist/generators/make.d.ts +38 -0
- package/dist/generators/make.js +176 -0
- package/dist/generators/migration-schema.d.ts +5 -0
- package/dist/generators/migration-schema.js +25 -2
- package/dist/generators/orm-model.d.ts +6 -1
- package/dist/generators/orm-model.js +31 -2
- package/dist/generators/resource.d.ts +21 -0
- package/dist/generators/resource.js +17 -3
- package/dist/generators/scaffold.d.ts +76 -0
- package/dist/generators/scaffold.js +353 -0
- package/dist/generators/update-model.d.ts +21 -0
- package/dist/generators/update-model.js +129 -0
- package/dist/program.js +175 -6
- package/dist/templates/cascade.d.ts +37 -0
- package/dist/templates/cascade.js +87 -0
- package/dist/templates/catalog/common.d.ts +1 -0
- package/dist/templates/catalog/common.js +63 -0
- package/dist/templates/catalog/construction.d.ts +1 -0
- package/dist/templates/catalog/construction.js +138 -0
- package/dist/templates/catalog/crm.d.ts +1 -0
- package/dist/templates/catalog/crm.js +81 -0
- package/dist/templates/catalog/ecommerce.d.ts +1 -0
- package/dist/templates/catalog/ecommerce.js +143 -0
- package/dist/templates/catalog/education.d.ts +1 -0
- package/dist/templates/catalog/education.js +80 -0
- package/dist/templates/catalog/hr.d.ts +1 -0
- package/dist/templates/catalog/hr.js +83 -0
- package/dist/templates/catalog/logistics.d.ts +1 -0
- package/dist/templates/catalog/logistics.js +60 -0
- package/dist/templates/catalog/marketing.d.ts +1 -0
- package/dist/templates/catalog/marketing.js +104 -0
- package/dist/templates/catalog/medical.d.ts +1 -0
- package/dist/templates/catalog/medical.js +147 -0
- package/dist/templates/catalog/pos.d.ts +1 -0
- package/dist/templates/catalog/pos.js +110 -0
- package/dist/templates/catalog/real-estate.d.ts +1 -0
- package/dist/templates/catalog/real-estate.js +171 -0
- package/dist/templates/fields.d.ts +64 -0
- package/dist/templates/fields.js +331 -0
- package/dist/templates/index.d.ts +27 -0
- package/dist/templates/index.js +175 -0
- package/dist/templates/migration.d.ts +7 -0
- package/dist/templates/migration.js +80 -0
- package/dist/templates/template.d.ts +37 -0
- package/dist/templates/template.js +36 -0
- package/dist/utils/dialect.d.ts +8 -0
- package/dist/utils/dialect.js +57 -0
- package/package.json +17 -5
- package/readme.md +30 -1
- package/stubs/controllers/model-controller.stub +10 -1
- package/stubs/seeders/database-seeder.stub +8 -0
- package/stubs/seeders/seeder.stub +10 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type Domain, type ModelTemplate } from "./template";
|
|
2
|
+
export type { Domain, ModelTemplate } from "./template";
|
|
3
|
+
export { dependencies } from "./template";
|
|
4
|
+
/** The built-in domains, in the order they are listed. */
|
|
5
|
+
export declare const BUILTIN_DOMAINS: readonly Domain[];
|
|
6
|
+
/** Where a project keeps its own templates, one JSON file per domain. */
|
|
7
|
+
export declare const PROJECT_TEMPLATES_DIR: string;
|
|
8
|
+
/** Domains from `.megh/templates/*.json` in the project. */
|
|
9
|
+
export declare function readProjectDomains(projectRoot: string): Domain[];
|
|
10
|
+
/** Built-in domains merged with the project's: a project template replaces a built-in one of the same name. */
|
|
11
|
+
export declare function allDomains(projectRoot?: string): Domain[];
|
|
12
|
+
export declare function findDomain(domains: Domain[], name: string): Domain;
|
|
13
|
+
/**
|
|
14
|
+
* The template for `ecommerce/product`, or for a bare `product` when only
|
|
15
|
+
* one domain has it (a common template wins over the others).
|
|
16
|
+
*/
|
|
17
|
+
export declare function findTemplate(domains: Domain[], ref: string): ModelTemplate;
|
|
18
|
+
/** The template that creates `table`: from `domain` first, then common, then any other domain. */
|
|
19
|
+
export declare function templateForTable(domains: Domain[], table: string, domain?: string): ModelTemplate | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* Order `templates` so each comes after the tables its foreign keys point
|
|
22
|
+
* to (when those are in the list too). Throws on a cycle.
|
|
23
|
+
*/
|
|
24
|
+
export declare function orderByDependencies<T extends {
|
|
25
|
+
template: ModelTemplate;
|
|
26
|
+
table: string;
|
|
27
|
+
}>(items: T[]): T[];
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.PROJECT_TEMPLATES_DIR = exports.BUILTIN_DOMAINS = exports.dependencies = void 0;
|
|
7
|
+
exports.readProjectDomains = readProjectDomains;
|
|
8
|
+
exports.allDomains = allDomains;
|
|
9
|
+
exports.findDomain = findDomain;
|
|
10
|
+
exports.findTemplate = findTemplate;
|
|
11
|
+
exports.templateForTable = templateForTable;
|
|
12
|
+
exports.orderByDependencies = orderByDependencies;
|
|
13
|
+
const fs_1 = __importDefault(require("fs"));
|
|
14
|
+
const path_1 = __importDefault(require("path"));
|
|
15
|
+
const errors_1 = require("../errors");
|
|
16
|
+
const common_1 = require("./catalog/common");
|
|
17
|
+
const construction_1 = require("./catalog/construction");
|
|
18
|
+
const crm_1 = require("./catalog/crm");
|
|
19
|
+
const ecommerce_1 = require("./catalog/ecommerce");
|
|
20
|
+
const education_1 = require("./catalog/education");
|
|
21
|
+
const hr_1 = require("./catalog/hr");
|
|
22
|
+
const logistics_1 = require("./catalog/logistics");
|
|
23
|
+
const marketing_1 = require("./catalog/marketing");
|
|
24
|
+
const medical_1 = require("./catalog/medical");
|
|
25
|
+
const pos_1 = require("./catalog/pos");
|
|
26
|
+
const real_estate_1 = require("./catalog/real-estate");
|
|
27
|
+
const template_1 = require("./template");
|
|
28
|
+
var template_2 = require("./template");
|
|
29
|
+
Object.defineProperty(exports, "dependencies", { enumerable: true, get: function () { return template_2.dependencies; } });
|
|
30
|
+
/** The built-in domains, in the order they are listed. */
|
|
31
|
+
exports.BUILTIN_DOMAINS = [
|
|
32
|
+
common_1.common,
|
|
33
|
+
ecommerce_1.ecommerce,
|
|
34
|
+
pos_1.pos,
|
|
35
|
+
medical_1.medical,
|
|
36
|
+
construction_1.construction,
|
|
37
|
+
marketing_1.marketing,
|
|
38
|
+
real_estate_1.realEstate,
|
|
39
|
+
hr_1.hr,
|
|
40
|
+
crm_1.crm,
|
|
41
|
+
education_1.education,
|
|
42
|
+
logistics_1.logistics,
|
|
43
|
+
];
|
|
44
|
+
/** Where a project keeps its own templates, one JSON file per domain. */
|
|
45
|
+
exports.PROJECT_TEMPLATES_DIR = path_1.default.join(".megh", "templates");
|
|
46
|
+
/** Domains from `.megh/templates/*.json` in the project. */
|
|
47
|
+
function readProjectDomains(projectRoot) {
|
|
48
|
+
const dir = path_1.default.join(projectRoot, exports.PROJECT_TEMPLATES_DIR);
|
|
49
|
+
if (!fs_1.default.existsSync(dir))
|
|
50
|
+
return [];
|
|
51
|
+
return fs_1.default
|
|
52
|
+
.readdirSync(dir)
|
|
53
|
+
.filter((f) => f.endsWith(".json"))
|
|
54
|
+
.sort()
|
|
55
|
+
.map((file) => {
|
|
56
|
+
const rel = path_1.default.join(exports.PROJECT_TEMPLATES_DIR, file).split(path_1.default.sep).join("/");
|
|
57
|
+
let data;
|
|
58
|
+
try {
|
|
59
|
+
data = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, file), "utf8"));
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
throw new errors_1.CliError(`${rel} is not valid JSON: ${err.message}`);
|
|
63
|
+
}
|
|
64
|
+
const name = data.domain ?? file.replace(/\.json$/, "");
|
|
65
|
+
if (!Array.isArray(data.templates)) {
|
|
66
|
+
throw new errors_1.CliError(`${rel} needs a "templates" array: [{ "name": "ticket", "fields": ["title", "status:in(open|closed)"] }]`);
|
|
67
|
+
}
|
|
68
|
+
const templates = data.templates.map((t, i) => {
|
|
69
|
+
if (!t || typeof t.name !== "string" || !Array.isArray(t.fields)) {
|
|
70
|
+
throw new errors_1.CliError(`${rel}: templates[${i}] needs a "name" and a "fields" array.`);
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
return (0, template_1.template)(name, t.name, t.description ?? "", t.fields, t);
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
throw new errors_1.CliError(`${rel} (${t.name}): ${err.message}`);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
return { name, title: data.title ?? name, description: data.description ?? "", templates };
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
/** Built-in domains merged with the project's: a project template replaces a built-in one of the same name. */
|
|
83
|
+
function allDomains(projectRoot) {
|
|
84
|
+
const domains = exports.BUILTIN_DOMAINS.map((d) => ({ ...d, templates: [...d.templates] }));
|
|
85
|
+
for (const own of projectRoot ? readProjectDomains(projectRoot) : []) {
|
|
86
|
+
const existing = domains.find((d) => d.name === own.name);
|
|
87
|
+
if (!existing) {
|
|
88
|
+
domains.push(own);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
for (const t of own.templates) {
|
|
92
|
+
const i = existing.templates.findIndex((x) => x.name === t.name);
|
|
93
|
+
if (i === -1)
|
|
94
|
+
existing.templates.push(t);
|
|
95
|
+
else
|
|
96
|
+
existing.templates[i] = t;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return domains;
|
|
100
|
+
}
|
|
101
|
+
function findDomain(domains, name) {
|
|
102
|
+
const domain = domains.find((d) => d.name === name);
|
|
103
|
+
if (!domain) {
|
|
104
|
+
throw new errors_1.CliError(`Unknown domain "${name}". Choose from: ${domains.map((d) => d.name).join(", ")}.`);
|
|
105
|
+
}
|
|
106
|
+
return domain;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The template for `ecommerce/product`, or for a bare `product` when only
|
|
110
|
+
* one domain has it (a common template wins over the others).
|
|
111
|
+
*/
|
|
112
|
+
function findTemplate(domains, ref) {
|
|
113
|
+
const [domainName, name] = ref.includes("/") ? ref.split("/", 2) : [undefined, ref];
|
|
114
|
+
const key = name.replace(/-/g, "_");
|
|
115
|
+
if (domainName) {
|
|
116
|
+
const domain = findDomain(domains, domainName);
|
|
117
|
+
const found = domain.templates.find((t) => t.name === key);
|
|
118
|
+
if (!found) {
|
|
119
|
+
throw new errors_1.CliError(`The ${domain.name} domain has no "${name}" template. It has: ${domain.templates.map((t) => t.name).join(", ")}.`);
|
|
120
|
+
}
|
|
121
|
+
return found;
|
|
122
|
+
}
|
|
123
|
+
const matches = domains.flatMap((d) => d.templates.filter((t) => t.name === key));
|
|
124
|
+
if (matches.length === 0) {
|
|
125
|
+
throw new errors_1.CliError(`No template is named "${name}". List them with: megh template:list`);
|
|
126
|
+
}
|
|
127
|
+
if (matches.length > 1) {
|
|
128
|
+
const commonMatch = matches.find((t) => t.domain === "common");
|
|
129
|
+
if (commonMatch)
|
|
130
|
+
return commonMatch;
|
|
131
|
+
throw new errors_1.CliError(`"${name}" is in several domains: ${matches.map((t) => `${t.domain}/${t.name}`).join(", ")}. Pick one.`);
|
|
132
|
+
}
|
|
133
|
+
return matches[0];
|
|
134
|
+
}
|
|
135
|
+
/** The template that creates `table`: from `domain` first, then common, then any other domain. */
|
|
136
|
+
function templateForTable(domains, table, domain) {
|
|
137
|
+
const order = [
|
|
138
|
+
...domains.filter((d) => d.name === domain),
|
|
139
|
+
...domains.filter((d) => d.name === "common" && d.name !== domain),
|
|
140
|
+
...domains.filter((d) => d.name !== domain && d.name !== "common"),
|
|
141
|
+
];
|
|
142
|
+
for (const d of order) {
|
|
143
|
+
const found = d.templates.find((t) => t.table === table);
|
|
144
|
+
if (found)
|
|
145
|
+
return found;
|
|
146
|
+
}
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Order `templates` so each comes after the tables its foreign keys point
|
|
151
|
+
* to (when those are in the list too). Throws on a cycle.
|
|
152
|
+
*/
|
|
153
|
+
function orderByDependencies(items) {
|
|
154
|
+
const byTable = new Map(items.map((i) => [i.table, i]));
|
|
155
|
+
const out = [];
|
|
156
|
+
const state = new Map();
|
|
157
|
+
const visit = (item, trail) => {
|
|
158
|
+
const s = state.get(item.table);
|
|
159
|
+
if (s === "done")
|
|
160
|
+
return;
|
|
161
|
+
if (s === "visiting")
|
|
162
|
+
throw new errors_1.CliError(`Foreign keys form a cycle: ${[...trail, item.table].join(" → ")}.`);
|
|
163
|
+
state.set(item.table, "visiting");
|
|
164
|
+
for (const dep of (0, template_1.dependencies)(item.template)) {
|
|
165
|
+
const target = byTable.get(dep);
|
|
166
|
+
if (target && target !== item)
|
|
167
|
+
visit(target, [...trail, item.table]);
|
|
168
|
+
}
|
|
169
|
+
state.set(item.table, "done");
|
|
170
|
+
out.push(item);
|
|
171
|
+
};
|
|
172
|
+
for (const item of items)
|
|
173
|
+
visit(item, []);
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Dialect } from "../utils/dialect";
|
|
2
|
+
import type { FieldDef } from "./fields";
|
|
3
|
+
import type { ModelTemplate } from "./template";
|
|
4
|
+
/** The schema builder call for one column, e.g. `table.string("name", 100).nullable();`. */
|
|
5
|
+
export declare function renderColumn(field: FieldDef, dialect?: Dialect): string;
|
|
6
|
+
/** A `defineMigration` file creating the template's table. */
|
|
7
|
+
export declare function renderCreateMigration(t: ModelTemplate, table?: string, dialect?: Dialect): string;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.renderColumn = renderColumn;
|
|
4
|
+
exports.renderCreateMigration = renderCreateMigration;
|
|
5
|
+
/** The schema builder call for one column, e.g. `table.string("name", 100).nullable();`. */
|
|
6
|
+
function renderColumn(field, dialect) {
|
|
7
|
+
const name = JSON.stringify(field.name);
|
|
8
|
+
let call;
|
|
9
|
+
switch (field.type) {
|
|
10
|
+
case "string":
|
|
11
|
+
call = field.length && field.length !== 255 ? `string(${name}, ${field.length})` : `string(${name})`;
|
|
12
|
+
break;
|
|
13
|
+
case "decimal":
|
|
14
|
+
call = field.precision ? `decimal(${name}, ${field.precision}, ${field.scale ?? 2})` : `decimal(${name})`;
|
|
15
|
+
break;
|
|
16
|
+
default:
|
|
17
|
+
call = `${field.type}(${name})`;
|
|
18
|
+
}
|
|
19
|
+
let line = `table.${call}`;
|
|
20
|
+
const setNull = field.references?.onDelete === "set null";
|
|
21
|
+
if (field.nullable && !setNull)
|
|
22
|
+
line += ".nullable()";
|
|
23
|
+
if (field.unique)
|
|
24
|
+
line += ".unique()";
|
|
25
|
+
if (field.default !== undefined)
|
|
26
|
+
line += `.default(${JSON.stringify(field.default)})`;
|
|
27
|
+
if (field.references) {
|
|
28
|
+
line += `.constrained(${JSON.stringify(field.references.table)})`;
|
|
29
|
+
if (field.references.onDelete === "cascade")
|
|
30
|
+
line += ".cascadeOnDelete()";
|
|
31
|
+
else if (setNull)
|
|
32
|
+
line += ".nullOnDelete()";
|
|
33
|
+
// SQL Server has no RESTRICT; NO ACTION also refuses the delete.
|
|
34
|
+
else if (field.references.onDelete === "restrict") {
|
|
35
|
+
line += dialect === "mssql" ? `.onDelete("no action")` : `.onDelete("restrict")`;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
line += ";";
|
|
39
|
+
const comments = [field.enum?.join(" | "), field.comment].filter(Boolean);
|
|
40
|
+
if (comments.length)
|
|
41
|
+
line += ` // ${comments.join("; ")}`;
|
|
42
|
+
return line;
|
|
43
|
+
}
|
|
44
|
+
/** A `defineMigration` file creating the template's table. */
|
|
45
|
+
function renderCreateMigration(t, table = t.table, dialect) {
|
|
46
|
+
const lines = [];
|
|
47
|
+
if (!t.pivot)
|
|
48
|
+
lines.push("table.id();");
|
|
49
|
+
for (const field of t.fields)
|
|
50
|
+
lines.push(renderColumn(field, dialect));
|
|
51
|
+
if (t.timestamps)
|
|
52
|
+
lines.push("table.timestamps();");
|
|
53
|
+
if (t.softDeletes)
|
|
54
|
+
lines.push("table.softDeletes();");
|
|
55
|
+
const list = (columns) => `[${columns.map((c) => JSON.stringify(c)).join(", ")}]`;
|
|
56
|
+
if (t.pivot) {
|
|
57
|
+
const keys = t.fields.filter((f) => f.type === "foreignId").map((f) => f.name);
|
|
58
|
+
if (keys.length >= 2)
|
|
59
|
+
lines.push(`table.primary(${list(keys.slice(0, 2))});`);
|
|
60
|
+
}
|
|
61
|
+
for (const field of t.fields)
|
|
62
|
+
if (field.index && !field.unique)
|
|
63
|
+
lines.push(`table.index(${JSON.stringify(field.name)});`);
|
|
64
|
+
for (const columns of t.unique)
|
|
65
|
+
lines.push(`table.unique(${list(columns)});`);
|
|
66
|
+
return `import { defineMigration } from "@meghjs/core";
|
|
67
|
+
|
|
68
|
+
export default defineMigration({
|
|
69
|
+
async up(schema) {
|
|
70
|
+
await schema.create(${JSON.stringify(table)}, (table) => {
|
|
71
|
+
${lines.map((l) => ` ${l}`).join("\n")}
|
|
72
|
+
});
|
|
73
|
+
},
|
|
74
|
+
|
|
75
|
+
async down(schema) {
|
|
76
|
+
await schema.drop(${JSON.stringify(table)});
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
`;
|
|
80
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type FieldDef } from "./fields";
|
|
2
|
+
/** A table a model is scaffolded from: its columns, timestamps and keys. */
|
|
3
|
+
export interface ModelTemplate {
|
|
4
|
+
/** e.g. `ecommerce`. */
|
|
5
|
+
domain: string;
|
|
6
|
+
/** snake_case singular, e.g. `order_item`. */
|
|
7
|
+
name: string;
|
|
8
|
+
/** e.g. `order_items`. */
|
|
9
|
+
table: string;
|
|
10
|
+
description: string;
|
|
11
|
+
fields: FieldDef[];
|
|
12
|
+
timestamps: boolean;
|
|
13
|
+
softDeletes: boolean;
|
|
14
|
+
/** A join table: no id, a composite primary key, migration only (no model). */
|
|
15
|
+
pivot: boolean;
|
|
16
|
+
/** Composite unique keys. */
|
|
17
|
+
unique: string[][];
|
|
18
|
+
}
|
|
19
|
+
export interface Domain {
|
|
20
|
+
name: string;
|
|
21
|
+
title: string;
|
|
22
|
+
description: string;
|
|
23
|
+
templates: ModelTemplate[];
|
|
24
|
+
}
|
|
25
|
+
export type TemplateOptions = {
|
|
26
|
+
table?: string;
|
|
27
|
+
timestamps?: boolean;
|
|
28
|
+
softDeletes?: boolean;
|
|
29
|
+
pivot?: boolean;
|
|
30
|
+
unique?: string[][];
|
|
31
|
+
};
|
|
32
|
+
/** A template from field specs (see fields.ts). */
|
|
33
|
+
export declare function template(domain: string, name: string, description: string, specs: string[], opts?: TemplateOptions): ModelTemplate;
|
|
34
|
+
/** A domain whose templates are written as `[name, description, specs, options?]`. */
|
|
35
|
+
export declare function domain(name: string, title: string, description: string, templates: [string, string, string[], TemplateOptions?][]): Domain;
|
|
36
|
+
/** Tables a template's foreign keys point to (itself excluded). */
|
|
37
|
+
export declare function dependencies(t: ModelTemplate): string[];
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.template = template;
|
|
4
|
+
exports.domain = domain;
|
|
5
|
+
exports.dependencies = dependencies;
|
|
6
|
+
const orm_model_1 = require("../generators/orm-model");
|
|
7
|
+
const fields_1 = require("./fields");
|
|
8
|
+
/** A template from field specs (see fields.ts). */
|
|
9
|
+
function template(domain, name, description, specs, opts = {}) {
|
|
10
|
+
const pivot = opts.pivot === true;
|
|
11
|
+
return {
|
|
12
|
+
domain,
|
|
13
|
+
name,
|
|
14
|
+
table: opts.table ?? (0, orm_model_1.pluralize)(name),
|
|
15
|
+
description,
|
|
16
|
+
fields: specs.flatMap(fields_1.parseFieldSpec),
|
|
17
|
+
timestamps: opts.timestamps ?? !pivot,
|
|
18
|
+
softDeletes: opts.softDeletes ?? false,
|
|
19
|
+
pivot,
|
|
20
|
+
unique: opts.unique ?? [],
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** A domain whose templates are written as `[name, description, specs, options?]`. */
|
|
24
|
+
function domain(name, title, description, templates) {
|
|
25
|
+
return {
|
|
26
|
+
name,
|
|
27
|
+
title,
|
|
28
|
+
description,
|
|
29
|
+
templates: templates.map(([n, d, specs, opts]) => template(name, n, d, specs, opts)),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** Tables a template's foreign keys point to (itself excluded). */
|
|
33
|
+
function dependencies(t) {
|
|
34
|
+
const tables = t.fields.flatMap((f) => (f.references ? [f.references.table] : []));
|
|
35
|
+
return [...new Set(tables)].filter((table) => table !== t.table);
|
|
36
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type Dialect = "postgres" | "mysql" | "sqlite" | "mssql";
|
|
2
|
+
/**
|
|
3
|
+
* The database the project's migrations run on, found the way
|
|
4
|
+
* app.useMeghORM() finds it: `megh.database` in package.json, then
|
|
5
|
+
* DB_DIALECT, then the scheme of DATABASE_URL (the environment over .env).
|
|
6
|
+
* Undefined when nothing says.
|
|
7
|
+
*/
|
|
8
|
+
export declare function projectDialect(projectRoot: string): Dialect | undefined;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.projectDialect = projectDialect;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const SCHEMES = {
|
|
10
|
+
postgres: "postgres",
|
|
11
|
+
postgresql: "postgres",
|
|
12
|
+
mysql: "mysql",
|
|
13
|
+
mariadb: "mysql",
|
|
14
|
+
mssql: "mssql",
|
|
15
|
+
sqlserver: "mssql",
|
|
16
|
+
sqlite: "sqlite",
|
|
17
|
+
file: "sqlite",
|
|
18
|
+
};
|
|
19
|
+
const DIALECTS = new Set(["postgres", "mysql", "sqlite", "mssql"]);
|
|
20
|
+
/** `KEY=value` pairs of a .env file (no expansion). */
|
|
21
|
+
function readDotEnv(file) {
|
|
22
|
+
if (!fs_1.default.existsSync(file))
|
|
23
|
+
return {};
|
|
24
|
+
const out = {};
|
|
25
|
+
for (const line of fs_1.default.readFileSync(file, "utf8").split(/\r?\n/)) {
|
|
26
|
+
const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][\w]*)\s*=\s*(.*?)\s*$/);
|
|
27
|
+
if (m)
|
|
28
|
+
out[m[1]] = m[2].replace(/^(["'])(.*)\1$/, "$2");
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
const fromUrl = (url) => {
|
|
33
|
+
const scheme = url?.match(/^([a-z][a-z0-9+.-]*):/i)?.[1].toLowerCase();
|
|
34
|
+
return scheme ? SCHEMES[scheme] : undefined;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* The database the project's migrations run on, found the way
|
|
38
|
+
* app.useMeghORM() finds it: `megh.database` in package.json, then
|
|
39
|
+
* DB_DIALECT, then the scheme of DATABASE_URL (the environment over .env).
|
|
40
|
+
* Undefined when nothing says.
|
|
41
|
+
*/
|
|
42
|
+
function projectDialect(projectRoot) {
|
|
43
|
+
let database = {};
|
|
44
|
+
try {
|
|
45
|
+
const pkg = JSON.parse(fs_1.default.readFileSync(path_1.default.join(projectRoot, "package.json"), "utf8"));
|
|
46
|
+
database = pkg?.megh?.database ?? {};
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
// No or invalid package.json: use the environment.
|
|
50
|
+
}
|
|
51
|
+
const dotenv = readDotEnv(path_1.default.join(projectRoot, ".env"));
|
|
52
|
+
const env = (key) => process.env[key] ?? dotenv[key];
|
|
53
|
+
const named = database.dialect ?? env("DB_DIALECT");
|
|
54
|
+
if (named && DIALECTS.has(named))
|
|
55
|
+
return named;
|
|
56
|
+
return fromUrl(database.url) ?? fromUrl(env("DATABASE_URL"));
|
|
57
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@meghjs/cli",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.4",
|
|
4
4
|
"description": "CLI for scaffolding and running Megh applications",
|
|
5
5
|
"author": "Tareq Hossain",
|
|
6
6
|
"license": "MIT",
|
|
@@ -27,10 +27,18 @@
|
|
|
27
27
|
"prepublishOnly": "npm run build"
|
|
28
28
|
},
|
|
29
29
|
"keywords": [
|
|
30
|
-
"cli",
|
|
31
30
|
"megh",
|
|
31
|
+
"cli",
|
|
32
|
+
"typescript",
|
|
32
33
|
"backend",
|
|
33
|
-
"
|
|
34
|
+
"generator",
|
|
35
|
+
"scaffold",
|
|
36
|
+
"scaffolding",
|
|
37
|
+
"migrations",
|
|
38
|
+
"orm",
|
|
39
|
+
"auth",
|
|
40
|
+
"rbac",
|
|
41
|
+
"fastify"
|
|
34
42
|
],
|
|
35
43
|
"dependencies": {
|
|
36
44
|
"@swc/core": "^1.13.5",
|
|
@@ -44,7 +52,7 @@
|
|
|
44
52
|
"vitest": "^4.1.12"
|
|
45
53
|
},
|
|
46
54
|
"peerDependencies": {
|
|
47
|
-
"@meghjs/core": "^0.5.
|
|
55
|
+
"@meghjs/core": "^0.5.4"
|
|
48
56
|
},
|
|
49
57
|
"peerDependenciesMeta": {
|
|
50
58
|
"@meghjs/core": {
|
|
@@ -56,8 +64,12 @@
|
|
|
56
64
|
"url": "git+https://github.com/meghjs/megh.git",
|
|
57
65
|
"directory": "packages/cli"
|
|
58
66
|
},
|
|
67
|
+
"homepage": "https://meghjs.github.io/cli/basic",
|
|
68
|
+
"bugs": {
|
|
69
|
+
"url": "https://github.com/meghjs/megh/issues"
|
|
70
|
+
},
|
|
59
71
|
"publishConfig": {
|
|
60
72
|
"access": "public"
|
|
61
73
|
},
|
|
62
|
-
"gitHead": "
|
|
74
|
+
"gitHead": "25ab107490492cc54d1eb3419a33b735613c57ab"
|
|
63
75
|
}
|
package/readme.md
CHANGED
|
@@ -43,12 +43,21 @@ npm run start:dev
|
|
|
43
43
|
| `start` | | `--entry <file>` | Run the compiled app with `NODE_ENV=production` |
|
|
44
44
|
| `doctor` | | | Check Node.js, `@meghjs/core`, `reflect-metadata` and decorator settings |
|
|
45
45
|
| `route:list` | `routes` | `--json`, `--static` | List the app's routes |
|
|
46
|
-
| `make:model` | `m:m` | `-f`, `--orm`, `--root <dir
|
|
46
|
+
| `make:model` | `m:m` | `-f`, `--orm`, `--root <dir>`, `--template [ref]`, `--fields <list>`, `--factory` | Create a model / TypeORM entity; with `--template` / `--fields`, also its migration |
|
|
47
|
+
| `make:resource` | `m:r` | `-f`, `-t <table>`, `--template [ref]`, `--fields <list>`, `--factory` | Create a model's DTOs, CRUD service and controller |
|
|
48
|
+
| `update:model` | `u:m` | `-t <table>`, `--dto`, `--dry-run`, `--root <dir>` | Sync a model's columns with its migrations, keeping relations and methods |
|
|
47
49
|
| `make:controller` | `m:c` | `-f`, `-r`, `-m <model>`, `--orm`, `--root <dir>`, `--base-path` | Create a controller |
|
|
48
50
|
| `make:service` | `m:s` | `-f`, `-r`, `-m <model>`, `--orm`, `--root <dir>` | Create a service |
|
|
49
51
|
| `make:config` | `m:cnf` | `-f`, `--root <dir>` | Create an `@AppConfig` class |
|
|
50
52
|
| `make:middleware` | `m:mlwr` | `-f`, `--root <dir>` | Create a middleware |
|
|
51
53
|
| `make:dto` | `m:dto` | `-f`, `--root <dir>` | Create a class-validator DTO |
|
|
54
|
+
| `make:seeder` | `m:sd` | `-f` | Create a seeder in `src/database/seeders` (`database` for the entry seeder) |
|
|
55
|
+
| `db:seed` | | `-s <name>`, `--force` | Run the seeders in one transaction (also `migrate --seed`) |
|
|
56
|
+
| `make:factory` | `m:f` | `-f` | Create a model factory in `src/database/factories`, with Faker values per column |
|
|
57
|
+
| `scaffold:domain [domain]` | `sc:domain` | `--only <list>`, `--resource`, `--factory`, `--migrations-only`, `--no-deps`, `-y` | Create a business domain's tables and models (or resources) |
|
|
58
|
+
| `scaffold:auth` | `sc:auth` | `--strategy <jwt\|api-key\|both>`, `--roles <none\|single\|multiple>`, `--permissions`, `-f`, `-y` | Add sign-up and sign-in, optionally with roles and permissions |
|
|
59
|
+
| `scaffold:rbac` | `sc:rbac` | `--roles <single\|multiple>`, `--permissions`, `-f`, `-y` | Add roles and permissions to an app's users |
|
|
60
|
+
| `template:list [domain]` | `templates` | `--json` | List the model templates |
|
|
52
61
|
|
|
53
62
|
`-f` / `--force` overwrites an existing file. `-r` / `--resource` generates a
|
|
54
63
|
full REST skeleton. `--root <dir>` (also `-rt`) writes under `src/<dir>`
|
|
@@ -114,6 +123,26 @@ npx megh make:config jwt
|
|
|
114
123
|
|
|
115
124
|
Generates a class extending `MeghConfig`, registered via `@AppConfig`.
|
|
116
125
|
|
|
126
|
+
## Scaffold
|
|
127
|
+
|
|
128
|
+
Build tables, models and whole features from templates. A template becomes a
|
|
129
|
+
create-table migration; the model, DTOs, service and controller are generated
|
|
130
|
+
from it.
|
|
131
|
+
|
|
132
|
+
```sh
|
|
133
|
+
npx megh make:model Product --template ecommerce/product # migration + model (+ categories, brands)
|
|
134
|
+
npx megh make:resource Ticket --fields "title,body,status:in(open|closed),user_id:cascade"
|
|
135
|
+
npx megh sc:domain ecommerce --resource # a whole domain as REST resources
|
|
136
|
+
npx megh sc:auth --strategy both --roles multiple --permissions
|
|
137
|
+
npx megh sc:rbac --roles single --permissions
|
|
138
|
+
npx megh templates ecommerce # list a domain's templates
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
There are 11 domains (common, ecommerce, pos, medical, construction,
|
|
142
|
+
marketing, real-estate, hr, crm, education, logistics), and your own go in
|
|
143
|
+
`.megh/templates/<domain>.json`. See [Scaffold](https://meghjs.github.io/cli/scaffold/)
|
|
144
|
+
for the field spec, every template, and what `sc:auth` generates.
|
|
145
|
+
|
|
117
146
|
## Development Server
|
|
118
147
|
|
|
119
148
|
```sh
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { ApiController, Body, Delete, Get, Param, Post, Put, Query } from '@meghjs/core';
|
|
1
|
+
import { ApiController, ApiResponse, Body, Delete, Get, Paginated, Param, Post, Put, Query } from '@meghjs/core';
|
|
2
|
+
import { {Model} } from '{modelImport}';
|
|
2
3
|
import { Create{Model}Dto, List{Plural}Query, Update{Model}Dto } from '{dtoImport}';
|
|
3
4
|
import { {ServiceClass} } from '{serviceImport}';
|
|
4
5
|
|
|
@@ -7,26 +8,34 @@ export class {ClassName} {
|
|
|
7
8
|
constructor(private readonly {serviceVar}: {ServiceClass}) {}
|
|
8
9
|
|
|
9
10
|
@Get()
|
|
11
|
+
@ApiResponse(200, Paginated({Model}))
|
|
10
12
|
index(@Query() query: List{Plural}Query) {
|
|
11
13
|
return this.{serviceVar}.paginate(query);
|
|
12
14
|
}
|
|
13
15
|
|
|
14
16
|
@Get('/:id')
|
|
17
|
+
@ApiResponse(200, {Model})
|
|
18
|
+
@ApiResponse(404)
|
|
15
19
|
show(@Param('id') id: {primaryKeyType}) {
|
|
16
20
|
return this.{serviceVar}.findOrFail({idArg});
|
|
17
21
|
}
|
|
18
22
|
|
|
19
23
|
@Post()
|
|
24
|
+
@ApiResponse(200, {Model})
|
|
20
25
|
create(@Body() body: Create{Model}Dto) {
|
|
21
26
|
return this.{serviceVar}.create(body);
|
|
22
27
|
}
|
|
23
28
|
|
|
24
29
|
@Put('/:id')
|
|
30
|
+
@ApiResponse(200, {Model})
|
|
31
|
+
@ApiResponse(404)
|
|
25
32
|
update(@Param('id') id: {primaryKeyType}, @Body() body: Update{Model}Dto) {
|
|
26
33
|
return this.{serviceVar}.update({idArg}, body);
|
|
27
34
|
}
|
|
28
35
|
|
|
29
36
|
@Delete('/:id')
|
|
37
|
+
@ApiResponse(200, { type: 'object', properties: { message: { type: 'string' } } })
|
|
38
|
+
@ApiResponse(404)
|
|
30
39
|
async delete(@Param('id') id: {primaryKeyType}) {
|
|
31
40
|
await this.{serviceVar}.delete({idArg});
|
|
32
41
|
return { message: '{Model} deleted.' };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { defineSeeder } from "@meghjs/core";
|
|
2
|
+
|
|
3
|
+
export default defineSeeder({
|
|
4
|
+
async run() {
|
|
5
|
+
// Insert rows with factories, models or the query builder, e.g.
|
|
6
|
+
// await UserFactory.createMany(10); // megh make:factory user
|
|
7
|
+
// await Role.create({ name: "Admin" });
|
|
8
|
+
// await DB.table("{table}").insert([{ ... }]);
|
|
9
|
+
},
|
|
10
|
+
});
|