From c82a7ab75675b8fe45912febd5bf69a1cd3d2e23 Mon Sep 17 00:00:00 2001 From: WebStreamr <210764791+webstreamr@users.noreply.github.com> Date: Sun, 31 Aug 2025 19:14:43 +0000 Subject: [PATCH] chore(source): cache source results for 3 hours --- src/source/PrimeWire.ts | 1 + src/source/Source.ts | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/source/PrimeWire.ts b/src/source/PrimeWire.ts index 54abcdf..4f1e3c5 100644 --- a/src/source/PrimeWire.ts +++ b/src/source/PrimeWire.ts @@ -70,6 +70,7 @@ export class PrimeWire extends Source { .map(async (redirectUrl) => { let targetUrl = this.redirectUrlCache.get(redirectUrl.href); + /* istanbul ignore if */ if (!targetUrl) { const linkFetchUrl = new URL(redirectUrl.href.replace('/gos/', '/go/')); linkFetchUrl.searchParams.set('token', linksToken); diff --git a/src/source/Source.ts b/src/source/Source.ts index a2ee5a2..71dd54f 100644 --- a/src/source/Source.ts +++ b/src/source/Source.ts @@ -1,3 +1,4 @@ +import TTLCache from '@isaacs/ttlcache'; import { ContentType } from 'stremio-addon-sdk'; import { Context, CountryCode } from '../types'; import { Id } from '../utils'; @@ -13,15 +14,30 @@ export abstract class Source { public abstract readonly label: string; + public readonly ttl: number = 10800000; // 3h + public abstract readonly contentTypes: ContentType[]; public abstract readonly countryCodes: CountryCode[]; public abstract readonly baseUrl: string; + private readonly sourceResultCache: TTLCache; + + public constructor() { + this.sourceResultCache = new TTLCache({ max: 1024, ttl: this.ttl }); + } + protected abstract handleInternal(ctx: Context, type: ContentType, id: Id): Promise<(SourceResult[])>; public async handle(ctx: Context, type: ContentType, id: Id): Promise<(SourceResult[])> { - return await this.handleInternal(ctx, type, id); + if (this.sourceResultCache.has(id.id)) { + return this.sourceResultCache.get(id.id) as SourceResult[]; + } + + const sourceResults = await this.handleInternal(ctx, type, id); + this.sourceResultCache.set(id.id, sourceResults); + + return sourceResults; } }