Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Comando de redirecionamento de rotas. #38

Merged
merged 6 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 16 additions & 38 deletions infraestrutura/resposta.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Simbolo } from '@designliquido/delegua/fontes/lexador';
import { DefinirValor, FuncaoConstruto, Isto, Literal, Variavel } from '@designliquido/delegua/fontes/construtos';
import { DefinirValor, FuncaoConstruto, Isto, Variavel } from '@designliquido/delegua/fontes/construtos';
import { Expressao, PropriedadeClasse, Retorna } from '@designliquido/delegua/fontes/declaracoes';
import { DeleguaClasse, DeleguaFuncao } from '@designliquido/delegua/fontes/estruturas';
import { ParametroInterface } from '@designliquido/delegua/fontes/interfaces';
Expand All @@ -14,24 +14,28 @@
export class Resposta extends DeleguaClasse {
constructor() {
const metodos = {};
const propriedades = [
new PropriedadeClasse(
new Simbolo('IDENTIFICADOR', 'destino', null, -1, -1),
'texto'
),
new PropriedadeClasse(
new Simbolo('IDENTIFICADOR', 'mensagem', null, -1, -1),
'texto'
),
new PropriedadeClasse(
new Simbolo('IDENTIFICADOR', 'statusHttp', null, -1, -1),
'numero'
),
new PropriedadeClasse(
new Simbolo('IDENTIFICADOR', 'valores', null, -1, -1),
'dicionário'
),
new PropriedadeClasse(
new Simbolo('IDENTIFICADOR', 'visao', null, -1, -1),
'texto'
)
];

Check warning on line 38 in infraestrutura/resposta.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

// Há duas formas de construção de métodos apenas usando
// estruturas de alto nível: declarando cada uma manualmente,
Expand Down Expand Up @@ -163,46 +167,20 @@
geradorExpressoes.gerarRetornoDeFuncao('isto')
])
);
/* metodos['lmht'] = new DeleguaFuncao(
'lmht',
new FuncaoConstruto(
-1,
-1,
[
{
abrangencia: 'padrao',
tipo: 'numero',
nome: new Simbolo('IDENTIFICADOR', 'valores', null, -1, -1)
} as ParametroInterface
],

metodos['redirecionar'] = geradorExpressoes.gerarMetodo('redirecionar',
geradorExpressoes.gerarConstrutoFuncao(
[geradorExpressoes.gerarParametro('destino', 'texto')],
[
new Expressao(
new DefinirValor(
-1,
-1,
new Isto(-1, -1, new Simbolo('ISTO', 'isto', null, -1, -1)),
new Simbolo('IDENTIFICADOR', 'valores', null, -1, -1),
new Variavel(-1, new Simbolo('IDENTIFICADOR', 'valores', null, -1, -1))
)
),
new Expressao(
new DefinirValor(
-1,
-1,
new Isto(-1, -1, new Simbolo('ISTO', 'isto', null, -1, -1)),
new Simbolo('IDENTIFICADOR', 'lmht', null, -1, -1),
new Literal(-1, -1, true)
)
geradorExpressoes.gerarAtribuicaoValorEmPropriedadeClasse(
'destino',
geradorExpressoes.gerarReferenciaVariavel('destino')
),
new Retorna(
new Simbolo('IDENTIFICADOR', 'qualquerCoisa', null, -1, -1),
new Variavel(-1, new Simbolo('IDENTIFICADOR', 'isto', null, -1, -1))
)
geradorExpressoes.gerarRetornoDeFuncao('isto')
]
),
null,
false
); */
)
);

Check warning on line 182 in infraestrutura/resposta.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

