@naiv/codegen-axios-client 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2024 ADF Language. https://adf-lang.com
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,110 @@
1
+ # TypeORM - ADF Code Generator
2
+
3
+ Generator kode [ADF](https://github.com/Graf-Research/adf-core) untuk model [TypeORM](https://github.com/typeorm/typeorm) dalam format Typescript.
4
+
5
+ **Modul ADF yang digunakan**
6
+
7
+ `Table` `Enum`
8
+
9
+ **Penggunaan CLI (Command Line)**
10
+
11
+ ```bash
12
+ npx @graf-research/adf-codegen-model-typeorm <file/url ADF> <folder output>
13
+ ```
14
+
15
+ ## Instalasi
16
+
17
+ ```bash
18
+ npm install --save @graf-research/adf-codegen-model-typeorm
19
+ ```
20
+
21
+ ## Fungsi
22
+
23
+ ```typescript
24
+ import { Model } from "@graf-research/adf-core";
25
+
26
+ type MapModelNameFilePath = {[key: string]: string};
27
+
28
+ interface CodegenFileOutput {
29
+ filename: string
30
+ content: string
31
+ }
32
+
33
+ interface ItemOutput {
34
+ files: CodegenFileOutput[]
35
+ map: MapModelNameFilePath
36
+ }
37
+
38
+ interface Output {
39
+ table: ItemOutput
40
+ enum: ItemOutput
41
+ }
42
+
43
+ function TypeORMModel.compile(list_model: Model.Item[]): Output
44
+ ```
45
+
46
+ ## Paduan TypeORM
47
+
48
+ Untuk menggunakan fitur auto generated-migration TypeORM konfigurasi antara data source harus sesuai. Pada generator ini kode yang di-generate akan muncul pada dua folder besar yaitu:
49
+ - &lt;folder output&gt;/model/table/*.ts
50
+ - &lt;folder output&gt;/model/enum/*.ts
51
+
52
+ Berikut salah satu contoh kofigurasi Data Source dan Script `package.json`
53
+
54
+ #### data-source.ts
55
+ ```typescript
56
+ import { DataSource, DataSourceOptions } from "typeorm";
57
+
58
+ const config: DataSourceOptions = {
59
+ type: "postgres",
60
+ host: 'localhost',
61
+ port: 5432,
62
+ username: '<username>',
63
+ password: '<password>',
64
+ database: '<database name>',
65
+ synchronize: false,
66
+ logging: false,
67
+ migrations: [
68
+ __dirname + '/migration/**.ts'
69
+ ],
70
+ entities: [
71
+ __dirname + '/<folder output>/model/**/*.{ts,js}'
72
+ ]
73
+ };
74
+
75
+ export const AppDataSource = new DataSource(config);
76
+ ```
77
+
78
+ #### package.json
79
+ ```json
80
+ {
81
+ ...
82
+ "scripts": {
83
+ ...
84
+ "typeorm": "typeorm-ts-node-commonjs",
85
+ "generate-migration": "npm run typeorm migration:generate -- $1 -d ./data-source.ts",
86
+ "migrate": "npm run typeorm migration:run -- -d ./data-source.ts"
87
+ },
88
+ ...
89
+ }
90
+ ```
91
+
92
+ ##### Generate Migration
93
+
94
+ Untuk men-generate file migration TypeORM gunakan script `generate-migration` dengan output folder `migration` seperti konfigurasi pada `data-source.ts`, misalnya sebuah file migration dengan nama `Init.ts`:
95
+
96
+ ```bash
97
+ npm run generate-migration migration/Init
98
+ ```
99
+
100
+ akan menghasilkan file migration `migration/Init.ts`
101
+
102
+ ##### Menjalankan Migration
103
+
104
+ Untuk menjalankan file migration TypeORM gunakan script `migrate`, contoh:
105
+
106
+ ```bash
107
+ npm run migrate
108
+ ```
109
+
110
+ akan mengeksekusi sql script dari file-file migration.
@@ -0,0 +1,3 @@
1
+ import { NVAPI } from "@naiv/core/build/semantic-checker/check_api";
2
+ import { ItemOutput } from "./data-types";
3
+ export declare function buildAPIClient(list_api: NVAPI[]): ItemOutput;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildAPIClient = buildAPIClient;
4
+ function buildAPIClient(list_api) {
5
+ return {
6
+ files: [{
7
+ filename: './AxiosClient.ts',
8
+ content: createAPIClientNamespace(list_api)
9
+ }],
10
+ map: {}
11
+ };
12
+ }
13
+ function createAPIClientNamespace(list_api) {
14
+ const list_api_import = list_api.filter((api) => api.data.alias).map((api) => [
15
+ `import { T_${api.data.alias} } from "./api/${api.data.alias}";`,
16
+ ].join('\n'));
17
+ const list_api_str = list_api.filter((api) => api.data.alias).map((api) => {
18
+ var _a, _b, _c, _d;
19
+ return [
20
+ ` export const ${api.data.alias}: T_${api.data.alias} = async (req, base_url: string = BaseURL.instance.base_url) => {`,
21
+ ` const final_url = __build_path(base_url, '${api.url_path}', ${(((_b = (_a = api.data.path) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0) ? 'req.path' : '{}'});`,
22
+ (['get', 'delete'].includes(api.method)
23
+ ? ` return (await axios['${api.method.toLowerCase()}'](final_url, ${createAPIParams(api)})).data as any;`
24
+ : ` return (await axios['${api.method.toLowerCase()}'](final_url, ${((_d = (_c = api.data.body) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0 ? 'req.body' : '{}'}, ${createAPIParams(api)})).data as any;`),
25
+ ` }`,
26
+ ].join('\n');
27
+ });
28
+ return [
29
+ list_api_import.join('\n'),
30
+ '',
31
+ 'export namespace AxiosClient {',
32
+ utility_functions,
33
+ list_api_str.join('\n'),
34
+ '}'
35
+ ].join('\n');
36
+ }
37
+ function createAPIParams(api) {
38
+ var _a, _b, _c, _d;
39
+ let result = '{';
40
+ if (((_b = (_a = api.data.headers) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0) {
41
+ result = `${result} headers: req.headers,`;
42
+ }
43
+ if (((_d = (_c = api.data.query) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0) {
44
+ result = `${result} params: req.query,`;
45
+ }
46
+ result = `${result} }`;
47
+ return result;
48
+ }
49
+ const utility_functions = `
50
+ function __build_path(base_url: string, url_path: string, path_param: { [key: string]: any }) {
51
+ const build_path = url_path.replace(/:([a-zA-Z_]\w*)/g, (_, key) => {
52
+ if (path_param[key] === undefined) {
53
+ throw new Error(\`Missing param: \${key}\`);
54
+ }
55
+ return encodeURIComponent(String(path_param[key]));
56
+ });
57
+ const url = new URL(build_path, base_url);
58
+ return url.toString();
59
+ }
60
+ export class BaseURL {
61
+ public base_url: string = '';
62
+ static _instance: BaseURL | undefined;
63
+ public static get instance(): BaseURL {
64
+ if (!BaseURL._instance) {
65
+ BaseURL._instance = new BaseURL();
66
+ }
67
+ return BaseURL._instance;
68
+ }
69
+ private constructor(){}
70
+ public set(_base_url: string) {
71
+ this.base_url = _base_url;
72
+ }
73
+ }
74
+ `;
@@ -0,0 +1,5 @@
1
+ import { NVAPI } from "@naiv/core/build/semantic-checker/check_api";
2
+ import { ItemOutput } from "./data-types";
3
+ import { NVSchema } from "@naiv/core/build/semantic-checker/check_schema";
4
+ export declare function getAPIFileName(api_alias: string, api: NVAPI, extension?: string): string;
5
+ export declare function buildFromAPI(api: NVAPI, list_schema: NVSchema[]): ItemOutput;
@@ -0,0 +1,103 @@
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.getAPIFileName = getAPIFileName;
7
+ exports.buildFromAPI = buildFromAPI;
8
+ const build_from_schema_1 = require("./build-from-schema");
9
+ const lodash_1 = __importDefault(require("lodash"));
10
+ function getAPIFileName(api_alias, api, extension) {
11
+ return `./api/${api_alias}${extension !== null && extension !== void 0 ? extension : ''}`;
12
+ }
13
+ function buildFromAPI(api, list_schema) {
14
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1;
15
+ if (!api.data.alias) {
16
+ throw new Error(`no api alias`);
17
+ }
18
+ let header_schema;
19
+ if (((_b = (_a = api.data.headers) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0) {
20
+ const s = {
21
+ name: `T_${api.data.alias}_headers`,
22
+ items: (_c = api.data.headers) !== null && _c !== void 0 ? _c : []
23
+ };
24
+ header_schema = (0, build_from_schema_1.getSchemaContent)(s, list_schema);
25
+ }
26
+ let query_schema;
27
+ if (((_e = (_d = api.data.query) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0) > 0) {
28
+ const s = {
29
+ name: `T_${api.data.alias}_query`,
30
+ items: (_f = api.data.query) !== null && _f !== void 0 ? _f : []
31
+ };
32
+ query_schema = (0, build_from_schema_1.getSchemaContent)(s, list_schema);
33
+ }
34
+ let path_schema;
35
+ if (((_h = (_g = api.data.path) === null || _g === void 0 ? void 0 : _g.length) !== null && _h !== void 0 ? _h : 0) > 0) {
36
+ const s = {
37
+ name: `T_${api.data.alias}_path`,
38
+ items: (_j = api.data.path) !== null && _j !== void 0 ? _j : []
39
+ };
40
+ path_schema = (0, build_from_schema_1.getSchemaContent)(s, list_schema);
41
+ }
42
+ let body_schema;
43
+ if (((_l = (_k = api.data.body) === null || _k === void 0 ? void 0 : _k.length) !== null && _l !== void 0 ? _l : 0) > 0) {
44
+ const s = {
45
+ name: `T_${api.data.alias}_body`,
46
+ items: (_m = api.data.body) !== null && _m !== void 0 ? _m : []
47
+ };
48
+ body_schema = (0, build_from_schema_1.getSchemaContent)(s, list_schema);
49
+ }
50
+ const fake_return_type_schema = {
51
+ name: 'ReturnType',
52
+ items: [{
53
+ key: 'rrr',
54
+ type: api.data.return_type.type
55
+ }]
56
+ };
57
+ const fake_return_type_schema_result = (0, build_from_schema_1.getSchemaContent)(fake_return_type_schema, list_schema);
58
+ const fake_return_type = {
59
+ key: 'rrr',
60
+ type: api.data.return_type.type
61
+ };
62
+ const fake_return_type_field_result = (0, build_from_schema_1.buildField)(fake_return_type, 0, { name: 'ReturnType', items: [] }, list_schema);
63
+ return {
64
+ files: [{
65
+ filename: getAPIFileName(api.data.alias, api, '.ts'),
66
+ content: [
67
+ `${lodash_1.default.uniq([
68
+ ...((_o = header_schema === null || header_schema === void 0 ? void 0 : header_schema.deps) !== null && _o !== void 0 ? _o : []),
69
+ ...((_p = query_schema === null || query_schema === void 0 ? void 0 : query_schema.deps) !== null && _p !== void 0 ? _p : []),
70
+ ...((_q = path_schema === null || path_schema === void 0 ? void 0 : path_schema.deps) !== null && _q !== void 0 ? _q : []),
71
+ ...((_r = body_schema === null || body_schema === void 0 ? void 0 : body_schema.deps) !== null && _r !== void 0 ? _r : []),
72
+ ...((_s = fake_return_type_schema_result.deps) !== null && _s !== void 0 ? _s : []),
73
+ ...((_t = fake_return_type_field_result.new_deps_lines) !== null && _t !== void 0 ? _t : []),
74
+ ].join('\n').split('\n')).join('\n')}
75
+
76
+ ${[
77
+ ...((_u = header_schema === null || header_schema === void 0 ? void 0 : header_schema.content) !== null && _u !== void 0 ? _u : []),
78
+ ...((_v = query_schema === null || query_schema === void 0 ? void 0 : query_schema.content) !== null && _v !== void 0 ? _v : []),
79
+ ...((_w = path_schema === null || path_schema === void 0 ? void 0 : path_schema.content) !== null && _w !== void 0 ? _w : []),
80
+ ...((_x = body_schema === null || body_schema === void 0 ? void 0 : body_schema.content) !== null && _x !== void 0 ? _x : []),
81
+ ...fake_return_type_field_result.new_class_lines,
82
+ ].join('\n')}
83
+
84
+ export type T_${api.data.alias} = (request: {
85
+ ${[
86
+ ((_y = header_schema === null || header_schema === void 0 ? void 0 : header_schema.content.length) !== null && _y !== void 0 ? _y : 0) > 0 ? ` headers: T_${api.data.alias}_headers` : '',
87
+ ((_z = query_schema === null || query_schema === void 0 ? void 0 : query_schema.content.length) !== null && _z !== void 0 ? _z : 0) > 0 ? ` query: T_${api.data.alias}_query` : '',
88
+ ((_0 = path_schema === null || path_schema === void 0 ? void 0 : path_schema.content.length) !== null && _0 !== void 0 ? _0 : 0) > 0 ? ` path: T_${api.data.alias}_path` : '',
89
+ ((_1 = body_schema === null || body_schema === void 0 ? void 0 : body_schema.content.length) !== null && _1 !== void 0 ? _1 : 0) > 0 ? ` body: T_${api.data.alias}_body` : '',
90
+ ].filter(Boolean).join('\n')}
91
+ }) => Promise<${fake_return_type_field_result.type_only}${api.data.return_type.type.required ? '' : ' | null'}>;
92
+
93
+ export const method = '${api.method.toLowerCase()}';
94
+ export const url_path = '${api.url_path}';
95
+ export const alias = '${api.data.alias}';
96
+ `
97
+ ].join('\n')
98
+ }],
99
+ map: {
100
+ [api.data.alias]: getAPIFileName(api.data.alias, api)
101
+ }
102
+ };
103
+ }
@@ -0,0 +1,4 @@
1
+ import { NVEnum } from "@naiv/core";
2
+ import { ItemOutput } from "./data-types";
3
+ export declare function getEnumFileName(item: NVEnum, extension?: string): string;
4
+ export declare function buildFromEnum(enume: NVEnum): ItemOutput;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getEnumFileName = getEnumFileName;
4
+ exports.buildFromEnum = buildFromEnum;
5
+ function getEnumFileName(item, extension) {
6
+ return `./model/enum/${item.name}${extension !== null && extension !== void 0 ? extension : ''}`;
7
+ }
8
+ function buildFromEnum(enume) {
9
+ return {
10
+ files: [{
11
+ filename: getEnumFileName(enume, '.ts'),
12
+ content: [
13
+ `export enum ${enume.name} {`,
14
+ ...enume.items
15
+ .map(s => `'${s}' = '${s}',`)
16
+ .map(line => ' ' + line),
17
+ `};`
18
+ ].join('\n')
19
+ }],
20
+ map: {
21
+ [enume.name]: getEnumFileName(enume)
22
+ }
23
+ };
24
+ }
@@ -0,0 +1,23 @@
1
+ import { NVSchema } from "@naiv/core/build/semantic-checker/check_schema";
2
+ import { ItemOutput } from "./data-types";
3
+ import { NVSchemaItem } from "@naiv/core/build/semantic-checker/check_schema_item";
4
+ export declare function getSchemaFileName(schema: NVSchema, extension?: string): string;
5
+ export declare function buildSchemaDependency(schema: NVSchema, list_schema: NVSchema[]): string[];
6
+ export declare function buildFromSchema(schema: NVSchema, list_schema: NVSchema[]): ItemOutput;
7
+ export interface SchemaContentResult {
8
+ deps: string[];
9
+ content: string[];
10
+ }
11
+ export declare function getSchemaContent(schema: NVSchema, list_schema: NVSchema[], no_export?: boolean): SchemaContentResult;
12
+ export interface BuildFieldResult {
13
+ field_lines: string[];
14
+ type_only: string;
15
+ new_class_lines: string[];
16
+ new_deps_lines: string[];
17
+ }
18
+ export declare function buildField(item: NVSchemaItem, index: number, schema: NVSchema, list_schema: NVSchema[]): BuildFieldResult;
19
+ export declare function buildInlineSchemaClass(items: NVSchemaItem[], parent_schema_name: string, index: number, list_schema: NVSchema[]): {
20
+ new_class_deps: string[];
21
+ new_class_content: string[];
22
+ inline_schema_name: string;
23
+ };
@@ -0,0 +1,138 @@
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.getSchemaFileName = getSchemaFileName;
7
+ exports.buildSchemaDependency = buildSchemaDependency;
8
+ exports.buildFromSchema = buildFromSchema;
9
+ exports.getSchemaContent = getSchemaContent;
10
+ exports.buildField = buildField;
11
+ exports.buildInlineSchemaClass = buildInlineSchemaClass;
12
+ const lodash_1 = __importDefault(require("lodash"));
13
+ function getSchemaFileName(schema, extension) {
14
+ return `./schema/${schema.name}${extension !== null && extension !== void 0 ? extension : ''}`;
15
+ }
16
+ function buildSchemaDependency(schema, list_schema) {
17
+ return schema.items
18
+ .filter((item) => item.type.type === 'schema' || item.type.type === 'table' || item.type.type === 'enum')
19
+ .map((item) => {
20
+ switch (item.type.type) {
21
+ case 'schema':
22
+ const schema_item = list_schema.find((s) => item.type.type === 'schema' && s.name === item.type.subtype_native);
23
+ if (!schema_item) {
24
+ throw new Error(`Schema "${item.type.subtype_native}" is not available`);
25
+ }
26
+ return `import { ${schema_item.name} } from '.${getSchemaFileName(schema_item)}'`;
27
+ case 'table':
28
+ return `import { ${item.type.subtype_native} } from '../model/table/${item.type.subtype_native}'`;
29
+ case 'enum':
30
+ return `import { ${item.type.subtype_native} } from '../model/enum/${item.type.subtype_native}'`;
31
+ default:
32
+ return '';
33
+ }
34
+ });
35
+ }
36
+ function buildFromSchema(schema, list_schema) {
37
+ const { deps, content } = getSchemaContent(schema, list_schema);
38
+ return {
39
+ files: [{
40
+ filename: getSchemaFileName(schema, '.ts'),
41
+ content: [
42
+ ...deps,
43
+ '',
44
+ ...content,
45
+ ].join('\n')
46
+ }],
47
+ map: {
48
+ [schema.name]: getSchemaFileName(schema)
49
+ }
50
+ };
51
+ }
52
+ function getSchemaContent(schema, list_schema, no_export) {
53
+ const field_lines = [];
54
+ const new_class_lines = [];
55
+ const new_deps_lines = [];
56
+ let i = 0;
57
+ for (const c of schema.items) {
58
+ const field_result = buildField(c, i, schema, list_schema);
59
+ field_lines.push(...field_result.field_lines);
60
+ new_class_lines.push(...field_result.new_class_lines);
61
+ new_deps_lines.push(...field_result.new_deps_lines);
62
+ i++;
63
+ }
64
+ const complete_deps = lodash_1.default.uniq([
65
+ ...buildSchemaDependency(schema, list_schema),
66
+ ...new_deps_lines
67
+ ].join('\n').split('\n'));
68
+ return {
69
+ deps: complete_deps,
70
+ content: [
71
+ ...new_class_lines,
72
+ `${no_export ? '' : 'export '}interface ${schema.name} {`,
73
+ ...field_lines.map(line => ' ' + line),
74
+ `}`
75
+ ]
76
+ };
77
+ }
78
+ function buildField(item, index, schema, list_schema) {
79
+ var _a;
80
+ const is_array = item.type.array_dimension > 0;
81
+ const array_token = Array(item.type.array_dimension).fill('[]').join('');
82
+ switch (item.type.type) {
83
+ case "native":
84
+ return {
85
+ field_lines: [
86
+ `${item.key}${item.type.required ? '' : '?'}: ${item.type.type_native}${is_array ? array_token : ''}`
87
+ ],
88
+ type_only: `${item.type.type_native}${is_array ? array_token : ''}`,
89
+ new_class_lines: [],
90
+ new_deps_lines: []
91
+ };
92
+ case "schema":
93
+ return {
94
+ field_lines: [
95
+ `${item.key}${item.type.required ? '' : '?'}: ${item.type.subtype_native}${is_array ? array_token : ''}`
96
+ ],
97
+ type_only: `${item.type.subtype_native}${is_array ? array_token : ''}`,
98
+ new_class_lines: [],
99
+ new_deps_lines: []
100
+ };
101
+ case "table":
102
+ return {
103
+ field_lines: [
104
+ `${item.key}${item.type.required ? '' : '?'}: ${item.type.subtype_native}${is_array ? array_token : ''}`
105
+ ],
106
+ type_only: `${item.type.subtype_native}${is_array ? array_token : ''}`,
107
+ new_class_lines: [],
108
+ new_deps_lines: []
109
+ };
110
+ case "enum":
111
+ return {
112
+ field_lines: [
113
+ `${item.key}${item.type.required ? '' : '?'}: ${item.type.subtype_native}${is_array ? array_token : ''}`
114
+ ],
115
+ type_only: `${item.type.subtype_native}${is_array ? array_token : ''}`,
116
+ new_class_lines: [],
117
+ new_deps_lines: []
118
+ };
119
+ case "inline-schema":
120
+ const { new_class_deps, new_class_content, inline_schema_name } = buildInlineSchemaClass(((_a = item.type.type_inline_schema) !== null && _a !== void 0 ? _a : []), schema.name, index, list_schema);
121
+ return {
122
+ field_lines: [
123
+ `${item.key}${item.type.required ? '' : '?'}: ${inline_schema_name}${is_array ? array_token : ''}`
124
+ ],
125
+ type_only: `${inline_schema_name}${is_array ? array_token : ''}`,
126
+ new_class_lines: new_class_content,
127
+ new_deps_lines: new_class_deps
128
+ };
129
+ }
130
+ }
131
+ function buildInlineSchemaClass(items, parent_schema_name, index, list_schema) {
132
+ const inline_schema = {
133
+ name: [parent_schema_name, index].join('_'),
134
+ items
135
+ };
136
+ const new_class = getSchemaContent(inline_schema, list_schema, true);
137
+ return { new_class_deps: new_class.deps, new_class_content: new_class.content, inline_schema_name: inline_schema.name };
138
+ }
@@ -0,0 +1,10 @@
1
+ import { NVResult, NVTable, NVTableField, NVTableFieldType } from "@naiv/core";
2
+ import { ItemOutput } from "./data-types";
3
+ export declare function getTableFileName(item: NVTable, extension?: string): string;
4
+ export declare function buildTableDependency(table: NVTable, source: NVResult): string[];
5
+ export declare function mapSQLTypeToJSType(type: NVTableFieldType): string;
6
+ export declare function buildColumnNative(type: NVTableFieldType, column: NVTableField, source: NVResult): string[];
7
+ export declare function buildColumnEnum(type: NVTableFieldType, column: NVTableField): string[];
8
+ export declare function buildColumnRelation(type: NVTableFieldType, column: NVTableField, table: NVTable, source: NVResult): string[];
9
+ export declare function buildColumn(column: NVTableField, table: NVTable, source: NVResult): string[];
10
+ export declare function buildFromTable(table: NVTable, source: NVResult): ItemOutput;
@@ -0,0 +1,167 @@
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.getTableFileName = getTableFileName;
7
+ exports.buildTableDependency = buildTableDependency;
8
+ exports.mapSQLTypeToJSType = mapSQLTypeToJSType;
9
+ exports.buildColumnNative = buildColumnNative;
10
+ exports.buildColumnEnum = buildColumnEnum;
11
+ exports.buildColumnRelation = buildColumnRelation;
12
+ exports.buildColumn = buildColumn;
13
+ exports.buildFromTable = buildFromTable;
14
+ const build_from_enum_1 = require("./build-from-enum");
15
+ const lodash_1 = __importDefault(require("lodash"));
16
+ function getTableFileName(item, extension) {
17
+ return `./model/table/${item.name}${extension !== null && extension !== void 0 ? extension : ''}`;
18
+ }
19
+ function buildTableDependency(table, source) {
20
+ return table.fields
21
+ .filter((tc) => tc.type.kind === 'relation' || tc.type.kind === 'enum')
22
+ .map((tc) => {
23
+ const type = tc.type;
24
+ switch (type.kind) {
25
+ case "native":
26
+ case "enum":
27
+ const enum_item = source.list_enum.find((m) => m.name === type.subtype);
28
+ if (!enum_item) {
29
+ throw new Error(`Enum "${type.subtype}" is not available on models`);
30
+ }
31
+ return `import { ${enum_item.name} } from '../.${(0, build_from_enum_1.getEnumFileName)(enum_item)}'`;
32
+ case 'relation':
33
+ const table_item = source.list_table.find((m) => m.name === type.type);
34
+ if (!table_item) {
35
+ throw new Error(`Table "${type.type}" is not available on models`);
36
+ }
37
+ return `import { ${table_item.name} } from '../.${getTableFileName(table_item)}'`;
38
+ }
39
+ });
40
+ }
41
+ function mapSQLTypeToJSType(type) {
42
+ switch (type.type) {
43
+ case 'bigint':
44
+ case 'int8':
45
+ case 'bigserial':
46
+ case 'serial8':
47
+ return 'number';
48
+ case 'boolean':
49
+ case 'bool':
50
+ return 'boolean';
51
+ case 'box':
52
+ case 'bytea':
53
+ case 'cidr':
54
+ case 'circle':
55
+ return 'number';
56
+ case 'date':
57
+ return 'Date';
58
+ case 'float':
59
+ case 'float8':
60
+ return 'number';
61
+ case 'inet':
62
+ return 'string';
63
+ case 'integer':
64
+ case 'int':
65
+ case 'int4':
66
+ return 'number';
67
+ case 'json':
68
+ case 'jsonb':
69
+ case 'line':
70
+ case 'lseg':
71
+ case 'macaddr':
72
+ case 'macaddr8':
73
+ return 'string';
74
+ case 'money':
75
+ return 'number';
76
+ case 'path':
77
+ return 'string';
78
+ case 'pg_lsn':
79
+ case 'pg_snapshot':
80
+ case 'point':
81
+ case 'polygon':
82
+ return 'string';
83
+ case 'real':
84
+ case 'float4':
85
+ case 'smallint':
86
+ case 'int2':
87
+ case 'smallserial':
88
+ case 'serial2':
89
+ case 'serial':
90
+ case 'serial4':
91
+ return 'number';
92
+ case 'text':
93
+ return 'string';
94
+ case 'timetz':
95
+ case 'timestamptz':
96
+ return 'Date';
97
+ case 'tsquery':
98
+ case 'tsvector':
99
+ case 'txid_snapshot':
100
+ case 'uuid':
101
+ case 'xml':
102
+ case 'bit':
103
+ case 'varbit':
104
+ case 'char':
105
+ case 'varchar':
106
+ return 'string';
107
+ case 'numeric':
108
+ case 'decimal':
109
+ return 'number';
110
+ case 'time':
111
+ case 'timestamp':
112
+ return 'Date';
113
+ }
114
+ throw new Error(`unsupported data type '${type.type}'`);
115
+ }
116
+ function buildColumnNative(type, column, source) {
117
+ const is_required = !type.nullable;
118
+ return [
119
+ `${column.column_name}${is_required ? '' : '?'}: ${mapSQLTypeToJSType(type)};`
120
+ ];
121
+ }
122
+ function buildColumnEnum(type, column) {
123
+ const is_required = !type.nullable;
124
+ return [
125
+ `${column.column_name}${is_required ? '' : '?'}: ${type.subtype};`
126
+ ];
127
+ }
128
+ function buildColumnRelation(type, column, table, source) {
129
+ const is_required = !type.nullable;
130
+ const foreign_table = source.list_table.find((item) => item.name === type.type);
131
+ if (!foreign_table) {
132
+ throw new Error(`Table "${type.type}" not found on relation "${table.name}.${column.column_name}"`);
133
+ }
134
+ const foreign_column = foreign_table.fields.find((fc) => fc.column_name === type.subtype);
135
+ if (!foreign_column) {
136
+ throw new Error(`Column "${type.subtype}" on table "${type.type}" not found on relation "${table.name}.${column.column_name}"`);
137
+ }
138
+ return [
139
+ `${column.column_name}${is_required ? '' : '?'}: ${mapSQLTypeToJSType(foreign_column.type)};`
140
+ ];
141
+ }
142
+ function buildColumn(column, table, source) {
143
+ switch (column.type.kind) {
144
+ case "native": return buildColumnNative(column.type, column, source);
145
+ case "enum": return buildColumnEnum(column.type, column);
146
+ case "relation": return buildColumnRelation(column.type, column, table, source);
147
+ }
148
+ }
149
+ function buildFromTable(table, source) {
150
+ return {
151
+ files: [{
152
+ filename: getTableFileName(table, '.ts'),
153
+ content: [
154
+ ...lodash_1.default.uniq(buildTableDependency(table, source)),
155
+ '',
156
+ `export interface ${table.name} {`,
157
+ ...table.fields
158
+ .reduce((acc, c) => [...acc, ...buildColumn(c, table, source)], [])
159
+ .map(line => ' ' + line),
160
+ `}`
161
+ ].join('\n')
162
+ }],
163
+ map: {
164
+ [table.name]: getTableFileName(table)
165
+ }
166
+ };
167
+ }
@@ -0,0 +1 @@
1
+ export declare function cmdGenerate(design_folder_abs_path: string, out_folder: string): Promise<void>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.cmdGenerate = cmdGenerate;
16
+ const naiv_parser_1 = require("@naiv/core/build/naiv_parser");
17
+ const fs_1 = __importDefault(require("fs"));
18
+ const path_1 = __importDefault(require("path"));
19
+ const _1 = require(".");
20
+ function cmdGenerate(design_folder_abs_path, out_folder) {
21
+ return __awaiter(this, void 0, void 0, function* () {
22
+ const result = (0, naiv_parser_1.naiv_parse_folder)(design_folder_abs_path, { fs: fs_1.default, path: path_1.default });
23
+ const typeorm_model = _1.TypeORMModel.compile(result);
24
+ for (const f of typeorm_model.enum.files) {
25
+ writeFiles(f, out_folder);
26
+ }
27
+ for (const f of typeorm_model.table.files) {
28
+ writeFiles(f, out_folder);
29
+ }
30
+ for (const f of typeorm_model.schema.files) {
31
+ writeFiles(f, out_folder);
32
+ }
33
+ for (const f of typeorm_model.api.files) {
34
+ writeFiles(f, out_folder);
35
+ }
36
+ for (const f of typeorm_model.http_client.files) {
37
+ writeFiles(f, out_folder);
38
+ }
39
+ });
40
+ }
41
+ function writeFiles(output_1) {
42
+ return __awaiter(this, arguments, void 0, function* (output, main_project_location = 'project') {
43
+ const folder = main_project_location + '/' + output.filename.split('/').slice(0, -1).join('/');
44
+ if (!fs_1.default.existsSync(folder)) {
45
+ fs_1.default.mkdirSync(folder, { recursive: true });
46
+ }
47
+ const filename = main_project_location + '/' + output.filename;
48
+ fs_1.default.writeFileSync(filename, output.content);
49
+ });
50
+ }
@@ -0,0 +1,11 @@
1
+ export type MapModelNameFilePath = {
2
+ [key: string]: string;
3
+ };
4
+ export interface CodegenFileOutput {
5
+ filename: string;
6
+ content: string;
7
+ }
8
+ export interface ItemOutput {
9
+ files: CodegenFileOutput[];
10
+ map: MapModelNameFilePath;
11
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/dist/exec.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/exec.js ADDED
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const arg_1 = __importDefault(require("arg"));
8
+ const cmd_generate_1 = require("./cmd-generate");
9
+ const args = (0, arg_1.default)({
10
+ "--design": String,
11
+ "--out": String,
12
+ "-d": "--design",
13
+ "-o": "--out"
14
+ });
15
+ if (!args['--design']) {
16
+ throw new Error(`--design/-d argument is required`);
17
+ }
18
+ if (args['--out']) {
19
+ (0, cmd_generate_1.cmdGenerate)(args['--design'], args['--out']);
20
+ process.exit(0);
21
+ }
22
+ throw new Error(`use --out/-o to generate axios client in typescript`);
@@ -0,0 +1,12 @@
1
+ import { NVResult } from "@naiv/core";
2
+ import { ItemOutput } from "./data-types";
3
+ export declare namespace TypeORMModel {
4
+ interface Output {
5
+ table: ItemOutput;
6
+ enum: ItemOutput;
7
+ schema: ItemOutput;
8
+ api: ItemOutput;
9
+ http_client: ItemOutput;
10
+ }
11
+ function compile(source: NVResult): Output;
12
+ }
package/dist/index.js ADDED
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TypeORMModel = void 0;
4
+ const build_from_table_1 = require("./build-from-table");
5
+ const build_from_enum_1 = require("./build-from-enum");
6
+ const build_from_schema_1 = require("./build-from-schema");
7
+ const build_from_api_1 = require("./build-from-api");
8
+ const build_api_client_1 = require("./build-api-client");
9
+ var TypeORMModel;
10
+ (function (TypeORMModel) {
11
+ function compile(source) {
12
+ const list_api_output = source.list_api.map((t) => (0, build_from_api_1.buildFromAPI)(t, source.list_schema));
13
+ const list_schema_output = source.list_schema.map((t) => (0, build_from_schema_1.buildFromSchema)(t, source.list_schema));
14
+ const list_table_output = source.list_table.map((t) => (0, build_from_table_1.buildFromTable)(t, source));
15
+ const list_enume_output = source.list_enum.map((t) => (0, build_from_enum_1.buildFromEnum)(t));
16
+ const http_client = (0, build_api_client_1.buildAPIClient)(source.list_api);
17
+ return {
18
+ http_client,
19
+ api: {
20
+ files: list_api_output.reduce((accumulator, o) => [...accumulator, ...o.files], []),
21
+ map: list_api_output.reduce((accumulator, o) => (Object.assign(Object.assign({}, accumulator), o.map)), {})
22
+ },
23
+ schema: {
24
+ files: list_schema_output.reduce((accumulator, o) => [...accumulator, ...o.files], []),
25
+ map: list_schema_output.reduce((accumulator, o) => (Object.assign(Object.assign({}, accumulator), o.map)), {})
26
+ },
27
+ table: {
28
+ files: list_table_output.reduce((accumulator, o) => [...accumulator, ...o.files], []),
29
+ map: list_table_output.reduce((accumulator, o) => (Object.assign(Object.assign({}, accumulator), o.map)), {})
30
+ },
31
+ enum: {
32
+ files: list_enume_output.reduce((accumulator, o) => [...accumulator, ...o.files], []),
33
+ map: list_enume_output.reduce((accumulator, o) => (Object.assign(Object.assign({}, accumulator), o.map)), {})
34
+ }
35
+ };
36
+ }
37
+ TypeORMModel.compile = compile;
38
+ })(TypeORMModel || (exports.TypeORMModel = TypeORMModel = {}));
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@naiv/codegen-axios-client",
3
+ "version": "0.0.1",
4
+ "main": "dist/index.js",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "scripts": {
9
+ "build": "rm -rf dist && tsc && npm unlink -g && npm link",
10
+ "start": "node dist",
11
+ "dev": "npm run build && npm start",
12
+ "test": "npm run dev"
13
+ },
14
+ "bin": {
15
+ "codegen-axios-client": "dist/exec.js"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "package.json"
20
+ ],
21
+ "keywords": [],
22
+ "author": "",
23
+ "license": "ISC",
24
+ "description": "",
25
+ "devDependencies": {
26
+ "@types/lodash": "^4.17.13",
27
+ "@types/node": "^22.8.1",
28
+ "typescript": "^5.6.3"
29
+ },
30
+ "dependencies": {
31
+ "@naiv/core": "^0.0.10",
32
+ "arg": "^5.0.2",
33
+ "lodash": "^4.17.21"
34
+ }
35
+ }