1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const changeCase = require("change-case");
|
4 | const enum_matcher_1 = require("./enums/enum-matcher");
|
5 | class InterfaceBuilder {
|
6 | constructor(settings, mysqlTypes, schema) {
|
7 | this.settings = settings;
|
8 | this.mysqlTypes = mysqlTypes;
|
9 | this.schema = schema;
|
10 | this.matcher = new enum_matcher_1.EnumMatcher();
|
11 | }
|
12 | renderTs(tableClass, table) {
|
13 | const extraImports = [];
|
14 | let stringBuilder = this.settings.defaultClassModifier + " " + tableClass.prefixedClassName + " { \n";
|
15 | for (const colName in table) {
|
16 | const col = table[colName];
|
17 | stringBuilder += this.buildTypeRow(col, colName);
|
18 | if (this.isEnum(col)) {
|
19 | extraImports.push(col);
|
20 | }
|
21 | }
|
22 | stringBuilder += "}\n";
|
23 | const importStatements = new Set();
|
24 | if (extraImports.length) {
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | const bestMatches = extraImports.map(c => this.matcher.run(this.schema, c, tableClass.tableName));
|
31 | bestMatches.forEach(b => {
|
32 | let relativePath = "../enums/" + changeCase.paramCase(b.table) + ".generated";
|
33 | importStatements.add(this.importStatement([changeCase.constant(b.table)], relativePath));
|
34 | });
|
35 |
|
36 | }
|
37 | const importStr = [...importStatements].join("");
|
38 | return this.getMetaText() + "\n" + importStr + "\n" + stringBuilder;
|
39 | }
|
40 | importStatement(fieldNames, relativePath) {
|
41 | return `import { ${fieldNames.join(", ")} } from "${relativePath}"\n`;
|
42 | }
|
43 | getMetaText() {
|
44 | let meta = `/**\n * Autogenerated interface, DO NOT MODIFY\n */\n`;
|
45 | meta += "/* tslint:disable */\n";
|
46 | return meta;
|
47 | }
|
48 | buildTypeRow(col, colName) {
|
49 | const tabs = "\t";
|
50 | const optional = this.settings.optionalParameters ? "?" : "";
|
51 | const tsType = this.getTsType(col, colName);
|
52 | const field = col.field;
|
53 | return `${tabs}"${field}"${optional}: ${tsType};\n`;
|
54 | }
|
55 | ;
|
56 | isEnum(col) {
|
57 | var _a;
|
58 | return !!((_a = col.enumValues) === null || _a === void 0 ? void 0 : _a.length);
|
59 | }
|
60 | getTsType(col, colName) {
|
61 | var _a;
|
62 | if (this.isEnum(col)) {
|
63 |
|
64 |
|
65 |
|
66 | const matches = this.matcher.run(this.schema, col, colName);
|
67 | if (!matches) {
|
68 | throw new Error("No matching column");
|
69 | }
|
70 | if ((_a = matches.replacementFor) === null || _a === void 0 ? void 0 : _a.length) {
|
71 | return changeCase.constantCase(matches.field);
|
72 | }
|
73 | return changeCase.constantCase(matches.table) + "." + changeCase.constantCase(matches.field);
|
74 |
|
75 | }
|
76 | let ts = this.mysqlTypes[col.type];
|
77 | if (!ts) {
|
78 |
|
79 | console.error("Unknown type " + col.type);
|
80 | return "unknown";
|
81 | }
|
82 | return ts;
|
83 | }
|
84 | }
|
85 | exports.InterfaceBuilder = InterfaceBuilder;
|
86 |
|
\ | No newline at end of file |