super(
new Simbolo('IDENTIFICADOR', 'Resposta', null, -1, -1),
null,
Expand Down
8 changes: 5 additions & 3 deletions interface-linha-comando/gerar/gerador-rotas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ export class GeradorRotas {
*/
private criarNovasRotasSemId(declaracaoModelo: Classe, diretorioRotas: string): string {
const conteudoSelecionarTudo = this.criarRotaSelecionarTudo(declaracaoModelo);
const conteudoAdicionar = `liquido.rotaPost(funcao(requisicao, resposta) {\n resposta.lmht({ "titulo": "Liquido" })\n})\n\n`;
const nomeModeloPlural = pluralizar(declaracaoModelo.simbolo.lexema.toLocaleLowerCase('pt')).toLocaleLowerCase('pt');
const conteudoAdicionar = `liquido.rotaPost(funcao(requisicao, resposta) {\n resposta.redirecionar("/${nomeModeloPlural}")\n})\n\n`;
const conteudoRotas = `${conteudoSelecionarTudo}${conteudoAdicionar}`;

const caminhoRotas = caminho.join(diretorioRotas, 'inicial.delegua');
Expand All @@ -64,11 +65,12 @@ export class GeradorRotas {
* @returns O caminho do arquivo de rotas no sistema de arquivos.
*/
private criarNovasRotasComId(declaracaoModelo: Classe, diretorioRotas: string): string[] {
const nomeModeloPlural = pluralizar(declaracaoModelo.simbolo.lexema.toLocaleLowerCase('pt')).toLocaleLowerCase('pt');
const conteudoSelecionarUm = this.criarRotaSelecionarUm(declaracaoModelo);
const conteudoSelecionarParaEdicao = this.criarRotaEditar(declaracaoModelo);
const conteudoAtualizar = `liquido.rotaPost(funcao(requisicao, resposta) {\n resposta.lmht({ "titulo": "Liquido" })\n})\n\n`;
const conteudoAtualizar = `liquido.rotaPost(funcao(requisicao, resposta) {\n resposta.redirecionar("/${nomeModeloPlural}")\n})\n\n`;
const conteudoSelecionarParaExclusao = this.criarRotaConfirmarExclusao(declaracaoModelo);
const conteudoExcluir = `liquido.rotaPost(funcao(requisicao, resposta) {\n resposta.lmht({ "titulo": "Liquido" })\n})\n\n`;
const conteudoExcluir = `liquido.rotaPost(funcao(requisicao, resposta) {\n resposta.redirecionar("/${nomeModeloPlural}")\n})\n\n`;

const diretorioRotasComId = criarDiretorioComIdSeNaoExiste(diretorioRotas);

Expand Down
12 changes: 6 additions & 6 deletions interface-linha-comando/gerar/gerador-visoes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export class GeradorVisoes {
const listaPropriedades: string[] = [];
for (const propriedade of declaracaoModelo.propriedades) {
listaPropriedades.push(" ".repeat(this.indentacao * 4) + `<etiqueta para="${propriedade.nome.lexema}">${propriedade.nome.lexema}</etiqueta>`);
listaPropriedades.push(" ".repeat(this.indentacao * 4) + `<campo tipo="texto" id="${propriedade.nome.lexema}" value={{${propriedade.nome.lexema}}}></campo>`);
listaPropriedades.push(" ".repeat(this.indentacao * 4) + `<campo tipo="texto" id="${propriedade.nome.lexema}" valor="{{${propriedade.nome.lexema}}}" />`);
}

return listaPropriedades.reduce(
Expand All @@ -162,7 +162,7 @@ export class GeradorVisoes {

const formulario = `${" ".repeat(this.indentacao * 2)}<formulário método="POST" ação="/${pluralizar(declaracaoModelo.simbolo.lexema.toLocaleLowerCase())}">\n` +
`${relacaoPropriedades}` +
`\n\n${" ".repeat(this.indentacao * 3)}<campo tipo="enviar">Adicionar</campo>\n` +
`\n\n${" ".repeat(this.indentacao * 3)}<campo tipo="enviar" valor="Adicionar" />\n` +
`${" ".repeat(this.indentacao * 2)}</formulário>\n`;
return `${titulo}${formulario}`;
}
Expand All @@ -176,9 +176,9 @@ export class GeradorVisoes {
const titulo = `${" ".repeat(this.indentacao * 2)}<titulo1>Editar ${declaracaoModelo.simbolo.lexema}</titulo1>\n`;

const relacaoPropriedades = `${" ".repeat(this.indentacao * 3)}<campos>\n` +
`${" ".repeat(this.indentacao * 4)}<campo tipo="escondido" id="id"></campo>\n` +
`${" ".repeat(this.indentacao * 4)}<campo tipo="escondido" id="id" valor="{{id}}" />\n` +
this.geracaoComumCamposFormulario(declaracaoModelo) +
`\n\n${" ".repeat(this.indentacao * 4)}<campo tipo="enviar">Atualizar</campo>\n` +
`\n\n${" ".repeat(this.indentacao * 4)}<campo tipo="enviar" valor="Atualizar" />\n` +
`\n${" ".repeat(this.indentacao * 3)}</campos>\n`;

const formulario = `${" ".repeat(this.indentacao * 2)}<formulário método="POST" ação="/${pluralizar(declaracaoModelo.simbolo.lexema.toLocaleLowerCase())}/{{id}}/editar">\n`+
Expand All @@ -201,8 +201,8 @@ export class GeradorVisoes {
`\n${" ".repeat(this.indentacao * 2)}</lista-definições>\n`;

const formulario = `${" ".repeat(this.indentacao * 2)}<formulário método="POST" ação="/${pluralizar(declaracaoModelo.simbolo.lexema.toLocaleLowerCase())}/{{id}}/excluir">\n`+
`${" ".repeat(this.indentacao * 3)}<campo tipo="escondido" id="id" value={{id}}></campo>\n` +
`${" ".repeat(this.indentacao * 3)}<campo tipo="enviar">Confirmar Exclusão</campo>\n` +
`${" ".repeat(this.indentacao * 3)}<campo tipo="escondido" id="id" valor={{id}} />\n` +
`${" ".repeat(this.indentacao * 3)}<campo tipo="enviar" valor="Confirmar Exclusão" />\n` +
`${" ".repeat(this.indentacao * 2)}</formulário>\n`;

return `${titulo}${mensagemConfirmacaoExclusao}${relacaoPropriedades}${formulario}`;
Expand Down
35 changes: 23 additions & 12 deletions liquido.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@
private async logicaComumResultadoInterpretador(
caminhoRota: string,
retornoInterpretador: RetornoInterpretador
): Promise<{ corpoRetorno: any; statusHttp: number }> {
): Promise<{ corpoRetorno?: any; statusHttp?: number, redirecionamento?: string }> {
// O resultado que interessa é sempre o último.
// Ele vem como string, e precisa ser desserializado para ser usado.

Expand All @@ -341,32 +341,39 @@
if (valor.propriedades.statusHttp) {
statusHttp = valor.propriedades.statusHttp;
}

try {
if (valor.propriedades.lmht) {

if (valor.propriedades.destino) {
// Redirecionamento
return { redirecionamento: valor.propriedades.destino };

Check warning on line 347 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
}

Check warning on line 348 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

Check warning on line 348 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

if (valor.propriedades.lmht) {
try {
let visao: string = caminhoRota;
// Verifica se foi definida uma preferência de visão.
// Se não foi, usa o sufixo da rota como visão correspondente.
// Por exemplo, `/rotas/inicial.delegua` tem como visão correspondente `/visoes/inicial.lmht`.
if (valor.propriedades.visao) {
const partesRota = caminhoRota.split('/');
partesRota.pop();
visao = partesRota.join('/') + '/' + valor.propriedades.visao;
}

const resultadoFormatacaoLmht = await this.formatadorLmht.formatar(visao, valor.propriedades.valores);
return {
corpoRetorno: resultadoFormatacaoLmht,
statusHttp: statusHttp
};
} else if (valor.propriedades.mensagem) {
return {
corpoRetorno: valor.propriedades.mensagem,
statusHttp: statusHttp
};
} catch (erro: any) {
console.log(`Erro ao processar LMHT: ${erro}`);

Check warning on line 368 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
}

Check warning on line 369 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
} catch (erro: any) {
console.log(`Erro ao processar LMHT: ${erro}`);
}

Check warning on line 370 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

Check warning on line 370 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

if (valor.propriedades.mensagem) {
return {
corpoRetorno: valor.propriedades.mensagem,
statusHttp: statusHttp
};

Check warning on line 376 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
}

Check warning on line 377 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

Check warning on line 377 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch
}

Expand All @@ -382,12 +389,16 @@
const funcao = argumentos[0] as FuncaoConstruto;
const metodoResolvido = MetodoRoteador[metodoRoteador.replace('rota', '')];

this.roteador.mapaRotas[metodoResolvido](caminhoRota, async (req, res) => {
await this.prepararRequisicao(req, `funcaoRota${metodoRoteador}`, funcao);

const retornoInterpretador = await this.chamarInterpretador(`funcaoRota${metodoRoteador}`);
const corpoEStatus = await this.logicaComumResultadoInterpretador(caminhoRota, retornoInterpretador);
res.send(corpoEStatus.corpoRetorno).status(corpoEStatus.statusHttp);
if (corpoEStatus.redirecionamento) {
res.redirect(corpoEStatus.redirecionamento);

Check warning on line 398 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
} else {
res.send(corpoEStatus.corpoRetorno).status(corpoEStatus.statusHttp);

Check warning on line 400 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
}

Check warning on line 401 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

Check warning on line 401 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

Check warning on line 401 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch
});

Check warning on line 402 in liquido.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
}
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@
"swagger": "tsoa spec"
},
"dependencies": {
"@designliquido/delegua-node": "^0.30.3",
"@designliquido/delegua-node": "^0.30.7",
"@designliquido/flexoes": "^0.1.0",
"@designliquido/foles": "^0.6.1",
"@designliquido/lincones-sqlite": "^0.0.2",
"@designliquido/lmht-js": "^0.4.5",
"@designliquido/lmht-js": "^0.4.8",
"body-parser": "^1.20.1",
"commander": "^11.1.0",
"cookie-parser": "^1.4.6",
Expand Down
36 changes: 18 additions & 18 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -304,21 +304,21 @@
dependencies:
"@jridgewell/trace-mapping" "0.3.9"

"@designliquido/delegua-node@^0.30.3":
version "0.30.3"
resolved "https://registry.yarnpkg.com/@designliquido/delegua-node/-/delegua-node-0.30.3.tgz#126569987b2b49d95e702d0d5d77743d22ae8e72"
integrity sha512-Fo7ZdRp3VW6E8UMY/+RGUUMeDu+3RlUGct37nfzbJuRgenlRFJEgvHL/P5GJBHjFFXyfsVe19nK3+F6kcVT9Zg==
"@designliquido/delegua-node@^0.30.7":
version "0.30.7"
resolved "https://registry.yarnpkg.com/@designliquido/delegua-node/-/delegua-node-0.30.7.tgz#c6bb323265aae071465c15aea3d4a767296b2663"
integrity sha512-3hc9ft3yWzHOoPBDDHytikKINBPmheupXvFkMws5GVlyqrICkoZG5+N377DHxwhDwpNSMgLLNeJl+R2w1PsJ/Q==
dependencies:
"@designliquido/delegua" "0.30.3"
"@designliquido/delegua" "0.30.7"
chalk "4.1.2"
commander "^9.4.1"
json-colorizer "^2.2.2"
lodash.clonedeep "^4.5.0"

"@designliquido/[email protected].3":
version "0.30.3"
resolved "https://registry.yarnpkg.com/@designliquido/delegua/-/delegua-0.30.3.tgz#c901c56c795df0a7822a363af643c7fff45d61cb"
integrity sha512-CGGHJrX/eW7ChdO2gFpDU6SP0Gls6i4YFeN4orU5PfOb9pN55Mu5PYPKZGbFfF/aS6klYzp4T1OXboxgsgWLDw==
"@designliquido/[email protected].7":
version "0.30.7"
resolved "https://registry.yarnpkg.com/@designliquido/delegua/-/delegua-0.30.7.tgz#7f4a97f5ef0d1583ba033ffe8c0fd0ea2e19bd6f"
integrity sha512-8kJ9lDoC/Ak0IkWOn4hjrMk4W8vwT8jcrpbSZp4Ql3DbXaykGZ2XZfZMehm0IiLNw/1UFW8YOnSS4/n5/14IaA==
dependencies:
antlr4ts "^0.5.0-alpha.4"
browser-process-hrtime "^1.0.0"
Expand Down Expand Up @@ -348,13 +348,13 @@
sqlite "4.1.2"
sqlite3 "^5.1.4"

"@designliquido/lmht-js@^0.4.5":
version "0.4.5"
resolved "https://registry.yarnpkg.com/@designliquido/lmht-js/-/lmht-js-0.4.5.tgz#5a31cb4a62a989d4cca97dd0a88035d5adf0cc0b"
integrity sha512-Y9DzF4XLjrxXtz6KDXBY3TJ9bUlepLJNUTKRT41OAh+5P8c2E7dYhVMZm2nvlq26IPmEwVwHNslEF4ueipgCgQ==
"@designliquido/lmht-js@^0.4.8":
version "0.4.8"
resolved "https://registry.yarnpkg.com/@designliquido/lmht-js/-/lmht-js-0.4.8.tgz#4718c81c0b286574f69dac4d399a47e19e8e05fb"
integrity sha512-VvbAe9+TXSqV9+NJQB/WknOqkC5Rm2HlEddCrJVFnbKItv1XNRVG2Tz85zrrNVoSCCEKEZ7aHiioJkoKVAYfpw==
dependencies:
jsdom "^21.1.1"
xslt-processor "^2.1.3"
xslt-processor "^2.2.0"

"@eslint/eslintrc@^1.3.3":
version "1.3.3"
Expand Down Expand Up @@ -6309,10 +6309,10 @@ [email protected]:
resolved "https://registry.yarnpkg.com/xregexp/-/xregexp-2.0.0.tgz#52a63e56ca0b84a7f3a5f3d61872f126ad7a5943"
integrity sha512-xl/50/Cf32VsGq/1R8jJE5ajH1yMCQkpmoS10QbFZWl2Oor4H0Me64Pu2yxvsRWK3m6soJbmGfzSR7BYmDcWAA==

xslt-processor@^2.1.3:
version "2.1.3"
resolved "https://registry.yarnpkg.com/xslt-processor/-/xslt-processor-2.1.3.tgz#2380190f4ae383cc1f22173690ebc051d3f2e022"
integrity sha512-WiYeocbC/Y7SmRO7FAHUCx7mmGstd82CKiuWiJG3lYQYTbSHl/e1PVCuVuCVSY4ZHlGRkey48rgvCEEdAtlrjQ==
xslt-processor@^2.2.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/xslt-processor/-/xslt-processor-2.2.0.tgz#ce4a91fcb3863c80b2b5c57854e8bc1d0a3a37bc"
integrity sha512-gmBVzwqWpVr72H/b71AK2LhNQARsj3RxPX8tQRXsLPJ0dagVmu6JmFzhsTm6kK0wuDJ5NLQQ2V1GzRKlK6zMfA==
dependencies:
he "^1.2.0"

Expand Down
Loading