feat: added redis
This commit is contained in:
parent
bfe4725537
commit
2fa46d65ae
33
lib/cache.ts
Normal file
33
lib/cache.ts
Normal file
@ -0,0 +1,33 @@
|
||||
import { connect } from "https://deno.land/x/redis/mod.ts";
|
||||
|
||||
const REDIS_HOST = Deno.env.get("REDIS_HOST");
|
||||
const REDIS_PASS = Deno.env.get("REDIS_PASS");
|
||||
const REDIS_PORT = Deno.env.get("REDIS_PORT");
|
||||
|
||||
async function createCache() {
|
||||
if (REDIS_HOST && REDIS_PASS) {
|
||||
const client = await connect({
|
||||
password: REDIS_PASS,
|
||||
hostname: REDIS_HOST,
|
||||
port: REDIS_PORT || 6379,
|
||||
});
|
||||
console.log("COnnected to redis");
|
||||
return client;
|
||||
}
|
||||
|
||||
return new Map<string, any>();
|
||||
}
|
||||
|
||||
const cache = await createCache();
|
||||
|
||||
export function get(id: string) {
|
||||
return cache.get(id);
|
||||
}
|
||||
|
||||
export function has(id: string) {
|
||||
return cache.has(id);
|
||||
}
|
||||
|
||||
export function set(id: string, content: any) {
|
||||
return cache.set(id, content);
|
||||
}
|
@ -5,11 +5,10 @@ import {
|
||||
MagickGeometry,
|
||||
} from "https://deno.land/x/imagemagick_deno@0.0.14/mod.ts";
|
||||
import { parseMediaType } from "https://deno.land/std@0.175.0/media_types/parse_media_type.ts";
|
||||
import * as cache from "../../../../lib/cache.ts";
|
||||
|
||||
await initializeImageMagick();
|
||||
|
||||
const cache = new Map<string, Promise<Response>>();
|
||||
|
||||
async function getRemoteImage(image: string) {
|
||||
const sourceRes = await fetch(image);
|
||||
if (!sourceRes.ok) {
|
||||
@ -76,7 +75,6 @@ function parseParams(reqUrl: URL) {
|
||||
}
|
||||
|
||||
async function getImageResponse(
|
||||
imageUrl: string,
|
||||
remoteImage: { buffer: Uint8Array; mediaType: string },
|
||||
params: { width: number; height: number },
|
||||
): Promise<Response> {
|
||||
@ -110,8 +108,8 @@ export const handler = async (
|
||||
}
|
||||
|
||||
const imageId = `${imageUrl}.${params.width}.${params.height}`;
|
||||
if (cache.has(imageId)) {
|
||||
return (await cache.get(imageId)!).clone();
|
||||
if (await cache.has(imageId)) {
|
||||
return (await (await cache.get(imageId)!)).clone();
|
||||
}
|
||||
|
||||
const remoteImage = await getRemoteImage(imageUrl);
|
||||
@ -119,9 +117,9 @@ export const handler = async (
|
||||
return new Response(remoteImage, { status: 400 });
|
||||
}
|
||||
|
||||
const response = getImageResponse(imageUrl, remoteImage, params);
|
||||
const response = getImageResponse(remoteImage, params);
|
||||
|
||||
cache.set(imageId, response);
|
||||
await cache.set(imageId, response);
|
||||
|
||||
return response;
|
||||
};
|
||||
|
Loading…
x
Reference in New Issue
Block a user