Skip to content

Instantly share code, notes, and snippets.

@andenacitelli
Last active March 29, 2023 17:02
Show Gist options
  • Save andenacitelli/dfee76bbc7d6b6bd141d0695937d1d44 to your computer and use it in GitHub Desktop.
Save andenacitelli/dfee76bbc7d6b6bd141d0695937d1d44 to your computer and use it in GitHub Desktop.
Simple zlib + Prisma compressed caching implementation
// Generic cache class for compressing and storing data in the database. Use it for any data where you don't need to be able to read it. Things like deterministic API calls are a great candidate.
// Also a fun experiment to play around with cache invalidation times, where the cache is only "valid" for so long.
import zlib from "zlib";
export const getCache = async (prisma: any, key: string): Promise<string | undefined> => {
const entry = await prisma.cacheEntry.findUnique({
where: {
key,
},
select: {
value: true,
},
});
if (!entry) return undefined;
return zlib.inflateSync(new Buffer(entry.value, "base64")).toString();
};
export const setCache = async (prisma: any, key: string, data: string): Promise<void> => {
const value = zlib.deflateSync(data).toString("base64");
await prisma.cacheEntry.upsert({
where: {
key,
},
update: {
value,
},
create: {
key,
value,
},
});
};
// Simple prisma model to accompany the above
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model CacheEntry {
key String @id @map("_id")
value String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment