From 11b24c3b98b0a5742e03ead184149a453d024b22 Mon Sep 17 00:00:00 2001 From: Luiz Silva Date: Wed, 13 Aug 2025 13:22:24 -0300 Subject: [PATCH] converter objeto para postgres --- dist-back/index.js | 2 ++ dist-back/postgres.js | 47 ++++++++++++++++++++++++++++++++++++++++++ dist-front/index.d.mts | 23 ++++++++++++++++++++- dist-front/index.mjs | 2 +- package.json | 2 +- src/index.ts | 1 + src/postgres.ts | 32 ++++++++++++++++++++++++++++ 7 files changed, 106 insertions(+), 3 deletions(-) create mode 100644 dist-back/postgres.js create mode 100644 src/postgres.ts diff --git a/dist-back/index.js b/dist-back/index.js index 54f6b58..0006ad2 100644 --- a/dist-back/index.js +++ b/dist-back/index.js @@ -23,6 +23,7 @@ __reExport(index_exports, require("./dayjs"), module.exports); __reExport(index_exports, require("./ecosistema"), module.exports); __reExport(index_exports, require("./extensoes"), module.exports); __reExport(index_exports, require("./logger"), module.exports); +__reExport(index_exports, require("./postgres"), module.exports); __reExport(index_exports, require("./testes-de-variaveis"), module.exports); __reExport(index_exports, require("./texto_busca"), module.exports); __reExport(index_exports, require("./tipagemRotas"), module.exports); @@ -39,6 +40,7 @@ __reExport(index_exports, require("./variaveisComuns"), module.exports); ...require("./ecosistema"), ...require("./extensoes"), ...require("./logger"), + ...require("./postgres"), ...require("./testes-de-variaveis"), ...require("./texto_busca"), ...require("./tipagemRotas"), diff --git a/dist-back/postgres.js b/dist-back/postgres.js new file mode 100644 index 0000000..62a7d6b --- /dev/null +++ b/dist-back/postgres.js @@ -0,0 +1,47 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var postgres_exports = {}; +__export(postgres_exports, { + objetoPg: () => objetoPg, + paraObjetoRegistroPg: () => paraObjetoRegistroPg, + pgObjeto: () => pgObjeto +}); +module.exports = __toCommonJS(postgres_exports); +const paraObjetoRegistroPg = (entrada) => { + try { + return Object.fromEntries( + Object.entries(entrada).map(([k, v]) => [ + k, + v === void 0 || v == null ? v : typeof v == "string" || typeof v == "number" || typeof v == "boolean" ? v : JSON.stringify(v, null, 2) + ]) + ); + } catch (error) { + throw new Error( + `Erro na fun\xE7\xE3o paraObjetoRegistroPg: ${error.message} ${error.stack}` + ); + } +}; +const pgObjeto = paraObjetoRegistroPg; +const objetoPg = paraObjetoRegistroPg; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + objetoPg, + paraObjetoRegistroPg, + pgObjeto +}); diff --git a/dist-front/index.d.mts b/dist-front/index.d.mts index 28eccfb..00ad847 100644 --- a/dist-front/index.d.mts +++ b/dist-front/index.d.mts @@ -118,6 +118,27 @@ type tipoLogger = (amb: { }) => TipoLoggerSessao; declare const logger: tipoLogger; +/** + * Trata um objeto para ser imput para postgres + * @param entrada + * @returns + */ +declare const paraObjetoRegistroPg: (entrada: { + [k: string]: any; +}) => { + [k: string]: string | boolean | null | undefined | number; +}; +declare const pgObjeto: (entrada: { + [k: string]: any; +}) => { + [k: string]: string | boolean | null | undefined | number; +}; +declare const objetoPg: (entrada: { + [k: string]: any; +}) => { + [k: string]: string | boolean | null | undefined | number; +}; + declare const umaFuncao: () => string; declare const umaVariavel = "Ol\u00E1 Mundo! (vari\u00E1vel)"; @@ -243,4 +264,4 @@ declare const nomeVariavel: (v: { [key: string]: any; }) => string; -export { TipagemRotas, type TipoLoggerSessao, aleatorio, cacheM, cacheMFixo, cacheMemoria, camposComuns, cdn_carro_de_boi, defineCwd, erUuid, esperar, extensoes, type interfaceConsulta, logger, nomeVariavel, operadores, postLogger, siglas_unidades_medida, texto_busca, tipoArquivo, type tipoFiltro, type tipoLogger, type tipoLoggerLog, type tipoLokiObjeto, tipoUsuarioResiduos, tx, umaFuncao, umaVariavel, unidades_medida, uuid, uuidV3, uuidV4, uuid_null, validarUuid, verCacheM }; +export { TipagemRotas, type TipoLoggerSessao, aleatorio, cacheM, cacheMFixo, cacheMemoria, camposComuns, cdn_carro_de_boi, defineCwd, erUuid, esperar, extensoes, type interfaceConsulta, logger, nomeVariavel, objetoPg, operadores, paraObjetoRegistroPg, pgObjeto, postLogger, siglas_unidades_medida, texto_busca, tipoArquivo, type tipoFiltro, type tipoLogger, type tipoLoggerLog, type tipoLokiObjeto, tipoUsuarioResiduos, tx, umaFuncao, umaVariavel, unidades_medida, uuid, uuidV3, uuidV4, uuid_null, validarUuid, verCacheM }; diff --git a/dist-front/index.mjs b/dist-front/index.mjs index c32081f..00786dc 100644 --- a/dist-front/index.mjs +++ b/dist-front/index.mjs @@ -1 +1 @@ -var f="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),W=e=>`eli-${Array.from({length:e||8}).map(()=>f[(999*Math.random()|0)%f.length]).join("")}`;var l={},x=(e,o,t)=>{let i=typeof e=="string"?e:typeof e=="number"?String(e):encodeURIComponent(JSON.stringify(e)),m=t&&new Date().getTime()+t*1e3;o!==void 0&&(l[i]={valor:o,validade:m});let r=l[i];if(!(r?.validade&&r.validadel,ee=x,oe=e=>o=>x(e,o);var ie="00000000-0000-0000-0000-000000000000",k=(n=>(n.codigo="codigo",n.excluido="excluido",n.data_hora_criacao="data_hora_criacao",n.data_hora_atualizacao="data_hora_atualizacao",n.codigo_usuario_criacao="codigo_usuario_criacao",n.codigo_usuario_atualizacao="codigo_usuario_atualizacao",n.versao="versao",n))(k||{}),j=(o=>(o.token="token",o))(j||{}),T=(t=>(t.Usuario="usuario",t.Fornecedor="fornecedor",t))(T||{});var z=(t=>(t["="]="=",t["!="]="!=",t[">"]=">",t[">="]=">=",t["<"]="<",t["<="]="<=",t.like="like",t.in="in",t))(z||{});import a from"dayjs";import"dayjs/locale/pt-br";import S from"dayjs/plugin/duration";import $ from"dayjs/plugin/isSameOrAfter";import N from"dayjs/plugin/isSameOrBefore";import M from"dayjs/plugin/minMax";import P from"dayjs/plugin/relativeTime";import U from"dayjs/plugin/timezone";import A from"dayjs/plugin/utc";import I from"dayjs/plugin/weekOfYear";a.extend(A);a.extend(U);a.extend(I);a.extend(N);a.extend($);a.extend(M);a.extend(P);a.extend(S);a.locale("pt-br");var ve="https://carro-de-boi-idz-one.b-cdn.net";var q=[{ext:"gif",tipo:"imagem",mime:"image/gif"},{ext:"jpg",tipo:"imagem",mime:"image/jpeg"},{ext:"jpeg",tipo:"imagem",mime:"image/jpeg"},{ext:"png",tipo:"imagem",mime:"image/png"},{ext:"bmp",tipo:"imagem",mime:"image/bmp"},{ext:"webp",tipo:"imagem",mime:"image/webp"},{ext:"tiff",tipo:"imagem",mime:"image/tiff"},{ext:"svg",tipo:"imagem",mime:"image/svg+xml"},{ext:"ico",tipo:"imagem",mime:"image/x-icon"},{ext:"pdf",tipo:"documento",mime:"application/pdf"},{ext:"doc",tipo:"documento",mime:"application/msword"},{ext:"docx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},{ext:"xls",tipo:"documento",mime:"application/vnd.ms-excel"},{ext:"xlsx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},{ext:"ppt",tipo:"documento",mime:"application/vnd.ms-powerpoint"},{ext:"pptx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"},{ext:"txt",tipo:"documento",mime:"text/plain"},{ext:"odt",tipo:"documento",mime:"application/vnd.oasis.opendocument.text"},{ext:"ods",tipo:"documento",mime:"application/vnd.oasis.opendocument.spreadsheet"},{ext:"rtf",tipo:"documento",mime:"application/rtf"},{ext:"csv",tipo:"documento",mime:"text/csv"},{ext:"mp4",tipo:"v\xEDdeo",mime:"video/mp4"},{ext:"avi",tipo:"v\xEDdeo",mime:"video/x-msvideo"},{ext:"mkv",tipo:"v\xEDdeo",mime:"video/x-matroska"},{ext:"mov",tipo:"v\xEDdeo",mime:"video/quicktime"},{ext:"wmv",tipo:"v\xEDdeo",mime:"video/x-ms-wmv"},{ext:"flv",tipo:"v\xEDdeo",mime:"video/x-flv"},{ext:"webm",tipo:"v\xEDdeo",mime:"video/webm"},{ext:"3gp",tipo:"v\xEDdeo",mime:"video/3gpp"},{ext:"mpeg",tipo:"v\xEDdeo",mime:"video/mpeg"}],_e=e=>{let o=String(e||"").toLocaleLowerCase().split(".").pop();return q.find(i=>i.ext===o)?.tipo||"outros"};import K from"cross-fetch";var we=e=>new Promise(o=>setTimeout(()=>o(!0),e)),u=e=>Object.keys(e).join("/");var C="https://log.idz.one",F="/loki/api/v1/push",G=async({objeto:e})=>{let o=await K(`${C}${F}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}).catch(t=>t);return o.ok?[e]:[e,`Erro ${o.status}: ${await o?.text?.()}`]},g="",Te=e=>{g=e},ze=({app:e,eProducao:o,parametros:t})=>({inquilino:i,usuario:m,parametros:r})=>async(d,n,h)=>{let{__filename:p,detalhes:s,local:c,parametros:b}=h||{},y=`${o?"":"DEV-"}${e}`;g&&p&&(p=p.replace(g,"")),c&&(s=[`${u({local:c})}="${c}"`,...s||[]]),p&&(s=[`${u({__filename:p})}="${p}"`,...s||[]]);let _=`${Date.now()}000000`,L=s?.length?`${n} | ${s.map(O=>JSON.stringify(O)).join(" | ")}`:n,w={streams:[{stream:{app:y,inquilino:i,usuario:m,level:d,...t||{},...r||{},...b||{}},values:[[_,L]]}]};return await G({objeto:w})};var $e=()=>"Ol\xE1 Mundo! (fun\xE7\xE3o)";var Me="Ol\xE1 Mundo! (vari\xE1vel)";var qe=(...e)=>e.map(o=>o==null?"":String(o).normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s+/g," ").toLowerCase()).join(" ");var v=class{constructor({caminho:o,acaoIr:t}){this._partesCaminho=[];this._acaoIr=t,this._partesCaminho=(Array.isArray(o)?o:[o]).flatMap(i=>i.split("/")).filter(Boolean)}get caminho(){return`/${this._partesCaminho.join("/")}`}set caminho(o){this._partesCaminho=o.split("/").filter(t=>t)}endereco(o,t){let i=new URL(typeof window<"u"?window.location.href:"http://localhost");i.pathname=this.caminho,i.search="";let m=Object.entries(o);for(let[r,d]of m)i.searchParams.set(String(r),d??"");return i.hash="",t&&(i.hash=`#${i.search}`,i.search=""),i.href}ir(o){this._acaoIr?this._acaoIr(this.endereco(o)):typeof window<"u"&&(window.location.href=this.endereco(o))}get parametros(){let o=new URL(typeof window<"u"?window.location.href:"http://localhost"),t=o.searchParams,i=Object.fromEntries(t.entries()),m=o.hash;if(m){let r=Object.fromEntries(new URLSearchParams(m.slice(1)).entries());return{...i,...r}}return i}};var D=(r=>(r.UN="UN",r.KG="KG",r.TON="TON",r.g="g",r["M\xB3"]="M\xB3",r.Lt="Lt",r))(D||{}),Fe=[{sigla_unidade:"KG",nome:"Quilograma",sigla_normalizada:"KG",normalizar:e=>e,tipo:"massa"},{sigla_unidade:"g",nome:"Grama",sigla_normalizada:"KG",normalizar:e=>e/1e3,tipo:"massa"},{sigla_unidade:"TON",nome:"Tonelada",sigla_normalizada:"KG",normalizar:e=>e*1e3,tipo:"massa"},{sigla_unidade:"Lt",nome:"Litro",sigla_normalizada:"Lt",normalizar:e=>e,tipo:"volume"},{sigla_unidade:"M\xB3",nome:"Metro C\xFAbico",sigla_normalizada:"Lt",normalizar:e=>e*1e3,tipo:"volume"},{sigla_unidade:"UN",nome:"Unidade",sigla_normalizada:"UN",normalizar:e=>e,tipo:"unidade"}];import{NIL as E,v3 as V,v4 as J}from"uuid";var B=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ee=e=>B.test(String(e||"")),R=(e,o)=>V(typeof e=="string"?e:typeof e=="number"?String(e):JSON.stringify(e),o?R(o):E),Q=J,Ve=Q;export{v as TipagemRotas,W as aleatorio,x as cacheM,oe as cacheMFixo,ee as cacheMemoria,k as camposComuns,ve as cdn_carro_de_boi,a as dayjsbr,Te as defineCwd,B as erUuid,we as esperar,q as extensoes,ze as logger,u as nomeVariavel,z as operadores,G as postLogger,D as siglas_unidades_medida,qe as texto_busca,_e as tipoArquivo,T as tipoUsuarioResiduos,j as tx,$e as umaFuncao,Me as umaVariavel,Fe as unidades_medida,Ve as uuid,R as uuidV3,Q as uuidV4,ie as uuid_null,Ee as validarUuid,Z as verCacheM}; +var f="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),X=e=>`eli-${Array.from({length:e||8}).map(()=>f[(999*Math.random()|0)%f.length]).join("")}`;var l={},x=(e,o,t)=>{let i=typeof e=="string"?e:typeof e=="number"?String(e):encodeURIComponent(JSON.stringify(e)),m=t&&new Date().getTime()+t*1e3;o!==void 0&&(l[i]={valor:o,validade:m});let r=l[i];if(!(r?.validade&&r.validadel,oe=x,te=e=>o=>x(e,o);var re="00000000-0000-0000-0000-000000000000",k=(n=>(n.codigo="codigo",n.excluido="excluido",n.data_hora_criacao="data_hora_criacao",n.data_hora_atualizacao="data_hora_atualizacao",n.codigo_usuario_criacao="codigo_usuario_criacao",n.codigo_usuario_atualizacao="codigo_usuario_atualizacao",n.versao="versao",n))(k||{}),T=(o=>(o.token="token",o))(T||{}),z=(t=>(t.Usuario="usuario",t.Fornecedor="fornecedor",t))(z||{});var S=(t=>(t["="]="=",t["!="]="!=",t[">"]=">",t[">="]=">=",t["<"]="<",t["<="]="<=",t.like="like",t.in="in",t))(S||{});import a from"dayjs";import"dayjs/locale/pt-br";import $ from"dayjs/plugin/duration";import N from"dayjs/plugin/isSameOrAfter";import M from"dayjs/plugin/isSameOrBefore";import P from"dayjs/plugin/minMax";import E from"dayjs/plugin/relativeTime";import U from"dayjs/plugin/timezone";import A from"dayjs/plugin/utc";import I from"dayjs/plugin/weekOfYear";a.extend(A);a.extend(U);a.extend(I);a.extend(M);a.extend(N);a.extend(P);a.extend(E);a.extend($);a.locale("pt-br");var he="https://carro-de-boi-idz-one.b-cdn.net";var q=[{ext:"gif",tipo:"imagem",mime:"image/gif"},{ext:"jpg",tipo:"imagem",mime:"image/jpeg"},{ext:"jpeg",tipo:"imagem",mime:"image/jpeg"},{ext:"png",tipo:"imagem",mime:"image/png"},{ext:"bmp",tipo:"imagem",mime:"image/bmp"},{ext:"webp",tipo:"imagem",mime:"image/webp"},{ext:"tiff",tipo:"imagem",mime:"image/tiff"},{ext:"svg",tipo:"imagem",mime:"image/svg+xml"},{ext:"ico",tipo:"imagem",mime:"image/x-icon"},{ext:"pdf",tipo:"documento",mime:"application/pdf"},{ext:"doc",tipo:"documento",mime:"application/msword"},{ext:"docx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},{ext:"xls",tipo:"documento",mime:"application/vnd.ms-excel"},{ext:"xlsx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},{ext:"ppt",tipo:"documento",mime:"application/vnd.ms-powerpoint"},{ext:"pptx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"},{ext:"txt",tipo:"documento",mime:"text/plain"},{ext:"odt",tipo:"documento",mime:"application/vnd.oasis.opendocument.text"},{ext:"ods",tipo:"documento",mime:"application/vnd.oasis.opendocument.spreadsheet"},{ext:"rtf",tipo:"documento",mime:"application/rtf"},{ext:"csv",tipo:"documento",mime:"text/csv"},{ext:"mp4",tipo:"v\xEDdeo",mime:"video/mp4"},{ext:"avi",tipo:"v\xEDdeo",mime:"video/x-msvideo"},{ext:"mkv",tipo:"v\xEDdeo",mime:"video/x-matroska"},{ext:"mov",tipo:"v\xEDdeo",mime:"video/quicktime"},{ext:"wmv",tipo:"v\xEDdeo",mime:"video/x-ms-wmv"},{ext:"flv",tipo:"v\xEDdeo",mime:"video/x-flv"},{ext:"webm",tipo:"v\xEDdeo",mime:"video/webm"},{ext:"3gp",tipo:"v\xEDdeo",mime:"video/3gpp"},{ext:"mpeg",tipo:"v\xEDdeo",mime:"video/mpeg"}],we=e=>{let o=String(e||"").toLocaleLowerCase().split(".").pop();return q.find(i=>i.ext===o)?.tipo||"outros"};import K from"cross-fetch";var Oe=e=>new Promise(o=>setTimeout(()=>o(!0),e)),u=e=>Object.keys(e).join("/");var C="https://log.idz.one",F="/loki/api/v1/push",G=async({objeto:e})=>{let o=await K(`${C}${F}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}).catch(t=>t);return o.ok?[e]:[e,`Erro ${o.status}: ${await o?.text?.()}`]},g="",ze=e=>{g=e},Se=({app:e,eProducao:o,parametros:t})=>({inquilino:i,usuario:m,parametros:r})=>async(c,n,y)=>{let{__filename:s,detalhes:p,local:d,parametros:v}=y||{},_=`${o?"":"DEV-"}${e}`;g&&s&&(s=s.replace(g,"")),d&&(p=[`${u({local:d})}="${d}"`,...p||[]]),s&&(p=[`${u({__filename:s})}="${s}"`,...p||[]]);let w=`${Date.now()}000000`,L=p?.length?`${n} | ${p.map(j=>JSON.stringify(j)).join(" | ")}`:n,O={streams:[{stream:{app:_,inquilino:i,usuario:m,level:c,...t||{},...r||{},...v||{}},values:[[w,L]]}]};return await G({objeto:O})};var b=e=>{try{return Object.fromEntries(Object.entries(e).map(([o,t])=>[o,t===void 0||t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"?t:JSON.stringify(t,null,2)]))}catch(o){throw new Error(`Erro na fun\xE7\xE3o paraObjetoRegistroPg: ${o.message} ${o.stack}`)}},Ne=b,Me=b;var Ee=()=>"Ol\xE1 Mundo! (fun\xE7\xE3o)";var Ae="Ol\xE1 Mundo! (vari\xE1vel)";var Fe=(...e)=>e.map(o=>o==null?"":String(o).normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s+/g," ").toLowerCase()).join(" ");var h=class{constructor({caminho:o,acaoIr:t}){this._partesCaminho=[];this._acaoIr=t,this._partesCaminho=(Array.isArray(o)?o:[o]).flatMap(i=>i.split("/")).filter(Boolean)}get caminho(){return`/${this._partesCaminho.join("/")}`}set caminho(o){this._partesCaminho=o.split("/").filter(t=>t)}endereco(o,t){let i=new URL(typeof window<"u"?window.location.href:"http://localhost");i.pathname=this.caminho,i.search="";let m=Object.entries(o);for(let[r,c]of m)i.searchParams.set(String(r),c??"");return i.hash="",t&&(i.hash=`#${i.search}`,i.search=""),i.href}ir(o){this._acaoIr?this._acaoIr(this.endereco(o)):typeof window<"u"&&(window.location.href=this.endereco(o))}get parametros(){let o=new URL(typeof window<"u"?window.location.href:"http://localhost"),t=o.searchParams,i=Object.fromEntries(t.entries()),m=o.hash;if(m){let r=Object.fromEntries(new URLSearchParams(m.slice(1)).entries());return{...i,...r}}return i}};var D=(r=>(r.UN="UN",r.KG="KG",r.TON="TON",r.g="g",r["M\xB3"]="M\xB3",r.Lt="Lt",r))(D||{}),Ve=[{sigla_unidade:"KG",nome:"Quilograma",sigla_normalizada:"KG",normalizar:e=>e,tipo:"massa"},{sigla_unidade:"g",nome:"Grama",sigla_normalizada:"KG",normalizar:e=>e/1e3,tipo:"massa"},{sigla_unidade:"TON",nome:"Tonelada",sigla_normalizada:"KG",normalizar:e=>e*1e3,tipo:"massa"},{sigla_unidade:"Lt",nome:"Litro",sigla_normalizada:"Lt",normalizar:e=>e,tipo:"volume"},{sigla_unidade:"M\xB3",nome:"Metro C\xFAbico",sigla_normalizada:"Lt",normalizar:e=>e*1e3,tipo:"volume"},{sigla_unidade:"UN",nome:"Unidade",sigla_normalizada:"UN",normalizar:e=>e,tipo:"unidade"}];import{NIL as V,v3 as J,v4 as R}from"uuid";var B=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Be=e=>B.test(String(e||"")),Q=(e,o)=>J(typeof e=="string"?e:typeof e=="number"?String(e):JSON.stringify(e),o?Q(o):V),Y=R,Qe=Y;export{h as TipagemRotas,X as aleatorio,x as cacheM,te as cacheMFixo,oe as cacheMemoria,k as camposComuns,he as cdn_carro_de_boi,a as dayjsbr,ze as defineCwd,B as erUuid,Oe as esperar,q as extensoes,Se as logger,u as nomeVariavel,Me as objetoPg,S as operadores,b as paraObjetoRegistroPg,Ne as pgObjeto,G as postLogger,D as siglas_unidades_medida,Fe as texto_busca,we as tipoArquivo,z as tipoUsuarioResiduos,T as tx,Ee as umaFuncao,Ae as umaVariavel,Ve as unidades_medida,Qe as uuid,Q as uuidV3,Y as uuidV4,re as uuid_null,Be as validarUuid,ee as verCacheM}; diff --git a/package.json b/package.json index 2f977fc..91bdcdf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "p-comuns", - "version": "0.217.0", + "version": "0.218.0", "description": "", "main": "./dist-back/index.js", "module": "./dist-front/index.mjs", diff --git a/src/index.ts b/src/index.ts index 18d1911..3b91422 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,7 @@ export * from "./dayjs" export * from "./ecosistema" export * from "./extensoes" export * from "./logger" +export * from "./postgres" export * from "./testes-de-variaveis" export * from "./texto_busca" export * from "./tipagemRotas" diff --git a/src/postgres.ts b/src/postgres.ts new file mode 100644 index 0000000..e3e1787 --- /dev/null +++ b/src/postgres.ts @@ -0,0 +1,32 @@ +/** + * Trata um objeto para ser imput para postgres + * @param entrada + * @returns + */ +export const paraObjetoRegistroPg = (entrada: { + [k: string]: any +}): { + [k: string]: string | boolean | null | undefined | number +} => { + try { + return Object.fromEntries( + Object.entries(entrada).map(([k, v]) => [ + k, + v === undefined || v == null + ? v + : typeof v == "string" || + typeof v == "number" || + typeof v == "boolean" + ? v + : JSON.stringify(v, null, 2), + ]), + ) + } catch (error) { + throw new Error( + `Erro na função paraObjetoRegistroPg: ${(error as Error).message} ${(error as Error).stack}`, + ) + } +} + +export const pgObjeto = paraObjetoRegistroPg +export const objetoPg = paraObjetoRegistroPg