HotTRDealsBackend/workers/newDealList.worker.js
2026-02-07 22:42:02 +00:00

98 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const { Worker } = require("bullmq")
const Redis = require("ioredis")
const { getRedisConnectionOptions } = require("../services/redis/connection")
const NEW_DEAL_TTL_SECONDS = 12 * 60 * 60
const NEW_DEAL_LIMIT = 1000
function createRedisClient() {
return new Redis(getRedisConnectionOptions())
}
function parseSearchResults(results = []) {
const ids = []
for (let i = 1; i < results.length; i += 2) {
const key = results[i]
const value = results[i + 1]
try {
const [deal] = JSON.parse(value[1])
ids.push(Number(deal.id))
} catch {
const idFromKey = key.split(":")[2]
if (idFromKey) ids.push(Number(idFromKey))
}
}
return ids
}
async function buildNewDealList() {
const redis = createRedisClient()
try {
const now = Date.now()
const query = "@status:{ACTIVE}"
const results = await redis.call(
"FT.SEARCH",
"idx:deals",
query,
"SORTBY",
"createdAtTs",
"DESC",
"LIMIT",
"0",
String(NEW_DEAL_LIMIT),
"DIALECT",
"3",
"RETURN",
"1",
"$"
)
const dealIds = parseSearchResults(results)
const runId = String(now)
const payload = {
id: runId,
createdAt: new Date(now).toISOString(),
total: dealIds.length,
dealIds,
}
const key = `deals:lists:new:${runId}`
await redis.call("JSON.SET", key, "$", JSON.stringify(payload))
await redis.expire(key, NEW_DEAL_TTL_SECONDS)
await redis.set("deals:lists:new:latest", runId, "EX", NEW_DEAL_TTL_SECONDS)
return { id: runId, total: dealIds.length }
} catch (error) {
console.error("❌ buildNewDealList Hatası:", error.message)
throw error
} finally {
redis.disconnect()
}
}
async function handler() {
return buildNewDealList()
}
function startNewDealListWorker() {
const worker = new Worker("newdeal-list", handler, {
connection: getRedisConnectionOptions(),
concurrency: 1,
})
worker.on("completed", (job) => {
console.log(`✅ New Deal Listesi Bitti. Bulunan ID Sayısı: ${job.returnvalue?.total}`)
})
worker.on("failed", (job, err) => {
console.error(`❌ New Deal Worker Hatası!`, err.message)
})
return worker
}
module.exports = { startNewDealListWorker }