pwi-plata-type 0.3.4 → 0.3.7

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/Dockerfile CHANGED
@@ -1,18 +1,13 @@
1
- FROM node:16-alpine AS build
1
+ FROM node:16-alpine
2
2
 
3
3
  WORKDIR /usr/src/app
4
4
 
5
- COPY . ./
6
-
7
- RUN npm ci --only=production && \
8
- npm run build
9
-
10
- FROM node:16-alpine AS bin
5
+ COPY package*.json ./
11
6
 
12
7
  EXPOSE 3050
13
8
 
14
- WORKDIR /usr/src/app
9
+ RUN npm ci --only=production
15
10
 
16
- COPY --from=build /usr/src/app/build .
11
+ COPY . ./
17
12
 
18
13
  CMD [ "npm", "start" ]
@@ -1,7 +1,7 @@
1
1
  import { spawn } from 'node:child_process'
2
2
  import fs from 'node:fs'
3
3
  import path from 'node:path'
4
- import { PlataResultado, PlataDirs, PlataFiles, PlataError } from '../../libs/tools.js';
4
+ import { PlataResultado, PlataDirs, PlataFiles, PlataError } from '../../libs/tools';
5
5
 
6
6
  export namespace tools {
7
7
  export interface ProcessExit {
@@ -14,7 +14,8 @@ export namespace tools {
14
14
  return new Promise((resolve) => {
15
15
  try {
16
16
  const p = spawn(command, args, {
17
- cwd: cwd
17
+ cwd: cwd,
18
+ shell: true
18
19
  })
19
20
 
20
21
  let stdout, stderr = ''
@@ -1,74 +1,144 @@
1
- import { tools } from "./plata-create-tools.js";
2
- import { PlataDirs } from "../../libs/tools.js"
1
+ import { tools } from "./plata-create-tools";
2
+ import { PlataDirs } from "../../libs/tools"
3
+ import { Command } from 'commander'
3
4
  import path from 'node:path'
4
5
 
5
- export async function h() {
6
- return tools.args.forEachArg(async (command, args) => {
6
+ const program = new Command()
7
+
8
+ program.name('Plata Create cli')
9
+ program.description('CLI usada para criar rotas, libs, models e muito mais na plata')
10
+ program.version(PlataDirs.PlataJson.version)
11
+
12
+ program.command('route <routes...>')
13
+ .description('Cria uma rota utilizando o templete da plata')
14
+ .action(async routes => {
15
+ if (!Array.isArray(routes)) {
16
+ return
17
+ }
18
+
19
+ const promises: any[] = []
20
+ const plataName = PlataDirs.ProjectJson.plata_name
21
+
22
+ for (const route of routes) {
23
+ const r = `${route}/`.replace(/:(.*?)(?:\/|$)/g, (_, parm) => {
24
+ return parm[parm.length - 1] !== '?' ? `{${parm}}/` : `[${parm.slice(0, -1)}]/`
25
+ })
26
+
27
+ const routeArg = r.slice(0, -1).split('/')
28
+
29
+ const routeFileName = routeArg[routeArg.length - 1] === '' ? 'index' : routeArg.pop()
30
+ const routeFilePath = path.join('routes', ...routeArg.filter(v => v !== ''))
31
+
32
+ promises.push(tools.files.deployFileToProject(
33
+ routeFilePath,
34
+ 'route',
35
+ `${routeFileName}.ts`,
36
+ { PlataName: `${plataName}` }
37
+ ).finally(() => console.log(
38
+ `Rota ${routeFilePath}/${routeFileName === 'index' ? '' : routeFileName} criada`
39
+ )))
40
+ }
41
+
42
+ await Promise.all(promises)
43
+ })
44
+ ;
45
+
46
+ program.command('lib <libs...>')
47
+ .description('Cria uma config com e uma lib utilizando o templete da plata')
48
+ .action(async libs => {
49
+ if (!Array.isArray(libs)) {
50
+ return
51
+ }
52
+
53
+ const promises: any[] = []
54
+
55
+ for (const lib of libs) {
56
+ promises.push(tools.files.deployFileToProject(
57
+ 'configs',
58
+ 'config',
59
+ `${lib}.ts`.toLowerCase(),
60
+ { Name: `${lib}`, name: `${lib}`.toLowerCase() }
61
+ ).finally(() => console.log(`Config ${lib} criada`)))
62
+
63
+ promises.push(tools.files.deployFileToProject(
64
+ 'libs',
65
+ 'lib',
66
+ `${lib}.ts`.toLowerCase(),
67
+ { Name: `${lib}`, name: `${lib}`.toLowerCase() }
68
+ ).finally(() => console.log(`Lib ${lib} criada`)))
69
+ }
70
+
71
+ await Promise.all(promises)
72
+ })
73
+ ;
74
+
75
+ program.command('config <configs...>')
76
+ .description('Cria uma config utilizando o templete da plata')
77
+ .action(async configs => {
78
+ if (!Array.isArray(configs)) {
79
+ return
80
+ }
81
+
82
+ const promises: any[] = []
83
+
84
+ for (const config of configs) {
85
+ promises.push(tools.files.deployFileToProject(
86
+ 'configs',
87
+ 'config',
88
+ `${config}.ts`.toLowerCase(),
89
+ { Name: `${config}`, name: `${config}`.toLowerCase() }
90
+ ).finally(() => console.log(`Config ${config} criada`)))
91
+ }
92
+
93
+ await Promise.all(promises)
94
+
95
+ })
96
+ ;
97
+
98
+ program.command('model <models...>')
99
+ .description('Cria um model utilizando o templete da plata')
100
+ .action(async models => {
101
+ if (!Array.isArray(models)) {
102
+ return
103
+ }
104
+
7
105
  const promises: any[] = []
106
+ const plataName = PlataDirs.ProjectJson.plata_name
8
107
 
9
- switch (command) {
10
- case 'lib':
11
- const nameLib = `${args.shift()}`
12
- promises.push(tools.files.deployFileToProject(
13
- 'configs',
14
- 'config',
15
- `${nameLib}.ts`.toLowerCase(),
16
- { Name: `${nameLib}`, name: `${nameLib}`.toLowerCase() }
17
- ).finally(() => console.log(`Config ${nameLib} criada`)))
18
-
19
- promises.push(tools.files.deployFileToProject(
20
- 'libs',
21
- 'lib',
22
- `${nameLib}.ts`.toLowerCase(),
23
- { Name: `${nameLib}`, name: `${nameLib}`.toLowerCase() }
24
- ).finally(() => console.log(`Lib ${nameLib} criada`)))
25
- break;
26
- case 'config':
27
- const nameConfig = `${args.shift()}`
28
- promises.push(tools.files.deployFileToProject(
29
- 'configs',
30
- 'config',
31
- `${nameConfig}.ts`.toLowerCase(),
32
- { Name: `${nameConfig}`, name: `${nameConfig}`.toLowerCase() }
33
- ).finally(() => console.log(`Config ${nameConfig} criada`)))
34
- break;
35
- case 'cluster':
36
- console.log('CLUSTER AINDA NÃO CRIANDO AINDA')
37
- break;
38
- case 'route':
39
- const r = `${args.shift()}/`.replace(/:(.*?)(?:\/|$)/g, (_, parm) => {
40
- return parm[parm.length - 1] !== '?' ? `{${parm}}/` : `[${parm.slice(0, -1)}]/`
41
- })
42
-
43
- const routeArg = r.slice(0, -1).split('/')
44
-
45
- const routeFileName = routeArg[routeArg.length - 1] === '' ? 'index' : routeArg.pop()
46
- const routeFilePath = path.join('routes', ...routeArg.filter(v => v !== ''))
47
-
48
- promises.push(tools.files.deployFileToProject(
49
- routeFilePath,
50
- 'route',
51
- `${routeFileName}.ts`,
52
- { PlataName: `${PlataDirs.ProjectJson.plata_name}` }
53
- ).finally(() => console.log(
54
- `Rota ${routeFilePath}/${routeFileName === 'index' ? '' : routeFileName} criada`
55
- )))
56
-
57
- break;
58
- case 'model':
59
- const modelName = `${args.shift()}`
60
- const plataName = PlataDirs.ProjectJson.plata_name
61
-
62
- promises.push(tools.files.deployFileToProject(
63
- 'models',
64
- 'model',
65
- `${modelName}.ts`.toLowerCase(),
66
- { Name: `${modelName}`, PlataName: `${plataName}` }
67
- ).finally(() => console.log(`Model ${modelName} criada`)))
68
- break;
108
+ for (const model of models) {
109
+ promises.push(tools.files.deployFileToProject(
110
+ 'models',
111
+ 'model',
112
+ `${model}.ts`.toLowerCase(),
113
+ { Name: `${model}`, PlataName: `${plataName}` }
114
+ ).finally(() => console.log(`Model ${model} criada`)))
69
115
  }
70
116
 
71
117
  await Promise.all(promises)
72
- return args
73
118
  })
74
- }
119
+ ;
120
+
121
+ program.command('task <tasks...>')
122
+ .description('Cria uma task utilizando o templete da plata')
123
+ .action(async tasks => {
124
+ if (!Array.isArray(tasks)) {
125
+ return
126
+ }
127
+
128
+ const promises: any[] = []
129
+ const plataName = PlataDirs.ProjectJson.plata_name
130
+
131
+ for (const task of tasks) {
132
+ promises.push(tools.files.deployFileToProject(
133
+ 'tasks',
134
+ 'task',
135
+ `${task}.ts`.toLowerCase(),
136
+ { Name: `${task}`, PlataName: `${plataName}` }
137
+ ).finally(() => console.log(`Task ${tasks} criada`)))
138
+ }
139
+
140
+ await Promise.all(promises)
141
+ })
142
+ ;
143
+
144
+ export const cli = program
@@ -1,41 +1,109 @@
1
- import { tools } from "./plata-create-tools.js";
1
+ import { tools } from "./plata-create-tools";
2
+ import { PlataDirs } from "../../libs/tools"
3
+ import { Command } from 'commander'
4
+
5
+ const program = new Command()
6
+
7
+ program.name('Plata Create cli')
8
+ program.description('CLI usada para criar rotas, libs, models e muito mais na plata')
9
+ program.version(PlataDirs.PlataJson.version)
10
+
11
+ program.command('lib <libs...>')
12
+ .description('Cria uma config com e uma lib utilizando o templete da plata')
13
+ .action(async libs => {
14
+ if (!Array.isArray(libs)) {
15
+ return
16
+ }
17
+
18
+ const promises: any[] = []
19
+
20
+ for (const lib of libs) {
21
+ promises.push(tools.files.deployFileToProject(
22
+ 'configs',
23
+ 'config',
24
+ `${lib}.ts`.toLowerCase(),
25
+ { Name: `${lib}`, name: `${lib}`.toLowerCase() }
26
+ ).finally(() => console.log(`Config ${lib} criada`)))
27
+
28
+ promises.push(tools.files.deployFileToProject(
29
+ 'libs',
30
+ 'lib',
31
+ `${lib}.ts`.toLowerCase(),
32
+ { Name: `${lib}`, name: `${lib}`.toLowerCase() }
33
+ ).finally(() => console.log(`Lib ${lib} criada`)))
34
+ }
35
+
36
+ await Promise.all(promises)
37
+ })
38
+ ;
39
+
40
+ program.command('config <configs...>')
41
+ .description('Cria uma config utilizando o templete da plata')
42
+ .action(async configs => {
43
+ if (!Array.isArray(configs)) {
44
+ return
45
+ }
46
+
47
+ const promises: any[] = []
48
+
49
+ for (const config of configs) {
50
+ promises.push(tools.files.deployFileToProject(
51
+ 'configs',
52
+ 'config',
53
+ `${config}.ts`.toLowerCase(),
54
+ { Name: `${config}`, name: `${config}`.toLowerCase() }
55
+ ).finally(() => console.log(`Config ${config} criada`)))
56
+ }
57
+
58
+ await Promise.all(promises)
59
+
60
+ })
61
+ ;
62
+
63
+ program.command('model <models...>')
64
+ .description('Cria um model utilizando o templete da plata')
65
+ .action(async models => {
66
+ if (!Array.isArray(models)) {
67
+ return
68
+ }
69
+
70
+ const promises: any[] = []
71
+ const plataName = PlataDirs.ProjectJson.plata_name
72
+
73
+ for (const model of models) {
74
+ promises.push(tools.files.deployFileToProject(
75
+ 'models',
76
+ 'model',
77
+ `${model}.ts`.toLowerCase(),
78
+ { Name: `${model}`, PlataName: `${plataName}` }
79
+ ).finally(() => console.log(`Model ${model} criada`)))
80
+ }
81
+
82
+ await Promise.all(promises)
83
+ })
84
+ ;
85
+
86
+ program.command('task <tasks...>')
87
+ .description('Cria uma task utilizando o templete da plata')
88
+ .action(async tasks => {
89
+ if (!Array.isArray(tasks)) {
90
+ return
91
+ }
2
92
 
3
- export async function h() {
4
- return tools.args.forEachArg(async (command, args) => {
5
93
  const promises: any[] = []
94
+ const plataName = PlataDirs.ProjectJson.plata_name
6
95
 
7
- switch (command) {
8
- case 'lib':
9
- const nameLib = args.shift()
10
- promises.push(tools.files.deployFileToProject(
11
- 'configs',
12
- 'config',
13
- `${nameLib}.ts`.toLowerCase(),
14
- { Name: `${nameLib}`, name: `${nameLib}`.toLowerCase() }
15
- ).finally(() => console.log(`Config ${nameLib} criada`)))
16
-
17
- promises.push(tools.files.deployFileToProject(
18
- 'libs',
19
- 'lib',
20
- `${nameLib}.ts`.toLowerCase(),
21
- { Name: `${nameLib}`, name: `${nameLib}`.toLowerCase() }
22
- ).finally(() => console.log(`Lib ${nameLib} criada`)))
23
- break;
24
- case 'config':
25
- const nameConfig = args.shift()
26
- promises.push(tools.files.deployFileToProject(
27
- 'configs',
28
- 'config',
29
- `${nameConfig}.ts`.toLowerCase(),
30
- { Name: `${nameConfig}`, name: `${nameConfig}`.toLowerCase() }
31
- ).finally(() => console.log(`Config ${nameConfig} criada`)))
32
- break;
33
- case 'cluster':
34
- console.log('CLUSTER AINDA NÃO CRIANDO AINDA')
35
- break;
96
+ for (const task of tasks) {
97
+ promises.push(tools.files.deployFileToProject(
98
+ 'tasks',
99
+ 'task',
100
+ `${task}.ts`.toLowerCase(),
101
+ { Name: `${task}`, PlataName: `${plataName}` }
102
+ ).finally(() => console.log(`Task ${tasks} criada`)))
36
103
  }
37
104
 
38
105
  await Promise.all(promises)
39
- return args
40
106
  })
41
- }
107
+ ;
108
+
109
+ export const cli = program
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
 
4
- import { PlataDirs, PlataFiles } from '../../libs/tools.js'
4
+ import { PlataDirs, PlataFiles } from '../../libs/tools'
5
5
 
6
6
  export namespace tools {
7
7
  export namespace files {
@@ -1,5 +1,5 @@
1
- import { tools } from './extras/plata-build-tool.js'
2
- import { PlataResultado, PlataDirs } from '../libs/tools.js'
1
+ import { tools } from './extras/plata-build-tool'
2
+ import { PlataResultado, PlataDirs } from '../libs/tools'
3
3
 
4
4
  const main = async () => {
5
5
  // Prepara o JSONs
@@ -1,34 +1,28 @@
1
- import { PlataDirs } from "../libs/tools.js";
1
+ import { PlataDirs } from "../libs/tools"
2
2
 
3
- interface Handler {
4
- h: () => Promise<void>
5
- }
3
+ import * as PlataCreateApi from "./extras/plata-create-api"
4
+ import * as PlataCreateLib from "./extras/plata-create-lib"
6
5
 
7
6
  const main = async () => {
8
- const projectPackage = await PlataDirs.ProjectJson
7
+ const projectPackage = PlataDirs.ProjectJson
9
8
 
10
9
  if (projectPackage.plata_no_setup !== undefined) {
11
10
  console.log('Existe o parametro plata_no_setup no package.json ou seja a plata não esta configurada')
12
11
  process.exit(0)
13
-
14
12
  }
15
13
 
16
- let handler: Handler
17
-
18
14
  switch(projectPackage.plata_type ?? 'api') {
19
15
  case 'api':
20
- handler = (await import(PlataDirs.getPlataBinExtraFile('plata-create-api.js'))) as unknown as Handler
16
+ await PlataCreateApi.cli.parseAsync(process.argv)
21
17
  break;
22
18
  case 'lib':
23
- handler = (await import(PlataDirs.getPlataBinExtraFile('plata-create-lib.js'))) as unknown as Handler
19
+ await PlataCreateLib.cli.parseAsync(process.argv)
24
20
  break;
25
21
  default:
26
22
  console.log(`tipo ${projectPackage.plata_type} não suportado pela plata`)
27
23
  process.exit(0)
28
24
  break;
29
25
  }
30
-
31
- await handler.h()
32
26
  }
33
27
 
34
28
  main()
@@ -0,0 +1,13 @@
1
+ import { tools } from './extras/plata-build-tool'
2
+ import { PlataDirs } from '../libs/tools'
3
+
4
+
5
+ const main = async () => {
6
+ console.log(await tools.runIn(
7
+ 'node',
8
+ [ 'postinstall.mjs' ],
9
+ PlataDirs.getPlataDir()
10
+ ))
11
+ }
12
+
13
+ main()
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path'
2
2
  import fs from 'node:fs'
3
- import { buildExpressRouter } from '../libs/routes.js'
4
- import { PlataResultado, PlataDirs, PlataFiles, PlataError } from '../libs/tools.js'
3
+ import { buildExpressRouter } from '../libs/routes'
4
+ import { PlataResultado, PlataDirs, PlataFiles, PlataError } from '../libs/tools'
5
5
 
6
6
  interface dumpParameter {
7
7
  name: string,
@@ -142,6 +142,9 @@ async function dumpRotas(): Promise<dumpRoute[]> {
142
142
  }
143
143
 
144
144
  const main = async () => {
145
+ // TODO :: Colocar isso em um function que inicializa a process._plata ou n usa isso mais
146
+ (process as any)._plata = new Object(null)
147
+
145
148
  const rotas = await dumpRotas()
146
149
  const files = loadSwaggerFiles()
147
150
 
package/bin/plata.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { PlataClusterManager, PlataClusterMsg } from "../libs/cluster.js"
2
- import { loadEnvProjectFile } from "../libs/env.js"
3
- import { buildExpressRouter } from "../libs/routes.js"
1
+ import { PlataClusterManager, PlataClusterMsg } from "../libs/cluster"
2
+ import { loadEnvProjectFile } from "../libs/env"
3
+ import { loadTasks } from "../libs/tasks"
4
+ import { buildExpressRouter } from "../libs/routes"
4
5
  import express, { Express } from "express"
5
6
  import { createServer } from 'node:https'
6
7
  import fs from 'node:fs'
7
- import { PlataDirs } from "../libs/tools.js"
8
+ import { PlataDirs } from "../libs/tools"
8
9
  import path from 'node:path'
9
10
 
10
11
  const main = async () => {
@@ -21,6 +22,8 @@ const main = async () => {
21
22
  }
22
23
  }
23
24
 
25
+ await loadTasks()
26
+
24
27
  console.log(process.env.ENV)
25
28
 
26
29
  clusterLib.run({
package/index.ts CHANGED
@@ -1,9 +1,10 @@
1
- import * as PlataCluster from './libs/cluster.js'
2
- import * as PlataEnv from './libs/env.js'
3
- import * as PlataRoutes from './libs/routes.js'
4
- import * as PlataTools from './libs/tools.js'
5
- import * as PlataModels from './libs/model.js'
6
- import { PlataSwagger } from './libs/swagger.js'
1
+ import * as PlataCluster from './libs/cluster'
2
+ import * as PlataEnv from './libs/env'
3
+ import * as PlataRoutes from './libs/routes'
4
+ import * as PlataTools from './libs/tools'
5
+ import * as PlataModels from './libs/model'
6
+ import * as PlataTasks from './libs/tasks'
7
+ import { PlataSwagger } from './libs/swagger'
7
8
 
8
9
  export {
9
10
  PlataCluster,
@@ -11,5 +12,6 @@ export {
11
12
  PlataRoutes,
12
13
  PlataTools,
13
14
  PlataModels,
14
- PlataSwagger
15
+ PlataSwagger,
16
+ PlataTasks
15
17
  }
package/libs/cluster.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { PlataRequire, PlataDirs, PlataFiles } from './tools.js'
1
+ import { PlataRequire, PlataDirs, PlataFiles } from './tools'
2
2
  import { cpus } from 'node:os'
3
3
  import * as typeCluster from 'node:cluster'
4
4
 
@@ -153,14 +153,14 @@ export class PlataClusterManager {
153
153
  [
154
154
  PlataDirs.getProjectDirClusters()
155
155
  ],
156
- `${process.env["_plata_name"]}.ts`
156
+ `${process.env["_plata_name"]}`
157
157
  ).catch(err => {
158
158
  console.error(err)
159
159
  return null
160
160
  })
161
161
 
162
162
  if (file !== null) {
163
- const config: PlataClusterWorkerConfig = (await import(`file:///${file}`.replace(/\\/g, '/'))).default
163
+ const config: PlataClusterWorkerConfig = (await import(file.replace(/\\/g, '/'))).default
164
164
 
165
165
  await config.onStart()
166
166
  }
package/libs/env.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { PlataDirs, PlataFiles } from "./tools.js"
1
+ import { PlataDirs, PlataFiles } from "./tools"
2
2
 
3
3
  export interface EnvConfig {
4
4
  readonly env: 'prod' | 'debug' | 'homolog' | string
@@ -6,7 +6,7 @@ export interface EnvConfig {
6
6
 
7
7
  export async function loadEnvProjectFile() {
8
8
  const config = process.env['ENV'] === undefined ?
9
- (await import(PlataDirs.getProjectConfigFileDir('env.js'))).default as EnvConfig
9
+ (await import(PlataDirs.getProjectConfigFileDir('env'))).default as EnvConfig
10
10
  : { env: process.env['ENV'] }
11
11
 
12
12
  return PlataFiles.readFileAsync(
package/libs/model.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { PlataError } from "./tools.js"
1
+ import { PlataError } from "./tools"
2
2
 
3
3
  export interface RetornoValidacaoPrimitivo {
4
4
  error?: PlataError
@@ -442,7 +442,7 @@ export function Telefone(): ModelValicacaoPrimitivo {
442
442
  }
443
443
  }
444
444
 
445
- if (v[0].length !== 2 || v[1].length > 9) {
445
+ if (v[0].length !== 2 || (v[1].length !== 8 && v[1].length !== 9)) {
446
446
  return {
447
447
  error: {
448
448
  errorID: "BPVTEL002",
@@ -481,7 +481,7 @@ export function TelefoneDDI(): ModelValicacaoPrimitivo {
481
481
  }
482
482
  }
483
483
 
484
- if (telefone[0].length !== 2 || telefone[1].length > 9) {
484
+ if (telefone[0].length !== 2 || (telefone[1].length !== 8 && telefone[1].length !== 9)) {
485
485
  return {
486
486
  error: {
487
487
  errorID: "BPVTELD002",
package/libs/routes.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path'
2
- import { PlataDirs, PlataRequire, PlataError } from "./tools.js";
2
+ import { PlataDirs, PlataRequire, PlataError } from "./tools";
3
3
  import express, { Router } from "express";
4
4
 
5
5
  export const HttpMethodsArray = [
@@ -206,7 +206,7 @@ export async function loadExpressRoutes(): Promise<PlataRequiredRoute[]> {
206
206
  r = r.map(route => {
207
207
  route.httpRoute = route.filePath
208
208
  .replace(PlataDirs.getProjectRoutesDir(), '')
209
- .replace(/.(ts|js)$/, '')
209
+ .replace(/\.ts|\.js$/, '')
210
210
  .replace(/index/, '')
211
211
  .replace(/\\/g, '/')
212
212
  .replace(/\{(.*?)\}/g, ':$1')
@@ -239,7 +239,7 @@ export async function loadExpressRoutes(): Promise<PlataRequiredRoute[]> {
239
239
  export async function buildExpressRouter(): Promise<_Router> {
240
240
  const router = Router() as _Router
241
241
  router._routes = []
242
- router.use(express.json())
242
+ router.use(express.json({ limit: process.env._PLATA_API_JSON_SIZE ?? '100kb' }))
243
243
 
244
244
  const routes = await loadExpressRoutes()
245
245
 
package/libs/swagger.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import swaggerUi from 'swagger-ui-express'
2
2
  import path from 'node:path'
3
- import { PlataRouterBuilder, PlataRequestHandler } from './routes.js';
4
- import { PlataFiles, PlataDirs } from "./tools.js";
3
+ import { PlataRouterBuilder, PlataRequestHandler } from './routes';
4
+ import { PlataFiles, PlataDirs } from "./tools";
5
5
 
6
6
  export namespace PlataSwagger {
7
7
  export const swagger: PlataRouterBuilder = async (router) => {
package/libs/tasks.ts ADDED
@@ -0,0 +1,157 @@
1
+ import * as schedule from 'node-schedule'
2
+ import { PlataResultado, PlataRequire, PlataDirs, PlataError } from './tools'
3
+
4
+ export type TaskRule = schedule.RecurrenceRule | schedule.RecurrenceSpecDateRange | schedule.RecurrenceSpecObjLit | Date | string | number
5
+ export type TaskCallback = (fireDate: Date) => Promise<PlataError | null>
6
+
7
+ export interface PlataTask {
8
+ name: string
9
+ rule: TaskRule | null
10
+ onPlataStart: boolean
11
+ callback: TaskCallback
12
+ }
13
+
14
+ export interface StatusPlataTask extends PlataTask {
15
+ lastRun: Date | null
16
+ lastReturn: PlataError | null
17
+ }
18
+
19
+ export interface PlataTasksProcess {
20
+ tasks: StatusPlataTask[]
21
+ }
22
+
23
+ export interface _PlataTasksProcess extends NodeJS.Process {
24
+ _plata?: PlataTasksProcess
25
+ }
26
+
27
+ export function getTasksNodeProcess(): PlataTasksProcess {
28
+ const p = process as _PlataTasksProcess
29
+
30
+ if (p._plata === undefined) {
31
+ p._plata = {
32
+ tasks: []
33
+ }
34
+ }
35
+
36
+ if (p._plata.tasks === undefined) {
37
+ p._plata.tasks = []
38
+ }
39
+
40
+ return p._plata
41
+ }
42
+
43
+ export function buildTaskCallBack(task: PlataTask): schedule.JobCallback {
44
+ return async (fireDate: Date) => {
45
+ let status: PlataError | null = null
46
+ const data = new Date()
47
+
48
+ const promise = task.callback(fireDate).then(
49
+ s => status = s,
50
+ err => status = {
51
+ errorID: 'PBT0001',
52
+ msg: `Erro ao rodar a task ${task.name}`,
53
+ error: err
54
+ }
55
+ )
56
+
57
+ const i = getTasksNodeProcess().tasks.findIndex(v => v.name === task.name)
58
+
59
+ await promise
60
+
61
+ if (i !== -1) {
62
+ getTasksNodeProcess().tasks[i].lastReturn = status
63
+ getTasksNodeProcess().tasks[i].lastRun = data
64
+ }
65
+ }
66
+ }
67
+
68
+ export async function buildTask(task: PlataTask): Promise<schedule.Job | null> {
69
+ if (task.onPlataStart) {
70
+ let status: PlataError | null = null
71
+
72
+ try{
73
+ status = await task.callback(new Date())
74
+ } catch (e) {
75
+ status = {
76
+ errorID: 'PBT0002',
77
+ msg: `Erro ao rodar a task ${task.name}`,
78
+ error: e
79
+ }
80
+ }
81
+
82
+ getTasksNodeProcess().tasks.push({
83
+ ...task,
84
+ lastRun: new Date(),
85
+ lastReturn: status
86
+ })
87
+ } else {
88
+ getTasksNodeProcess().tasks.push({
89
+ ...task,
90
+ lastRun: null,
91
+ lastReturn: null
92
+ })
93
+ }
94
+
95
+ if (task.rule === null) {
96
+ return null
97
+ }
98
+
99
+ return schedule.scheduleJob(task.rule as any, buildTaskCallBack(task))
100
+ }
101
+
102
+ export async function loadTasks(): Promise<PlataResultado<schedule.Job[]>> {
103
+ const tasks: schedule.Job[] = []
104
+
105
+ const task = await PlataRequire.requireFolderAsync<PlataTask>(
106
+ PlataDirs.getProjectDirTasks()
107
+ )
108
+
109
+ if (task.errorID !== undefined) {
110
+ return task
111
+ }
112
+
113
+ for (const t of task) {
114
+ if (t.errorID !== undefined) {
115
+ return t
116
+ }
117
+ const j = await buildTask(t.exports)
118
+
119
+ if (j !== null) tasks.push(j)
120
+ }
121
+
122
+ return tasks
123
+ }
124
+
125
+ export async function callTask(name: string): Promise<PlataError | null> {
126
+ const i = getTasksNodeProcess().tasks.findIndex(v => v.name === name)
127
+
128
+ if (i === -1) {
129
+ return {
130
+ errorID: 'PBT0003',
131
+ msg: `Task: ${name} não existe`,
132
+ }
133
+ }
134
+
135
+ const data = new Date()
136
+
137
+ return getTasksNodeProcess().tasks[i].callback(data).then(
138
+ status => {
139
+ getTasksNodeProcess().tasks[i].lastReturn = status
140
+ getTasksNodeProcess().tasks[i].lastRun = data
141
+
142
+ return status
143
+ },
144
+ err => {
145
+ const status = {
146
+ errorID: 'PBT0004',
147
+ msg: `Erro ao rodar a task ${name}`,
148
+ error: err
149
+ }
150
+
151
+ getTasksNodeProcess().tasks[i].lastReturn = status
152
+ getTasksNodeProcess().tasks[i].lastRun = data
153
+
154
+ return status
155
+ }
156
+ )
157
+ }
package/libs/tools.ts CHANGED
@@ -18,6 +18,10 @@ export namespace PlataDirs {
18
18
  return path.resolve('.')
19
19
  }
20
20
 
21
+ export function getProjectDirTasks(): string {
22
+ return path.resolve('.', 'tasks')
23
+ }
24
+
21
25
  export function getProjectDirSwagger(): string {
22
26
  return path.resolve('.', 'swagger')
23
27
  }
@@ -35,7 +39,7 @@ export namespace PlataDirs {
35
39
  }
36
40
 
37
41
  export function getProjectConfigFileDir(file: string): string {
38
- return `file:///${path.resolve('.', 'configs', file)}`.replace(/\\/g, '/')
42
+ return path.resolve('.', 'configs', file).replace(/\\/g, '/')
39
43
  }
40
44
 
41
45
  export function getProjectDirEnvs(): string {
@@ -59,7 +63,13 @@ export namespace PlataDirs {
59
63
  export function getPlataDir(): string {
60
64
  return path.resolve('.', 'node_modules', ProjectJson.plata_name)
61
65
  }
62
-
66
+
67
+ export const PlataJson: any = JSON.parse(
68
+ fs.readFileSync(
69
+ path.join(PlataDirs.getPlataDir(), 'package.json')
70
+ ).toString()
71
+ )
72
+
63
73
  export function getPlataTempletesDir(): string {
64
74
  return path.join(getPlataDir(), 'templates')
65
75
  }
@@ -69,7 +79,7 @@ export namespace PlataDirs {
69
79
  }
70
80
 
71
81
  export function getPlataBinExtraFile(file: string): string {
72
- return `file:///${path.join(getPlataDir(), 'bin', 'extras', file)}`.replace(/\\/g, '/')
82
+ return `${path.join(getPlataDir(), 'bin', 'extras', file)}`.replace(/\\/g, '/')
73
83
  }
74
84
 
75
85
  }
@@ -194,7 +204,7 @@ export namespace PlataRequire {
194
204
  export async function requireAsync<Type>(file: string): Promise<Required<Type>> {
195
205
  const p = path.resolve(file)
196
206
 
197
- const e = await import(`file:///${p}`.replace(/\\/g, '/')).catch(e => { return {_plataError: e } })
207
+ const e = await import(p.replace(/\\/g, '/')).catch(e => { return {_plataError: e } })
198
208
 
199
209
  if (e._plataError !== undefined) {
200
210
  return {
@@ -218,7 +228,7 @@ export namespace PlataRequire {
218
228
  glob.sync(`${p.replace(/\\/g, '/')}/**/*.+(js|ts)`)
219
229
  .filter(file => !file.endsWith('.d.ts'))
220
230
  .forEach(file => {
221
- file = file.replace('.ts', '.js')
231
+ file = file.replace(/\.ts|\.js$/, '')
222
232
 
223
233
  promises.push(requireAsync<Type>(file))
224
234
  })
package/package.json CHANGED
@@ -1,30 +1,35 @@
1
1
  {
2
2
  "name": "pwi-plata-type",
3
- "version": "0.3.4",
4
- "type": "module",
3
+ "version": "0.3.7",
5
4
  "main": "index.ts",
6
5
  "bin": {
7
6
  "plata": "bin/plata.ts",
8
7
  "plata-cli-create": "bin/plata-create.ts",
9
- "plata-swagger-gen": "bin/plata-swagger-gen.ts"
8
+ "plata-swagger-gen": "bin/plata-swagger-gen.ts",
9
+ "plata-reload": "bin/plata-reload.ts"
10
10
  },
11
11
  "scripts": {
12
- "postinstall": "node postinstall.js"
12
+ "postinstall": "node postinstall.mjs"
13
13
  },
14
14
  "keywords": [],
15
15
  "author": "",
16
16
  "license": "UNLICENSED",
17
17
  "dependencies": {
18
+ "@swc/core": "^1.2.218",
18
19
  "@types/express": "^4.17.13",
19
20
  "@types/glob": "^7.2.0",
20
21
  "@types/jest": "^28.1.1",
22
+ "@types/node-schedule": "^2.1.0",
21
23
  "@types/swagger-ui-express": "^4.1.3",
24
+ "commander": "^9.4.0",
25
+ "express": "^4.18.1",
22
26
  "glob": "^8.0.3",
23
27
  "jest": "^28.1.1",
28
+ "node-schedule": "^2.1.0",
24
29
  "swagger-ui-express": "^4.4.0",
25
30
  "ts-jest": "^28.0.4",
26
- "ts-node": "10.8.2",
27
- "express": "^4.18.1"
31
+ "ts-node": "^10.9.1",
32
+ "tsconfig-paths": "^4.0.0"
28
33
  },
29
34
  "description": "",
30
35
  "devDependencies": {
@@ -15,6 +15,10 @@ const main = async () => {
15
15
  projectPackageJson.plata_type = projectPackageJson.plata_type ?? 'api'
16
16
  projectPackageJson.plata_name = plataPackageJson.name
17
17
  projectPackageJson.license = "UNLICENSED"
18
+ projectPackageJson['scripts_plata'] = projectPackageJson['scripts_plata'] ?? new Object(null)
19
+
20
+ // https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy
21
+ projectPackageJson.scripts = JSON.parse(JSON.stringify(projectPackageJson['scripts_plata']))
18
22
 
19
23
  const templateDir = path.join(templatesDir, projectPackageJson.plata_type)
20
24
 
@@ -1,5 +1,5 @@
1
1
  //@ts-nocheck
2
- import * as ç__Name__çConfig from '../configs/ç__name__ç.js'
2
+ import * as ç__Name__çConfig from '@Configs/ç__name__ç'
3
3
 
4
4
  export class ç__Name__ç {
5
5
  private readonly config: typeof ç__Name__çConfig.default
@@ -0,0 +1,13 @@
1
+ //@ts-nocheck
2
+ import { PlataTasks, PlataTools } from "ç__PlataName__ç"
3
+
4
+ async function main(fireDate: Date): Promise<PlataTools.PlataError | null> {
5
+ return null
6
+ }
7
+
8
+ export default {
9
+ name: '',
10
+ rule: null, // https://crontab.guru/
11
+ onPlataStart: false,
12
+ callback: main
13
+ } as PlataTasks.PlataTask
@@ -1,18 +1,13 @@
1
- FROM node:16-alpine AS build
1
+ FROM node:16-alpine
2
2
 
3
3
  WORKDIR /usr/src/app
4
4
 
5
- COPY . ./
6
-
7
- RUN npm ci --only=production && \
8
- npm run build
9
-
10
- FROM node:16-alpine AS bin
5
+ COPY package*.json ./
11
6
 
12
7
  EXPOSE 3050
13
8
 
14
- WORKDIR /usr/src/app
9
+ RUN npm ci --only=production
15
10
 
16
- COPY --from=build /usr/src/app/build .
11
+ COPY . ./
17
12
 
18
13
  CMD [ "npm", "start" ]
@@ -10,6 +10,7 @@ export async function install({ dirs, projectPackageJson }) {
10
10
  promises.push(t.createFolderProject('routes'))
11
11
  promises.push(t.createFolderProject('libs'))
12
12
  promises.push(t.createFolderProject('models'))
13
+ promises.push(t.createFolderProject('tasks'))
13
14
 
14
15
  promises.push(t.copyFolderToProject('configs'))
15
16
  promises.push(t.copyFolderToProject('envs'))
@@ -18,13 +19,12 @@ export async function install({ dirs, projectPackageJson }) {
18
19
  promises.push(t.copyFileToProject('Dockerfile'))
19
20
  promises.push(t.syncFileToProject('tsconfig.json'))
20
21
 
21
- projectPackageJson.type = "module"
22
- projectPackageJson.scripts = new Object(null)
23
- projectPackageJson.scripts.start = `ts-node --transpile-only --esm ./node_modules/${projectPackageJson.plata_name}/bin/plata`
24
- projectPackageJson.scripts.build = `npx tsc && ts-node --transpile-only --esm ./node_modules/${projectPackageJson.plata_name}/bin/plata-build --`
25
- projectPackageJson.scripts.create = `ts-node --transpile-only --esm ./node_modules/${projectPackageJson.plata_name}/bin/plata-create --`
22
+ projectPackageJson.scripts.start = `ts-node -P ./tsconfig.json ./node_modules/${projectPackageJson.plata_name}/bin/plata`
23
+ projectPackageJson.scripts.build = `npx tsc && ts-node -P ./tsconfig.json ./node_modules/${projectPackageJson.plata_name}/bin/plata-build --`
24
+ projectPackageJson.scripts.create = `ts-node -P ./tsconfig.json ./node_modules/${projectPackageJson.plata_name}/bin/plata-create --`
26
25
  projectPackageJson.scripts.dev = "npx nodemon -e '.js,.mjs,.json,.ts' --exec 'npm start'"
27
- projectPackageJson.scripts['swagger:gen'] = `ts-node --transpile-only --esm ./node_modules/${projectPackageJson.plata_name}/bin/plata-swagger-gen`
26
+ projectPackageJson.scripts['swagger:gen'] = `ts-node -P ./tsconfig.json ./node_modules/${projectPackageJson.plata_name}/bin/plata-swagger-gen`
27
+ projectPackageJson.scripts['plata:reload'] = `ts-node -P ./tsconfig.json ./node_modules/${projectPackageJson.plata_name}/bin/plata-reload.ts`
28
28
  projectPackageJson.main = undefined
29
29
 
30
30
  await Promise.all(promises)
@@ -7,4 +7,5 @@ ENV=debug
7
7
  PORT=3050
8
8
  _PLATA_API_ROOT=/api
9
9
  _PLATA_API_SSL_KEY=
10
- _PLATA_API_SSL_CERT=
10
+ _PLATA_API_SSL_CERT=
11
+ _PLATA_API_JSON_SIZE=100kb
@@ -8,4 +8,5 @@ ENV=homolog
8
8
  PORT=3050
9
9
  _PLATA_API_ROOT=/api
10
10
  _PLATA_API_SSL_KEY=
11
- _PLATA_API_SSL_CERT=
11
+ _PLATA_API_SSL_CERT=
12
+ _PLATA_API_JSON_SIZE=100kb
@@ -8,4 +8,5 @@ ENV=prod
8
8
  PORT=3050
9
9
  _PLATA_API_ROOT=/api
10
10
  _PLATA_API_SSL_KEY=
11
- _PLATA_API_SSL_CERT=
11
+ _PLATA_API_SSL_CERT=
12
+ _PLATA_API_JSON_SIZE=100kb
@@ -1,16 +1,40 @@
1
1
  {
2
+ "ts-node": {
3
+ "transpileOnly": true,
4
+ "swc": true,
5
+ "esm": false,
6
+ "project": "./tsconfig.json",
7
+ "skipIgnore": true,
8
+ "require": [
9
+ "tsconfig-paths/register"
10
+ ],
11
+ "compilerOptions": {
12
+ "module": "CommonJS"
13
+ }
14
+ },
2
15
  "compilerOptions": {
3
- "strictNullChecks": true,
4
- "module": "es2022",
5
- "target": "es2022",
6
- "declaration": false,
7
- "sourceMap": false,
8
- "esModuleInterop": true,
9
- "outDir": "build",
10
- "moduleResolution": "node"
16
+ "target": "ESNext",
17
+ "module": "CommonJS",
18
+ "lib": ["esnext"],
19
+ "allowJs": true,
20
+ "outDir": "./build",
21
+ "rootDir": "./",
22
+ "esModuleInterop": true,
23
+ "resolveJsonModule": true,
24
+ "strictNullChecks": true,
25
+ "forceConsistentCasingInFileNames": true,
26
+ "baseUrl": ".",
27
+ "paths": {
28
+ "@Libs/*": ["./libs/*"],
29
+ "@Configs/*": [ "./configs/*" ],
30
+ "@Models/*": [ "./models/*" ],
31
+ "@Clusters/*": [ "./clusters/*" ],
32
+ "@Plata/*": [ "./node_modules/pwi-plata-type/*" ],
33
+ "@PlataBin/*": [ "./node_modules/pwi-plata-type/bin/*" ],
34
+ }
11
35
  },
12
36
  "include": [
13
37
  "./**/*.ts",
14
- "node_modules/pwi-plata*/**/*.ts"
38
+ "./node_modules/pwi-plata-type/**/*.ts"
15
39
  ]
16
40
  }
@@ -9,7 +9,7 @@ export async function install({ dirs, projectPackageJson }) {
9
9
  promises.push(t.createFolderProject('clusters'))
10
10
  promises.push(t.createFolderProject('routes'))
11
11
  promises.push(t.createFolderProject('libs'))
12
-
12
+ promises.push(t.createFolderProject('tasks'))
13
13
  promises.push(t.createFolderProject('configs'))
14
14
  promises.push(t.createFolderProject('bin'))
15
15
 
@@ -18,10 +18,10 @@ export async function install({ dirs, projectPackageJson }) {
18
18
  promises.push(t.syncFileToProject('tsconfig.json'))
19
19
 
20
20
  projectPackageJson.type = "module"
21
- projectPackageJson.scripts = new Object(null)
22
- projectPackageJson.scripts.dev = "ts-node"
21
+ projectPackageJson.scripts.dev = "ts-node -P ./tsconfig.json"
23
22
  projectPackageJson.scripts.postinstall = "node postinstall.js"
24
- projectPackageJson.scripts.create = `ts-node --transpile-only --esm ./node_modules/${projectPackageJson.plata_name}/bin/plata-create --`
23
+ projectPackageJson.scripts.create = `ts-node -P ./tsconfig.json ./node_modules/${projectPackageJson.plata_name}/bin/plata-create --`
24
+ projectPackageJson.scripts['plata:reload'] = `ts-node -P ./tsconfig.json ./node_modules/${projectPackageJson.plata_name}/bin/plata-reload.ts`
25
25
  projectPackageJson.main = undefined
26
26
 
27
27
  await Promise.all(promises)
@@ -22,6 +22,7 @@ const main = async() => {
22
22
  promises.push(t.copyFolderToProject('configs'))
23
23
  promises.push(t.syncFolderProject('clusters'))
24
24
  promises.push(t.syncFolderProject('libs'))
25
+ promises.push(t.syncFolderProject('tasks'))
25
26
 
26
27
  await Promise.all(promises)
27
28
  }
@@ -1,16 +1,40 @@
1
1
  {
2
- "compilerOptions": {
3
- "strictNullChecks": true,
4
- "module": "es2022",
5
- "target": "es2022",
6
- "declaration": false,
7
- "sourceMap": false,
8
- "esModuleInterop": true,
9
- "outDir": "build",
10
- "moduleResolution": "node"
11
- },
12
- "include": [
13
- "./**/*.ts",
14
- "node_modules/pwi-plata*/**/*.ts"
15
- ]
2
+ "ts-node": {
3
+ "transpileOnly": true,
4
+ "swc": true,
5
+ "esm": false,
6
+ "project": "./tsconfig.json",
7
+ "skipIgnore": true,
8
+ "require": [
9
+ "tsconfig-paths/register"
10
+ ],
11
+ "compilerOptions": {
12
+ "module": "CommonJS"
13
+ }
14
+ },
15
+ "compilerOptions": {
16
+ "target": "ESNext",
17
+ "module": "CommonJS",
18
+ "lib": ["esnext"],
19
+ "allowJs": true,
20
+ "outDir": "./build",
21
+ "rootDir": "./",
22
+ "esModuleInterop": true,
23
+ "resolveJsonModule": true,
24
+ "strictNullChecks": true,
25
+ "forceConsistentCasingInFileNames": true,
26
+ "baseUrl": ".",
27
+ "paths": {
28
+ "@Libs/*": ["./libs/*"],
29
+ "@Configs/*": [ "./configs/*" ],
30
+ "@Models/*": [ "./models/*" ],
31
+ "@Clusters/*": [ "./clusters/*" ],
32
+ "@Plata/*": [ "./node_modules/pwi-plata-type/*" ],
33
+ "@PlataBin/*": [ "./node_modules/pwi-plata-type/bin/*" ],
34
+ }
35
+ },
36
+ "include": [
37
+ "./**/*.ts",
38
+ "./node_modules/pwi-plata-type/**/*.ts"
39
+ ]
16
40
  }
package/tsconfig.json CHANGED
@@ -1,16 +1,40 @@
1
1
  {
2
+ "ts-node": {
3
+ "transpileOnly": true,
4
+ "swc": true,
5
+ "esm": false,
6
+ "project": "./tsconfig.json",
7
+ "skipIgnore": true,
8
+ "require": [
9
+ "tsconfig-paths/register"
10
+ ],
11
+ "compilerOptions": {
12
+ "module": "CommonJS"
13
+ }
14
+ },
2
15
  "compilerOptions": {
3
- "strictNullChecks": true,
4
- "module": "es2022",
5
- "target": "es2022",
6
- "declaration": false,
7
- "sourceMap": false,
8
- "esModuleInterop": true,
9
- "outDir": "build",
10
- "moduleResolution": "node"
16
+ "target": "ESNext",
17
+ "module": "CommonJS",
18
+ "lib": ["esnext"],
19
+ "allowJs": true,
20
+ "outDir": "./build",
21
+ "rootDir": "./",
22
+ "esModuleInterop": true,
23
+ "resolveJsonModule": true,
24
+ "strictNullChecks": true,
25
+ "forceConsistentCasingInFileNames": true,
26
+ "baseUrl": ".",
27
+ "paths": {
28
+ "@libs/*": ["./libs/*"],
29
+ "@configs/*": [ "./configs/*" ],
30
+ "@models/*": [ "./models/*" ],
31
+ "@clusters/*": [ "./clusters/*" ],
32
+ "@Plata/*": [ "./node_modules/pwi-plata-type/*" ],
33
+ "@PlataBin/*": [ "./node_modules/pwi-plata-type/bin/*" ],
34
+ }
11
35
  },
12
36
  "include": [
13
37
  "./**/*.ts",
14
- "node_modules/pwi-plata*/**/*.ts"
38
+ "./node_modules/pwi-plata-type/**/*.ts"
15
39
  ]
16
40
  }