namirasoft-node 1.4.2 → 1.4.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.
@@ -1,427 +1,428 @@
1
- import express, { Router } from 'express';
2
- import cors from "cors";
3
- import * as fs from "fs";
4
- import * as path from 'path';
5
- import serveIndex from "serve-index";
6
- import swaggerUi from 'swagger-ui-express';
7
- import swaggerJSDoc from 'swagger-jsdoc';
8
- import cookieParser from 'cookie-parser';
9
- import { BaseDatabase } from './BaseDatabase';
10
- import { ILogger } from "namirasoft-log";
11
- import { BaseApplicationLink } from './BaseApplicationLink';
12
- import { EnvService, HTTPMethod, ObjectService, PackageService } from 'namirasoft-core';
13
- import { ApplicationSchema, BaseVariableSchema, ObjectSchema, SwaggerApplicationBuilder } from 'namirasoft-schema';
14
- import { BaseController } from './BaseController';
15
- import { BaseCron } from './BaseCron';
16
-
17
- export abstract class BaseApplication<D extends BaseDatabase>
18
- {
19
- private linkLoader?: () => Promise<void>;
20
- private links: BaseApplicationLink[] = [];
21
- protected name_asset: string;
22
- protected name_page: string;
23
- protected base_path: string;
24
- protected dir_asset: string;
25
- protected dir_page: string;
26
- protected dir_swagger: string;
27
- protected path_asset: string;
28
- protected path_page: string;
29
- protected path_swagger: string;
30
- protected pkg: PackageService;
31
- protected title: string;
32
- protected description: string;
33
- protected logo: string;
34
- protected version: string;
35
- protected mode!: string;
36
- public express!: express.Express;
37
- public database!: D;
38
- public logger: ILogger;
39
- public cookies: boolean = false;
40
- constructor(base_path: string)
41
- {
42
- this.base_path = base_path;
43
- this.name_asset = "asset";
44
- this.name_page = "page";
45
- this.dir_asset = "./" + this.name_asset;
46
- this.dir_page = "./" + this.name_page;
47
- this.dir_swagger = "./swagger";
48
- this.path_asset = base_path + "/" + this.name_asset;
49
- this.path_page = base_path + "/" + this.name_page;
50
- this.path_swagger = this.path_page + "/swagger";
51
- this.pkg = PackageService.getMain();
52
- this.title = this.pkg?.getTitle() ?? "";
53
- this.description = this.pkg?.getDescription() ?? "";
54
- this.logo = this.pkg?.getLogo() ?? "";
55
- this.version = this.pkg?.getVersion() ?? "";
56
- this.mode = new EnvService("SERVER_MODE", false).getString("api").toLowerCase();
57
- this.logger = this.getILogger();
58
- this.addLink = this.addLink.bind(this);
59
- this.addLink_Asset = this.addLink_Asset.bind(this);
60
- this.addLink_Page = this.addLink_Page.bind(this);
61
- this.addLink_Swagger = this.addLink_Swagger.bind(this);
62
-
63
- // create folders
64
- this.dir_asset = path.join(path.dirname(this.pkg.getPath()), this.dir_asset);
65
- this.dir_page = path.join(path.dirname(this.pkg.getPath()), this.dir_page);
66
- this.dir_swagger = path.join(path.dirname(this.pkg.getPath()), this.dir_swagger);
67
- if (!fs.existsSync(this.dir_asset))
68
- fs.mkdirSync(this.dir_asset);
69
- if (!fs.existsSync(this.dir_page))
70
- fs.mkdirSync(this.dir_page);
71
- if (!fs.existsSync(this.dir_swagger))
72
- fs.mkdirSync(this.dir_swagger, { recursive: true });
73
- }
74
- public abstract getDatabase(): D;
75
- public getOtherDatabases(): BaseDatabase[]
76
- {
77
- return [];
78
- }
79
- protected abstract getILogger(): ILogger;
80
- protected abstract getPort(): number;
81
- protected abstract getControllers(): any[];
82
- protected abstract getTables(): any[];
83
- protected abstract getCrons(): any[];
84
- protected async foreachController(handler: (generator: (req: express.Request, res: express.Response) => any) => Promise<boolean>)
85
- {
86
- let controllers = this.getControllers();
87
- for (let i = 0; i < controllers.length; i++)
88
- {
89
- const Template = controllers[i] as any;
90
- let con = await handler((req: express.Request, res: express.Response) =>
91
- {
92
- if (ObjectService.isClass(Template))
93
- return new Template(this, req, res);
94
- return Template(this, req, res);
95
- });
96
- if (!con)
97
- break;
98
- }
99
- }
100
- protected async foreachCron(handler: (generator: () => any) => Promise<boolean>)
101
- {
102
- let crons = this.getCrons();
103
- for (let i = 0; i < crons.length; i++)
104
- {
105
- try
106
- {
107
- const Template = crons[i] as any;
108
- let con = await handler(() =>
109
- {
110
- if (ObjectService.isClass(Template))
111
- return new Template(this);
112
- return Template(this);
113
- });
114
- if (!con)
115
- break;
116
- } catch (error)
117
- {
118
- this.logger.onCatchError(error);
119
- }
120
- }
121
- }
122
- // start
123
- async start()
124
- {
125
- this.logger.info("Application was started.");
126
- await this.startCrashHandler();
127
- await this.startDatabase();
128
- if (!process.env.NAMIRASOFT_MUTE)
129
- {
130
- await this.onBeforeStart();
131
- if (this.mode == "api")
132
- {
133
- await this.startExpress();
134
- await this.startCrons();
135
- await this.createSwagger();
136
- await this.startSwagger();
137
- await this.startHomePage();
138
- await this.createAssets();
139
- await this.startAssets();
140
- await this.createPages();
141
- await this.startPages();
142
- }
143
- await this.startOthers();
144
- await this.onAfterStart();
145
- }
146
- else
147
- {
148
- await this.saveSchema();
149
- }
150
- }
151
- protected async startCrashHandler(): Promise<void>
152
- {
153
- if (process.env.NAMIRASOFT_MUTE)
154
- return;
155
-
156
- process.on('unhandledRejection', (reason) =>
157
- {
158
- if (reason instanceof Error)
159
- this.logger.onCatchCritical(reason);
160
- else
161
- this.logger.critical(reason + "");
162
- });
163
- process.on('uncaughtException', (error) =>
164
- {
165
- this.logger.onCatchFatal(error);
166
- });
167
- }
168
- protected async startDatabase(): Promise<void>
169
- {
170
- this.database = this.getDatabase();
171
- this.database.init();
172
- this.database.connect();
173
- await this.database.sync(false);
174
- this.logger.success("Database was connected.");
175
- }
176
- protected async onBeforeStart(): Promise<void>
177
- { }
178
- protected async startExpress(): Promise<void>
179
- {
180
- if (!process.env.NAMIRASOFT_MUTE)
181
- {
182
- this.express = express();
183
- // Express
184
- this.express.use(express.static('static'));
185
- // Cors
186
- this.express.use(cors({ exposedHeaders: '*' }));
187
- // api routes
188
- this.express.use('/', await this.getRouter());
189
- // cookie
190
- if (this.cookies)
191
- this.express.use(cookieParser());
192
- // start server
193
- const port = this.getPort();
194
- this.express.listen(port, async () =>
195
- {
196
- this.logger.success(`Server is listening on port ${port}`);
197
- });
198
- }
199
- }
200
- protected async startCrons(): Promise<void>
201
- {
202
- if (!process.env.NAMIRASOFT_MUTE)
203
- {
204
- this.foreachCron(async generator =>
205
- {
206
- const template = generator() as BaseCron<D>;
207
- template.run();
208
- return true;
209
- });
210
- }
211
- }
212
- protected async createSwagger(): Promise<void>
213
- {
214
- let schema = await this.getSchema<BaseController<BaseDatabase, {}, {}, {}>>(c => c.generate_swagger);
215
- let builder = new SwaggerApplicationBuilder(schema);
216
- let result = await builder.run();
217
- for (let name of Object.keys(result.controllers))
218
- {
219
- const lines = result.controllers[name];
220
- fs.writeFileSync(this.dir_swagger + "/controller_" + name + ".swg", lines.join("\n"));
221
- }
222
- for (let name of Object.keys(result.classes))
223
- {
224
- const lines = result.classes[name];
225
- fs.writeFileSync(this.dir_swagger + "/model_" + name + ".swg", lines.join("\n"));
226
- }
227
- }
228
- protected async startSwagger(): Promise<void>
229
- {
230
- const joptions = {
231
- definition: {
232
- openapi: "3.0.1",
233
- info: {
234
- title: this.title,
235
- description: this.description,
236
- version: this.version,
237
- // license: {
238
- // name: "MIT",
239
- // url: "https://spdx.org/licenses/MIT.html",
240
- // },
241
- // contact: {
242
- // name: "Amir Abolhasani",
243
- // url: "https://namirasoft.com",
244
- // email: "accounts@namirasoft.com",
245
- // },
246
- },
247
- servers: [
248
- {
249
- url: this.base_path,
250
- },
251
- ],
252
- },
253
- apis: [this.dir_swagger + '/*.swg'],
254
- };
255
- const swaggerSpec = swaggerJSDoc(joptions);
256
- var options = {
257
- explorer: true
258
- };
259
- this.express.use(this.path_swagger + "/", swaggerUi.serve, swaggerUi.setup(swaggerSpec, options));
260
- }
261
- protected async startHomePage(): Promise<void>
262
- {
263
- this.express.get(this.base_path + "/", (req, res) =>
264
- {
265
- this.handleHomePage(req, res);
266
- });
267
- }
268
- protected abstract handleHomePage(_: express.Request, __: express.Response): Promise<void>;
269
- public getDirOfAsset(name: string)
270
- {
271
- return this.dir_asset + "/" + name;
272
- }
273
- public getPathOfAsset(name: string)
274
- {
275
- return this.path_asset + "/" + name;
276
- }
277
- protected async createAssets(): Promise<void>
278
- { }
279
- protected async startAssets(): Promise<void>
280
- {
281
- this.express.use(this.path_asset + '/',
282
- express.static(this.name_asset, { dotfiles: "allow" }),
283
- serveIndex(this.name_asset, { icons: true, view: "details", hidden: true }));
284
- }
285
- public getDirOfPage(name: string)
286
- {
287
- return this.dir_page + "/" + name;
288
- }
289
- public getPathOfPage(name: string)
290
- {
291
- return this.path_page + "/" + name;
292
- }
293
- protected async createPages(): Promise<void>
294
- { }
295
- protected async startPages(): Promise<void>
296
- {
297
- this.express.use(this.path_page + '/',
298
- express.static(this.name_page, {
299
- dotfiles: "allow", index: false, extensions: ['html']
300
- }),
301
- serveIndex(this.name_page, {
302
- icons: true,
303
- view: "details",
304
- hidden: false,
305
- filter: (filename) => { return filename.endsWith('.html'); }
306
-
307
- }));
308
- }
309
- protected async startOthers(): Promise<void>
310
- { }
311
- protected async onAfterStart(): Promise<void>
312
- { }
313
- protected async getRouter(): Promise<Router>
314
- {
315
- const router = express.Router({ mergeParams: true });
316
- await this.foreachController(async generator =>
317
- {
318
- try
319
- {
320
- const template = generator(null as any, null as any);
321
- let info = template.getInfo();
322
- let handlers = [];
323
- if (template.bodyAs.json.enabled)
324
- handlers.push(express.json({ limit: template.bodyAs.json.limit }));
325
- if (template.bodyAs.raw.enabled)
326
- handlers.push(express.raw({ type: template.bodyAs.raw.type }));
327
- handlers.push((req: express.Request, res: express.Response) =>
328
- {
329
- let controller = generator(req, res);
330
- controller.run();
331
- });
332
- let path = this.base_path + info.path;
333
- let ps: BaseVariableSchema[] = await template.getParametersSchema();
334
- for (let p of ps)
335
- path = path.replace(`{${p.name}}`, `:${p.name}`);
336
- if (info.method == HTTPMethod.GET)
337
- router.get(path, ...handlers);
338
- else if (info.method == HTTPMethod.POST)
339
- router.post(path, ...handlers);
340
- else if (info.method == HTTPMethod.PUT)
341
- router.put(path, ...handlers);
342
- else if (info.method == HTTPMethod.DELETE)
343
- router.delete(path, ...handlers);
344
- else
345
- return false;
346
- } catch (error)
347
- {
348
- this.logger.onCatchError(error);
349
- }
350
- return true;
351
- });
352
- return router;
353
- }
354
- // schema
355
- protected async saveSchema()
356
- {
357
- let app_schema = await this.getSchema<BaseController<BaseDatabase, {}, {}, {}>>(c => c.generate_sdk);
358
- app_schema.toFile("./application.schema");
359
- }
360
- async getSchema<C>(filter: (controller: C) => boolean): Promise<ApplicationSchema>
361
- {
362
- let schema = new ApplicationSchema(this.pkg);
363
- await this.foreachController(async generator =>
364
- {
365
- const template = generator(null as any, null as any);
366
- template.database = this.database;
367
- if (template instanceof BaseController)
368
- if (!filter || filter(template as C))
369
- schema.controllers.push(await template.getSchema());
370
- return true;
371
- });
372
- let tables = this.getTables();
373
- for (let i = 0; i < tables.length; i++)
374
- {
375
- const table = tables[i];
376
- let obj = table.getSchema(true, null) as ObjectSchema;
377
- schema.tables.push(obj);
378
- }
379
- schema.check();
380
- return schema;
381
- }
382
- // public
383
- async getLinks(): Promise<BaseApplicationLink[]>
384
- {
385
- if (this.linkLoader)
386
- {
387
- this.links = [];
388
- await this.linkLoader();
389
- }
390
- return this.links;
391
- }
392
- setLinkLoader(linkLoader: () => Promise<void>)
393
- {
394
- this.linkLoader = linkLoader;
395
- }
396
- addLink(link: BaseApplicationLink)
397
- {
398
- this.links.push(link);
399
- }
400
- addLink_Asset()
401
- {
402
- this.addLink({
403
- name: "Assets",
404
- url: this.path_asset + "/",
405
- logo: "https://static.namirasoft.com/image/concept/file/blue-yellow.png",
406
- description: "This shows the list of all assets of this API"
407
- });
408
- }
409
- addLink_Page()
410
- {
411
- this.addLink({
412
- name: "Pages",
413
- url: this.path_page + "/",
414
- logo: "https://static.namirasoft.com/image/concept/page/gray.png",
415
- description: "This shows the list of all pages of this API"
416
- });
417
- }
418
- addLink_Swagger()
419
- {
420
- this.addLink({
421
- name: "Swagger",
422
- url: this.path_swagger + "/",
423
- logo: "https://static.namirasoft.com/image/application/swagger/logo/base.png",
424
- description: this.description + " Swagger"
425
- });
426
- }
1
+ import express, { Router } from 'express';
2
+ import cors from "cors";
3
+ import * as fs from "fs";
4
+ import * as path from 'path';
5
+ import serveIndex from "serve-index";
6
+ import swaggerUi from 'swagger-ui-express';
7
+ import swaggerJSDoc from 'swagger-jsdoc';
8
+ import cookieParser from 'cookie-parser';
9
+ import { BaseDatabase } from './BaseDatabase';
10
+ import { ILogger } from "namirasoft-log";
11
+ import { BaseApplicationLink } from './BaseApplicationLink';
12
+ import { EnvService, HTTPMethod, ObjectService, PackageService } from 'namirasoft-core';
13
+ import { ApplicationSchema, BaseVariableSchema, ObjectSchema, SwaggerApplicationBuilder } from 'namirasoft-schema';
14
+ import { BaseController } from './BaseController';
15
+ import { BaseCron } from './BaseCron';
16
+
17
+ export abstract class BaseApplication<D extends BaseDatabase>
18
+ {
19
+ private linkLoader?: () => Promise<void>;
20
+ private links: BaseApplicationLink[] = [];
21
+ protected name_asset: string;
22
+ protected name_page: string;
23
+ protected base_path: string;
24
+ protected dir_asset: string;
25
+ protected dir_page: string;
26
+ protected dir_swagger: string;
27
+ protected path_asset: string;
28
+ protected path_page: string;
29
+ protected path_swagger: string;
30
+ protected pkg: PackageService;
31
+ protected title: string;
32
+ protected description: string;
33
+ protected logo: string;
34
+ protected version: string;
35
+ protected mode!: string;
36
+ public express!: express.Express;
37
+ public database!: D;
38
+ public logger: ILogger;
39
+ public cookies: boolean = false;
40
+ constructor(base_path: string)
41
+ {
42
+ this.base_path = base_path;
43
+ this.name_asset = "asset";
44
+ this.name_page = "page";
45
+ this.dir_asset = "./" + this.name_asset;
46
+ this.dir_page = "./" + this.name_page;
47
+ this.dir_swagger = "./swagger";
48
+ this.path_asset = base_path + "/" + this.name_asset;
49
+ this.path_page = base_path + "/" + this.name_page;
50
+ this.path_swagger = this.path_page + "/swagger";
51
+ this.pkg = PackageService.getMain();
52
+ this.title = this.pkg?.getTitle() ?? "";
53
+ this.description = this.pkg?.getDescription() ?? "";
54
+ this.logo = this.pkg?.getLogo() ?? "";
55
+ this.version = this.pkg?.getVersion() ?? "";
56
+ this.mode = new EnvService("SERVER_MODE", false).getString("api").toLowerCase();
57
+ this.logger = this.getILogger();
58
+ this.addLink = this.addLink.bind(this);
59
+ this.addLink_Asset = this.addLink_Asset.bind(this);
60
+ this.addLink_Page = this.addLink_Page.bind(this);
61
+ this.addLink_Swagger = this.addLink_Swagger.bind(this);
62
+
63
+ // create folders
64
+ this.dir_asset = path.join(path.dirname(this.pkg.getPath()), this.dir_asset);
65
+ this.dir_page = path.join(path.dirname(this.pkg.getPath()), this.dir_page);
66
+ this.dir_swagger = path.join(path.dirname(this.pkg.getPath()), this.dir_swagger);
67
+ if (!fs.existsSync(this.dir_asset))
68
+ fs.mkdirSync(this.dir_asset);
69
+ if (!fs.existsSync(this.dir_page))
70
+ fs.mkdirSync(this.dir_page);
71
+ if (!fs.existsSync(this.dir_swagger))
72
+ fs.mkdirSync(this.dir_swagger, { recursive: true });
73
+ }
74
+ public abstract getDatabase(): D;
75
+ public getOtherDatabases(): BaseDatabase[]
76
+ {
77
+ return [];
78
+ }
79
+ protected abstract getILogger(): ILogger;
80
+ protected abstract getPort(): number;
81
+ protected abstract getControllers(): any[];
82
+ protected abstract getTables(): any[];
83
+ protected abstract getCrons(): any[];
84
+ protected async foreachController(handler: (generator: (req: express.Request, res: express.Response) => any) => Promise<boolean>)
85
+ {
86
+ let controllers = this.getControllers();
87
+ for (let i = 0; i < controllers.length; i++)
88
+ {
89
+ const Template = controllers[i] as any;
90
+ let con = await handler((req: express.Request, res: express.Response) =>
91
+ {
92
+ if (ObjectService.isClass(Template))
93
+ return new Template(this, req, res);
94
+ return Template(this, req, res);
95
+ });
96
+ if (!con)
97
+ break;
98
+ }
99
+ }
100
+ protected async foreachCron(handler: (generator: () => any) => Promise<boolean>)
101
+ {
102
+ let crons = this.getCrons();
103
+ for (let i = 0; i < crons.length; i++)
104
+ {
105
+ try
106
+ {
107
+ const Template = crons[i] as any;
108
+ let con = await handler(() =>
109
+ {
110
+ if (ObjectService.isClass(Template))
111
+ return new Template(this);
112
+ return Template(this);
113
+ });
114
+ if (!con)
115
+ break;
116
+ } catch (error)
117
+ {
118
+ this.logger.onCatchError(error);
119
+ }
120
+ }
121
+ }
122
+ // start
123
+ async start()
124
+ {
125
+ this.logger.info("Application was started.");
126
+ await this.startCrashHandler();
127
+ await this.startDatabase();
128
+ if (!process.env.NAMIRASOFT_MUTE)
129
+ {
130
+ await this.onBeforeStart();
131
+ if (this.mode == "api")
132
+ {
133
+ await this.startExpress();
134
+ await this.startCrons();
135
+ await this.createSwagger();
136
+ await this.startSwagger();
137
+ await this.startHomePage();
138
+ await this.createAssets();
139
+ await this.startAssets();
140
+ await this.createPages();
141
+ await this.startPages();
142
+ }
143
+ await this.startOthers();
144
+ await this.onAfterStart();
145
+ }
146
+ else
147
+ {
148
+ await this.saveSchema();
149
+ }
150
+ }
151
+ protected async startCrashHandler(): Promise<void>
152
+ {
153
+ if (process.env.NAMIRASOFT_MUTE)
154
+ return;
155
+
156
+ process.on('unhandledRejection', (reason) =>
157
+ {
158
+ if (reason instanceof Error)
159
+ this.logger.onCatchCritical(reason);
160
+ else
161
+ this.logger.critical(reason + "");
162
+ });
163
+ process.on('uncaughtException', (error) =>
164
+ {
165
+ this.logger.onCatchFatal(error);
166
+ });
167
+ }
168
+ protected async startDatabase(): Promise<void>
169
+ {
170
+ this.database = this.getDatabase();
171
+ await this.database.init();
172
+ this.database.connect();
173
+ await this.database.sync(false);
174
+ await this.database.fill();
175
+ this.logger.success("Database was connected.");
176
+ }
177
+ protected async onBeforeStart(): Promise<void>
178
+ { }
179
+ protected async startExpress(): Promise<void>
180
+ {
181
+ if (!process.env.NAMIRASOFT_MUTE)
182
+ {
183
+ this.express = express();
184
+ // Express
185
+ this.express.use(express.static('static'));
186
+ // Cors
187
+ this.express.use(cors({ exposedHeaders: '*' }));
188
+ // api routes
189
+ this.express.use('/', await this.getRouter());
190
+ // cookie
191
+ if (this.cookies)
192
+ this.express.use(cookieParser());
193
+ // start server
194
+ const port = this.getPort();
195
+ this.express.listen(port, async () =>
196
+ {
197
+ this.logger.success(`Server is listening on port ${port}`);
198
+ });
199
+ }
200
+ }
201
+ protected async startCrons(): Promise<void>
202
+ {
203
+ if (!process.env.NAMIRASOFT_MUTE)
204
+ {
205
+ this.foreachCron(async generator =>
206
+ {
207
+ const template = generator() as BaseCron<D>;
208
+ template.run();
209
+ return true;
210
+ });
211
+ }
212
+ }
213
+ protected async createSwagger(): Promise<void>
214
+ {
215
+ let schema = await this.getSchema<BaseController<BaseDatabase, {}, {}, {}>>(c => c.generate_swagger);
216
+ let builder = new SwaggerApplicationBuilder(schema);
217
+ let result = await builder.run();
218
+ for (let name of Object.keys(result.controllers))
219
+ {
220
+ const lines = result.controllers[name];
221
+ fs.writeFileSync(this.dir_swagger + "/controller_" + name + ".swg", lines.join("\n"));
222
+ }
223
+ for (let name of Object.keys(result.classes))
224
+ {
225
+ const lines = result.classes[name];
226
+ fs.writeFileSync(this.dir_swagger + "/model_" + name + ".swg", lines.join("\n"));
227
+ }
228
+ }
229
+ protected async startSwagger(): Promise<void>
230
+ {
231
+ const joptions = {
232
+ definition: {
233
+ openapi: "3.0.1",
234
+ info: {
235
+ title: this.title,
236
+ description: this.description,
237
+ version: this.version,
238
+ // license: {
239
+ // name: "MIT",
240
+ // url: "https://spdx.org/licenses/MIT.html",
241
+ // },
242
+ // contact: {
243
+ // name: "Amir Abolhasani",
244
+ // url: "https://namirasoft.com",
245
+ // email: "accounts@namirasoft.com",
246
+ // },
247
+ },
248
+ servers: [
249
+ {
250
+ url: this.base_path,
251
+ },
252
+ ],
253
+ },
254
+ apis: [this.dir_swagger + '/*.swg'],
255
+ };
256
+ const swaggerSpec = swaggerJSDoc(joptions);
257
+ var options = {
258
+ explorer: true
259
+ };
260
+ this.express.use(this.path_swagger + "/", swaggerUi.serve, swaggerUi.setup(swaggerSpec, options));
261
+ }
262
+ protected async startHomePage(): Promise<void>
263
+ {
264
+ this.express.get(this.base_path + "/", (req, res) =>
265
+ {
266
+ this.handleHomePage(req, res);
267
+ });
268
+ }
269
+ protected abstract handleHomePage(_: express.Request, __: express.Response): Promise<void>;
270
+ public getDirOfAsset(name: string)
271
+ {
272
+ return this.dir_asset + "/" + name;
273
+ }
274
+ public getPathOfAsset(name: string)
275
+ {
276
+ return this.path_asset + "/" + name;
277
+ }
278
+ protected async createAssets(): Promise<void>
279
+ { }
280
+ protected async startAssets(): Promise<void>
281
+ {
282
+ this.express.use(this.path_asset + '/',
283
+ express.static(this.name_asset, { dotfiles: "allow" }),
284
+ serveIndex(this.name_asset, { icons: true, view: "details", hidden: true }));
285
+ }
286
+ public getDirOfPage(name: string)
287
+ {
288
+ return this.dir_page + "/" + name;
289
+ }
290
+ public getPathOfPage(name: string)
291
+ {
292
+ return this.path_page + "/" + name;
293
+ }
294
+ protected async createPages(): Promise<void>
295
+ { }
296
+ protected async startPages(): Promise<void>
297
+ {
298
+ this.express.use(this.path_page + '/',
299
+ express.static(this.name_page, {
300
+ dotfiles: "allow", index: false, extensions: ['html']
301
+ }),
302
+ serveIndex(this.name_page, {
303
+ icons: true,
304
+ view: "details",
305
+ hidden: false,
306
+ filter: (filename) => { return filename.endsWith('.html'); }
307
+
308
+ }));
309
+ }
310
+ protected async startOthers(): Promise<void>
311
+ { }
312
+ protected async onAfterStart(): Promise<void>
313
+ { }
314
+ protected async getRouter(): Promise<Router>
315
+ {
316
+ const router = express.Router({ mergeParams: true });
317
+ await this.foreachController(async generator =>
318
+ {
319
+ try
320
+ {
321
+ const template = generator(null as any, null as any);
322
+ let info = template.getInfo();
323
+ let handlers = [];
324
+ if (template.bodyAs.json.enabled)
325
+ handlers.push(express.json({ limit: template.bodyAs.json.limit }));
326
+ if (template.bodyAs.raw.enabled)
327
+ handlers.push(express.raw({ type: template.bodyAs.raw.type }));
328
+ handlers.push((req: express.Request, res: express.Response) =>
329
+ {
330
+ let controller = generator(req, res);
331
+ controller.run();
332
+ });
333
+ let path = this.base_path + info.path;
334
+ let ps: BaseVariableSchema[] = await template.getParametersSchema();
335
+ for (let p of ps)
336
+ path = path.replace(`{${p.name}}`, `:${p.name}`);
337
+ if (info.method == HTTPMethod.GET)
338
+ router.get(path, ...handlers);
339
+ else if (info.method == HTTPMethod.POST)
340
+ router.post(path, ...handlers);
341
+ else if (info.method == HTTPMethod.PUT)
342
+ router.put(path, ...handlers);
343
+ else if (info.method == HTTPMethod.DELETE)
344
+ router.delete(path, ...handlers);
345
+ else
346
+ return false;
347
+ } catch (error)
348
+ {
349
+ this.logger.onCatchError(error);
350
+ }
351
+ return true;
352
+ });
353
+ return router;
354
+ }
355
+ // schema
356
+ protected async saveSchema()
357
+ {
358
+ let app_schema = await this.getSchema<BaseController<BaseDatabase, {}, {}, {}>>(c => c.generate_sdk);
359
+ app_schema.toFile("./application.schema");
360
+ }
361
+ async getSchema<C>(filter: (controller: C) => boolean): Promise<ApplicationSchema>
362
+ {
363
+ let schema = new ApplicationSchema(this.pkg);
364
+ await this.foreachController(async generator =>
365
+ {
366
+ const template = generator(null as any, null as any);
367
+ template.database = this.database;
368
+ if (template instanceof BaseController)
369
+ if (!filter || filter(template as C))
370
+ schema.controllers.push(await template.getSchema());
371
+ return true;
372
+ });
373
+ let tables = this.getTables();
374
+ for (let i = 0; i < tables.length; i++)
375
+ {
376
+ const table = tables[i];
377
+ let obj = table.getSchema(true, null) as ObjectSchema;
378
+ schema.tables.push(obj);
379
+ }
380
+ schema.check();
381
+ return schema;
382
+ }
383
+ // public
384
+ async getLinks(): Promise<BaseApplicationLink[]>
385
+ {
386
+ if (this.linkLoader)
387
+ {
388
+ this.links = [];
389
+ await this.linkLoader();
390
+ }
391
+ return this.links;
392
+ }
393
+ setLinkLoader(linkLoader: () => Promise<void>)
394
+ {
395
+ this.linkLoader = linkLoader;
396
+ }
397
+ addLink(link: BaseApplicationLink)
398
+ {
399
+ this.links.push(link);
400
+ }
401
+ addLink_Asset()
402
+ {
403
+ this.addLink({
404
+ name: "Assets",
405
+ url: this.path_asset + "/",
406
+ logo: "https://static.namirasoft.com/image/concept/file/blue-yellow.png",
407
+ description: "This shows the list of all assets of this API"
408
+ });
409
+ }
410
+ addLink_Page()
411
+ {
412
+ this.addLink({
413
+ name: "Pages",
414
+ url: this.path_page + "/",
415
+ logo: "https://static.namirasoft.com/image/concept/page/gray.png",
416
+ description: "This shows the list of all pages of this API"
417
+ });
418
+ }
419
+ addLink_Swagger()
420
+ {
421
+ this.addLink({
422
+ name: "Swagger",
423
+ url: this.path_swagger + "/",
424
+ logo: "https://static.namirasoft.com/image/application/swagger/logo/base.png",
425
+ description: this.description + " Swagger"
426
+ });
427
+ }
427
428
  }