This commit is contained in:
Luiz Silva 2024-05-06 08:45:08 -03:00
commit b5ca2d50ac
337 changed files with 24672 additions and 0 deletions

7
src/aleatorio.ts Normal file
View file

@ -0,0 +1,7 @@
const alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
export const aleatorio = (tamanho?: number) =>
Array.from(
{ length: tamanho || 8 },
() => `ale-${alfabeto[Math.floor(Math.random() * 1000) % alfabeto.length]}`,
).join("");

View file

@ -0,0 +1,26 @@
import { z } from "zod";
export const InterfaceAuntenticacao = z.object({
// usuários
codigo_usuario: z.string().uuid(),
nome_usuario: z.string(),
email_usuario: z.string(),
documento_usuario: z.string(),
organizacao: z.string(),
rotas: z.object({}),
// Dados do sistema
sistema: z.string(),
sistema_cor: z.string(),
sistema_nome: z.string(),
sistema_logo: z.string(),
// integrações
/** as url de integração serão armazenadas pelo sistema resíduos e identificado pelo código do token */
codigo_token: z.string(),
url_usuarios: z.string().url(),
url_empreendedores: z.string().url(),
url_empreendimentos: z.string().url(),
});

View file

@ -0,0 +1,3 @@
/** Sistemas vão conversar por meio de autorizações tipar eles aqui */
export * from "./auntenticacaoResiduos";

10
src/constantes.ts Normal file
View file

@ -0,0 +1,10 @@
export const uuid_null = "00000000-0000-0000-0000-000000000000";
export enum camposComuns {
codigo = "codigo",
excluido = "excluido",
data_hora_criacao = "data_hora_criacao",
data_hora_atualizacao = "data_hora_atualizacao",
codigo_usuario_criacao = "codigo_usuario_criacao",
codigo_usuario_atualizacao = "codigo_usuario_atualizacao",
}

28
src/consulta.ts Normal file
View file

@ -0,0 +1,28 @@
export enum operadores {
"=" = "=",
"!=" = "!=",
">" = ">",
">=" = ">=",
"<" = "<",
"<=" = "<=",
like = "like",
in = "in",
}
export type tipoFiltro = {
coluna: string;
valor: any;
operador: keyof typeof operadores | operadores;
ou?: boolean;
};
export type interfaceConsulta = {
offset?: number;
limit?: number;
filtros?: tipoFiltro[];
ordem?: string;
ordemTipo?: "asc" | "desc";
colunas?: string[];
apenasConsulta?: boolean;
apenasContagem?: boolean;
};

9
src/index.ts Normal file
View file

@ -0,0 +1,9 @@
export * from "./respostas";
export * from "./autorizacoes";
export * from "./constantes";
export * from "./consulta";
export * from "./aleatorio";
export * from "./texto_busca";
export * from "./unidades_medida";
export * from "./uuid";
export * from "./provedores";

4
src/provedores.ts Normal file
View file

@ -0,0 +1,4 @@
export enum provedores {
"betha-sistemas" = "Betha Sistemas",
"e-licencie-gov" = "e-licencie Gov",
}

111
src/resposta.ts Executable file
View file

