-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathgenerateModels.js
More file actions
executable file
·72 lines (62 loc) · 2.46 KB
/
Copy pathgenerateModels.js
File metadata and controls
executable file
·72 lines (62 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import fs from "fs";
import path from "path";
import { toPascalCase, mapToTypeScriptType, getInstance } from "./utils.js";
import dotenv from "dotenv";
import { callTsProxy } from "./callTsProxy.js";
import { getAdminInstance } from "../commands/createCustomComponent/configLoader.js";
const envFileArg = process.argv.find((arg) => arg.startsWith("--env-file="));
const envFilePath = envFileArg ? envFileArg.split("=")[1] : ".env";
dotenv.config({ path: envFilePath });
async function generateModels() {
const currentDirectory = process.cwd();
const outputDirectory = path.join(
currentDirectory,
"node_modules",
"adminforth",
"models"
);
const modelFilePath = path.join(outputDirectory, "models.ts");
if (!fs.existsSync(outputDirectory)) {
fs.mkdirSync(outputDirectory, { recursive: true });
}
let modelContent = "// Generated model file\n\n";
let instanceFound = false;
const { adminInstance, configPath, configFileName } = await getAdminInstance();
if (adminInstance) {
await adminInstance.discoverDatabases();
instanceFound = true;
for (const resource of adminInstance.config.resources) {
if (resource.columns) {
const typeName = toPascalCase(resource.resourceId);
const tsCode = `
export async function exec() {
const columns = ${JSON.stringify(resource.columns)};
const typeName = "${typeName}";
function mapToTypeScriptType(type) {
const map = { "integer": "number", "varchar": "string", "boolean": "boolean", "date": "string", "datetime": "string", "decimal": "number", "float": "number", "json": "Record<string, any>", "text": "string", "string": "string", "time": "string" };
return map[type] || "any";
}
let typeStr = \`export type \${typeName} = {\\n\`;
for (const col of columns) {
if (col.name && col.type) {
typeStr += \` \${col.name}: \${mapToTypeScriptType(col.type)};\\n\`;
}
}
typeStr += "}\\n\\n";
return typeStr;
}
`;
const result = await callTsProxy(tsCode);
modelContent += result;
}
};
}
if (!instanceFound) {
console.error("Error: No valid instance found to generate models.");
return;
}
fs.writeFileSync(modelFilePath, modelContent, "utf-8");
console.log(`Generated TypeScript model file: ${modelFilePath}`);
return true;
}
export default generateModels;