projeto-hit/backend/src/helpers/WhatsCache.ts

255 lines
6.0 KiB
TypeScript
Raw Normal View History

2022-11-17 14:40:37 +00:00
import Redis from 'ioredis'
import { type } from 'os'
const unflatten = require('flat').unflatten
var flatten = require('flat')
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber"
import { redisConn } from './TicketCache'
import Whatsapp from "../models/Whatsapp";
import { response } from 'express'
2022-11-17 14:40:37 +00:00
const deleteWhatsappCache = async (hash: any) => {
2022-11-17 14:40:37 +00:00
const redis: any = await redisConn();
if (!redis) return
2022-11-17 14:40:37 +00:00
if (redis.status !== 'connect') return
const whatsapp_cache: any = await redis.hgetall(hash)
try {
if (whatsapp_cache && Object.keys(whatsapp_cache).length > 0) {
await redis.del(hash)
console.log(`Whatsapp cache number ${whatsapp_cache['number']} deleted!`)
}
else {
console.log('WHATSAPP CACHE NOT FOUND!')
}
} catch (error) {
console.log(`There was an error on deleteWhatsappCache: ${error}`)
}
await redis.quit()
2022-11-17 14:40:37 +00:00
}
const updateWhatsappCache = async (hash: any, json_object: any) => {
const redis: any = await redisConn();
if (!redis) return
2022-11-17 14:40:37 +00:00
if (redis.status !== 'connect') return
const pipeline = redis.pipeline()
let entries = Object.entries(json_object)
entries.forEach((e: any) => {
pipeline.hset(hash, e[0], e[1])
})
await pipeline.exec(() => { console.log("whatsapp Key/value inserted/updated") });
await redis.quit()
2022-11-17 14:40:37 +00:00
}
const updateWhatsappCacheById = async (hash: any, update_fields: object | any) => {
2022-11-17 14:40:37 +00:00
const redis: any = await redisConn();
if (!redis) return
2022-11-17 14:40:37 +00:00
if (redis.status !== 'connect') return
const whatsapp_cache: any = await redis.hgetall(hash)
try {
if (whatsapp_cache && Object.keys(whatsapp_cache).length > 0) {
2022-11-17 14:40:37 +00:00
// update_fields.escaped_name = escapeCharCache(update_fields.name)
await updateWhatsappCache(hash, update_fields)
console.log(`WHATSAPP ${whatsapp_cache['number']} CACHE WAS UPDATED!`)
}
else {
console.log('WHATSAPP CACHE NOT FOUND!')
}
} catch (error) {
console.log(`There was an error on updateWhatsappCacheById: ${error}`)
}
await redis.quit()
2022-11-17 14:40:37 +00:00
}
// const createOrUpdateContactCache = async (hash: any, contact: any) => {
// const redis: any = await redisConn();
// if(!redis) return
// if (redis.status !== 'connect') return
// if (contact.name) {
// contact.escaped_name = escapeCharCache(contact.name)
// }
// await redis.hmset(hash, contact);
// redis.quit()
// }
async function searchWhatsappCache(id: string, status: string) {
2022-11-17 14:40:37 +00:00
const redis: any = await redisConn();
if (!redis) return
2022-11-17 14:40:37 +00:00
if (redis.status !== 'connect') return null
2022-11-17 14:40:37 +00:00
const number_cache: any = await redis.hgetall(`whatsapp:${id}`)
if (Object.entries(number_cache).length == 0) {
await redis.quit()
return []
}
2022-12-14 12:29:42 +00:00
// console.log('NUMBER_CACHED: ', number_cache)
// @x:foo @y:bar
const response: any = await redis.call('FT.SEARCH', 'idx_whatsapp', `(@status:*${status}*) (@number:*${number_cache.number}*)`, 'SORTBY', 'status', 'ASC')
await redis.quit()
2022-11-17 14:40:37 +00:00
if (response.length === 1) {
return []
}
const results: any = []
for (let n = 2; n < response.length; n += 2) {
const result: any = {}
const fieldNamesAndValues = response[n]
for (let m = 0; m < fieldNamesAndValues.length; m += 2) {
const k = fieldNamesAndValues[m]
const v = fieldNamesAndValues[m + 1]
result[k] = v
}
results.push(result)
}
return results
}
const insertOrUpeateWhatsCache = async (hash: any, whatsapp: any) => {
2022-11-17 14:40:37 +00:00
const redis: any = await redisConn();
if (!redis) return
2022-11-17 14:40:37 +00:00
if (redis.status !== 'connect') return
2022-11-17 14:40:37 +00:00
if (Array.isArray(whatsapp)) {
2022-11-17 14:40:37 +00:00
const pipeline = redis.pipeline()
for (let i = 0; i < whatsapp.length; i++) {
2022-11-17 14:40:37 +00:00
pipeline.hmset(hash, whatsapp[i]);
}
2022-11-17 14:40:37 +00:00
await pipeline.exec(() => { console.log(`${whatsapp.length} WHATSAPP INSERTED IN CACHE!`) });
}
else {
await redis.hmset(hash, JSON.parse(JSON.stringify(whatsapp)));
2022-11-17 14:40:37 +00:00
console.log(`WHATSAPP ID ${whatsapp.id} INSERTED OR UPADTED IN CACHE!`)
2022-11-17 14:40:37 +00:00
}
await redis.quit()
2022-11-17 14:40:37 +00:00
}
const loadWhatsappCache = async () => {
await createWhatsappIndexCache('idx_whatsapp')
const redis: any = await redisConn();
if (!redis) return
2022-11-17 14:40:37 +00:00
if (redis.status !== 'connect') return
2022-11-17 14:40:37 +00:00
let whatsapps: any = await Whatsapp.findAll({ raw: true })
2022-11-17 14:40:37 +00:00
const pipeline = redis.pipeline()
for (let i = 0; i < whatsapps.length; i++) {
whatsapps[i].createdAt = new Date(whatsapps[i].createdAt).toISOString()
whatsapps[i].updatedAt = new Date(whatsapps[i].updatedAt).toISOString()
// whatsapps[i].escaped_name = escapeCharCache(whatsapps[i].name)
pipeline.hmset(`whatsapp:${whatsapps[i].id}`, whatsapps[i]);
}
await pipeline.exec(() => { console.log(`${whatsapps.length} WHATSAPPS INSERTED IN CACHE!`) });
await redis.quit()
2022-11-17 14:40:37 +00:00
}
const createWhatsappIndexCache = async (hashIndex: string) => {
const redis: any = await redisConn();
if (!redis) return
2022-11-17 14:40:37 +00:00
if (redis.status !== 'connect') return
try {
const lst_index_redis: any = await redis.call('FT._LIST')
if (lst_index_redis.includes(hashIndex)) {
console.log('entrou...')
await redis.call('FT.DROPINDEX', hashIndex)
}
const response = await redis.call('FT.CREATE', hashIndex, 'ON', 'HASH', 'PREFIX', '1', 'whatsapp:', 'SCHEMA', 'id', 'NUMERIC', 'status', 'TEXT', 'SORTABLE', 'number', 'TEXT', 'SORTABLE')
2022-11-17 14:40:37 +00:00
console.log('Whatsapp index created: ', response)
} catch (error) {
console.log('There was an error on createWhatsappIndexCache: ', error)
}
await redis.quit()
2022-11-17 14:40:37 +00:00
}
export {
loadWhatsappCache,
searchWhatsappCache,
updateWhatsappCacheById,
2022-11-17 14:40:37 +00:00
insertOrUpeateWhatsCache,
deleteWhatsappCache
}