Skip to content

Commit

Permalink
feat: add cache for link preview
Browse files Browse the repository at this point in the history
  • Loading branch information
darkskygit committed Dec 18, 2024
1 parent 094e36f commit 86da9ba
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion packages/backend/server/src/plugins/worker/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
import type { Request, Response } from 'express';
import { HTMLRewriter } from 'htmlrewriter';

import { BadRequest, Config, URLHelper } from '../../fundamentals';
import { BadRequest, Cache, Config, URLHelper } from '../../fundamentals';
import type { LinkPreviewRequest, LinkPreviewResponse } from './types';
import {
appendUrl,
Expand All @@ -31,6 +31,7 @@ export class WorkerController {

constructor(
config: Config,
private readonly cache: Cache,
private readonly url: URLHelper
) {
this.allowedOrigin = [
Expand Down Expand Up @@ -138,6 +139,17 @@ export class WorkerController {
this.logger.debug('Processing request', { origin, url: targetURL });

try {
const cachedResponse = await this.cache.get<string>(targetURL.toString());
if (cachedResponse) {
return resp
.status(200)
.header({
'content-type': 'application/json;charset=UTF-8',
...getCorsHeaders(origin),
})
.send(cachedResponse);
}

const response = await fetch(targetURL, {
headers: cloneHeader(request.headers),
});
Expand Down Expand Up @@ -245,6 +257,7 @@ export class WorkerController {
responseSize: json.length,
});

await this.cache.set(targetURL.toString(), res);
return resp
.status(200)
.header({
Expand Down

0 comments on commit 86da9ba

Please sign in to comment.