@ -0,0 +1,111 @@
import { esperar } from "./variaveisComuns";
export const codigosErros = {
400: "Erro de requisição",
403: "Não autenticado",
500: "Erro interno",
504: "Tempo de resposta excedido",
};
export interface tipoRespostaSucesso<T> {
codigo: 200;
eErro: false;
valor: T;
erro: undefined;
detalhes?: any[];
}
export interface tipoRespostaErro {
codigo: keyof typeof codigosErros;
eErro: true;
erro: string;
valor: undefined;
detalhes?: any[];
}
export type tipoResposta<T> = tipoRespostaSucesso<T> | tipoRespostaErro;
export class Resposta<opcoesErroInterno extends any[]> {
funcaoErroInterno: (...opcoes: opcoesErroInterno) => void | Promise<void>;
detalhesErroInterno: boolean;
constructor(
funcaoErroInterno: (...arg1: opcoesErroInterno) => void | Promise<void>,
opcoes?: {
detalhesErroInterno?: boolean;
},
) {
this.funcaoErroInterno = funcaoErroInterno;
this.detalhesErroInterno = opcoes?.detalhesErroInterno || false;
}
addResultado<T>(resultado: T): tipoResposta<T> {
return {
codigo: 200,
eErro: false,
valor: resultado,
erro: undefined,
};
}
addSucesso(resultado: string): tipoResposta<string> {
return this.addResultado<string>(resultado);
}
addTrue(): tipoResposta<true> {
return this.addResultado<true>(true);
}
addErro(erro: string, codigo?: keyof typeof codigosErros): tipoRespostaErro {
return {
codigo: codigo || 400,
eErro: true,
erro: erro,
valor: undefined,
};
}
addErroEspera(erro?: string): tipoRespostaErro {
return {
codigo: 504,
eErro: true,
erro: erro || codigosErros[504],
valor: undefined,
};
}
addErroInterno(...opcoes: opcoesErroInterno): tipoRespostaErro {
//comunica o suporte sobre o erro
this.funcaoErroInterno(...opcoes);
return {
codigo: 500,
eErro: true,
erro: "Erro interno: Contate o suporte técnico.",
valor: undefined,
detalhes: this.detalhesErroInterno ? opcoes : undefined,
};
}
async addPromise<T>(
promise: () => Promise<T> | T,
limiteEspera?: number,
): Promise<tipoResposta<T>> {
try {
const resultado = await Promise.race([
Promise.resolve(promise())
.then((re) => this.addResultado(re))
.catch((er) => this.addErro(er.message || er)),
...(limiteEspera
? [esperar(limiteEspera).then(() => this.addErroEspera())]
: []),
]);
return resultado;
} catch (error) {
return this.addErro("Erro na resolução da Promessa.");
}
}
}
export const respostaCM = new Resposta(() => {
//
});

113
src/respostas.ts Normal file
View file

@ -0,0 +1,113 @@
export type tipoRespostaSucesso<T> = {
cod: 200;
valor: T;
mensagem: undefined;
eErro: false;
eCerto: true;
detalhe?: undefined;
};
export type tipoRespostaErro = {
//400 é um erro conhecido,
//500 é um erro desconhecido, geralmente tem origem de um exception
cod: 400 | 403 | 500;
valor: undefined;
mensagem: string;
eErro: true;
eCerto: false;
detalhes?: string[];
};
export type tipoResposta<T> = tipoRespostaSucesso<T> | tipoRespostaErro;
export const gerarRespostas = <T>(
registrarErroInterno: (erro: T) => Partial<tipoRespostaErro>,
) => {
/**
* Gera uma resposta de sucesso
*/
const valor = <T>(valor: T): tipoRespostaSucesso<T> => {
return {
cod: 200,
valor,
mensagem: undefined,
eErro: false,
eCerto: true,
};
};
/**
* Gera uma resposta de sucesso com valor true
*/
const valorTrue = (): tipoRespostaSucesso<true> => {
return {
cod: 200,
valor: true,
mensagem: undefined,
eErro: false,
eCerto: true,
};
};
/**
* Gera uma resposta de erro conhecido
*/
const erro = (mensagem: string, detalhes?: string[]): tipoRespostaErro => {
return {
cod: 400,
valor: undefined,
mensagem,
eErro: true,
eCerto: false,
detalhes,
};
};
/**
* Gera uma resposta de erro de permissão,será necessário fazer o login novamente
*/
const erroPermissao = (
mensagem?: string,
detalhes?: string[],
): tipoRespostaErro => {
return {
cod: 403,
valor: undefined,
mensagem: mensagem || "Sem permissão para esse recurso.",
eErro: true,
eCerto: false,
detalhes,
};
};
/**
* Gera uma resposta de erro desconhecido, geralmente tem origem de um exception
*/
const erroInterno = (parametros: T, mensagem?: string): tipoRespostaErro => {
const resRegistro = registrarErroInterno(parametros);
const mensagemFim = `${mensagem || "Erro interno"}`;
return {
cod: 500,
valor: undefined,
mensagem: mensagemFim,
eErro: true,
eCerto: false,
...resRegistro,
};
};
return {
valor,
valorTrue,
erro,
erroPermissao,
erroInterno,
};
};
/**
* Uso de respostas em comuns
*/
export const respostaComuns = gerarRespostas(() => ({}));

