Last active
March 29, 2023 17:02
-
-
Save andenacitelli/dfee76bbc7d6b6bd141d0695937d1d44 to your computer and use it in GitHub Desktop.
Simple zlib + Prisma compressed caching implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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, | |
}, | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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