melhorias de caches

This commit is contained in:
Luiz Silva 2025-07-16 11:20:53 -03:00
parent 29ae7400cf
commit 00e9c4d698
18 changed files with 210 additions and 66 deletions

View file

@ -1,5 +1,7 @@
import cFetch from "cross-fetch"
import { respostaComuns, type tipoResposta } from "p-respostas"
import { cacheAuDrive } from "./plugins/node-cache"
import { uuidV3 } from "./plugins/uuid"
export const tx_vinculos__listar = "vinculos__listar" as const
export type tipo_retorno_vinculo_listas = {
@ -16,33 +18,67 @@ export type tipo_retorno_vinculo_listas = {
export const listarVinculos = async ({
token,
url_api_autenticacao,
desativarCache,
}: {
url_api_autenticacao: string
token: string
/** por padrão será 10 segundos */
desativarCache?: boolean
}): Promise<tipoResposta<tipo_retorno_vinculo_listas[]>> => {
const url = `${url_api_autenticacao}/api/${tx_vinculos__listar}`
const chaveCache = uuidV3({ token, url_api_autenticacao })
return cFetch(url, {
headers: { token, "Content-Type": "application/json" },
body: "{}",
method: "post",
})
.then(async (a) => {
const texto = await a.text()
// Buscar promeiro no cache
if (!desativarCache) {
const valorCache =
cacheAuDrive.get<Promise<tipoResposta<tipo_retorno_vinculo_listas[]>>>(
chaveCache,
)
if (valorCache) return valorCache
}
try {
const res: tipoResposta<tipo_retorno_vinculo_listas[]> =
JSON.parse(texto)
const res = (async () => {
const url = `${url_api_autenticacao}/api/${tx_vinculos__listar}`
return res
} catch (error: any) {
return respostaComuns.erro(`Erro ao listar cidades: ${error.message}`, [
texto,
error,
])
}
return cFetch(url, {
headers: { token, "Content-Type": "application/json" },
body: "{}",
method: "post",
})
.catch((error) =>
respostaComuns.erro(`Erro ao listar cidades: ${error.message}`, [error]),
)
.then(async (a) => {
const texto = await a.text()
try {
const res: tipoResposta<tipo_retorno_vinculo_listas[]> =
JSON.parse(texto)
return res
} catch (error: any) {
return respostaComuns.erro(
`Erro ao listar cidades: ${error.message}`,
[texto, error],
)
}
})
.catch((error) =>
respostaComuns.erro(`Erro ao listar cidades: ${error.message}`, [
error,
]),
)
})()
cacheAuDrive.set(
chaveCache,
res.then((a) => {
try {
if (a.eErro) {
cacheAuDrive.del(chaveCache)
}
} catch {}
return a
}),
10,
)
return res
}

View file

@ -0,0 +1,3 @@
import NodeCache from "node-cache"
export const cacheAuDrive = new NodeCache()

13
src/plugins/uuid.ts Normal file
View file

@ -0,0 +1,13 @@
import { NIL, v3, v4 } from "uuid"
export const uuidV3 = (qualquerCoisa: any) =>
v3(
typeof qualquerCoisa == "string"
? qualquerCoisa
: typeof qualquerCoisa == "number"
? String(qualquerCoisa)
: JSON.stringify(qualquerCoisa),
NIL,
)
export const uuidV4 = v4