namirasoft-node 1.4.102 → 1.4.104

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