- Updated `sp-test.ts` to enhance argument parsing and error handling for sellability checks. - Refactored `types.ts` to maintain consistent formatting and improve readability. - Improved `writer.ts` for better result handling and CSV writing, ensuring clarity in output. - Adjusted `tsconfig.json` formatting for consistency and readability.
67 lines
1.5 KiB
TypeScript
67 lines
1.5 KiB
TypeScript
import Redis from "ioredis";
|
|
import { config } from "./config.ts";
|
|
import type { EnrichedProduct } from "./types.ts";
|
|
|
|
let redis: Redis | null = null;
|
|
let disabled = false;
|
|
|
|
export async function connectCache(): Promise<void> {
|
|
if (disabled) return;
|
|
try {
|
|
redis = new Redis(config.redisUrl, {
|
|
maxRetriesPerRequest: 1,
|
|
connectTimeout: 3000,
|
|
lazyConnect: true,
|
|
retryStrategy: () => null,
|
|
reconnectOnError: () => false,
|
|
});
|
|
// Swallow connection-level errors after we intentionally disable cache.
|
|
redis.on("error", () => {
|
|
// no-op
|
|
});
|
|
await redis.connect();
|
|
console.log("Redis connected");
|
|
} catch (err) {
|
|
console.warn(`Redis unavailable, running without cache: ${err}`);
|
|
if (redis) {
|
|
redis.disconnect();
|
|
}
|
|
redis = null;
|
|
disabled = true;
|
|
}
|
|
}
|
|
|
|
export async function getCache(asin: string): Promise<EnrichedProduct | null> {
|
|
if (!redis) return null;
|
|
try {
|
|
const data = await redis.get(`asin:${asin}`);
|
|
return data ? JSON.parse(data) : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function setCache(
|
|
asin: string,
|
|
data: EnrichedProduct,
|
|
): Promise<void> {
|
|
if (!redis) return;
|
|
try {
|
|
await redis.set(
|
|
`asin:${asin}`,
|
|
JSON.stringify(data),
|
|
"EX",
|
|
config.cacheTtl,
|
|
);
|
|
} catch {
|
|
// Non-critical, continue without caching
|
|
}
|
|
}
|
|
|
|
export async function disconnectCache(): Promise<void> {
|
|
if (redis) {
|
|
await redis.quit();
|
|
redis = null;
|
|
}
|
|
}
|