15
src/texto_busca.ts Normal file
View file

@ -0,0 +1,15 @@
/** gerar o texto de busca removendo caracteres especies e caixa alta */
export const texto_busca = (...texto: any[]): string =>
texto
.map((txt) =>
txt === null || txt === undefined
? ""
: String(txt)
.normalize("NFD")
// biome-ignore lint/suspicious/noMisleadingCharacterClass: <explanation>
.replace(/[\u0300-\u036f]/g, "")
.replace(/\s+/g, " ")
.toLowerCase(),
)
.join(" ");

78
src/unidades_medida.ts Normal file
View file

@ -0,0 +1,78 @@
export const unidades_medida: {
unidade: string;
nome: string;
unidade_normalizada: string;
normalizar: (valor: number) => number;
tipo: "massa" | "volume" | "comprimento";
}[] = [
{
unidade: "kg",
nome: "Quilograma",
unidade_normalizada: "kg",
normalizar: (valor: number) => valor,
tipo: "massa",
},
{
unidade: "g",
nome: "Grama",
unidade_normalizada: "kg",
normalizar: (valor: number) => valor / 1000,
tipo: "massa",
},
{
unidade: "ton",
nome: "Tonelada",
unidade_normalizada: "kg",
normalizar: (valor: number) => valor * 1000,
tipo: "massa",
},
{
unidade: "L",
nome: "Litro",
unidade_normalizada: "L",
normalizar: (valor: number) => valor,
tipo: "volume",
},
{
unidade: "m3",
nome: "Metro Cúbico",
unidade_normalizada: "L",
normalizar: (valor: number) => valor * 1000,
tipo: "volume",
},
{
unidade: "mL",
nome: "Mililitro",
unidade_normalizada: "L",
normalizar: (valor: number) => valor / 1000,
tipo: "volume",
},
{
unidade: "cm",
nome: "Centímetro",
unidade_normalizada: "m",
normalizar: (valor: number) => valor / 100,
tipo: "comprimento",
},
{
unidade: "mm",
nome: "Milímetro",
unidade_normalizada: "m",
normalizar: (valor: number) => valor / 1000,
tipo: "comprimento",
},
{
unidade: "m",
nome: "Metro",
unidade_normalizada: "m",
normalizar: (valor: number) => valor,
tipo: "comprimento",
},
{
unidade: "km",
nome: "Quilômetro",
unidade_normalizada: "m",
normalizar: (valor: number) => valor * 1000,
tipo: "comprimento",
},
];

15
src/uuid.ts Normal file
View file

@ -0,0 +1,15 @@
//Gerar uma uuid V4
const letras = "0123456789abcdef".split("");
export const uuid = () => {
letras.sort(() => Math.random() - 0.5);
const modelo = "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx".split("");
const retorno = modelo
.map((letra) =>
letra === "x"
? letras[((1000 * Math.random()) | 0) % letras.length]
: letra,
)
.join("");
return retorno;
};

4
src/variaveisComuns.ts Normal file
View file

@ -0,0 +1,4 @@
export const esperar = (ms: number): Promise<true> =>
new Promise((resolve: (r: true) => void) =>
setTimeout(() => resolve(true), ms),
);