cached-prisma
cached-prisma copied to clipboard
A Prisma client abstraction that simplifies caching.
Cached Prisma
A Prisma client abstraction that simplifies caching.
Status
Source | Shields |
---|---|
Project | |
Health | |
Publishers | |
Repository | |
Activity |
Installing
npm i cached-prisma
Usage
To implement a cache we need to divert the prisma client's internals so that we can return cached values without hitting the database. To do this we can use readonly singleton instances for the client and cache objects.
import { Prisma } from 'cached-prisma';
const client1 = new Prisma().client;
const client2 = new Prisma().client;
client1 === client2;
import { Prisma } from 'cached-prisma';
const cache1 = new Prisma().cache;
const cache2 = new Prisma().cache;
cache1 === cache2;
The caching mechanism should be configurable. To control the object used for cache storage you can extend the Prisma class:
import { LruCache } from 'cached-prisma';
class CustomPrisma extends Prisma {
cacheFactory = () => new LruCache(100);
}
Minimal example
Create a prisma schema.
datasource db {
url = env("DATABASE_URL")
provider = "postgresql"
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
name String
}
Create a database. In this example we create a postgres container. You can switch db, user and password for your environment.
docker run --rm -d \
-p 5432:5432 \
-e POSTGRES_DB=db \
-e POSTGRES_USER=user \
-e POSTGRES_PASSWORD=password \
postgres:13
Define the DATABASE_URL environment variable mentioned in our prisma schema.
export DATABASE_URL=postgresql://user:password@localhost:5432/db
Generate the types for your client.
prisma generate
Migrate the database.
prisma migrate dev
Now we can create our client:
import { Prisma } from 'cached-prisma';
const client = new Prisma().client;
client.user.create({ data: { name: 'Joel' } });
Advanced concepts
The default cache is a fixed size queue that pops values as it surpasses its maximum length.
import LruMap from 'collections/lru-map';
new LruCache(100);
Memcached support is provided out of the box:
import { Memcached } from 'cached-prisma';
class CustomPrisma extends Prisma {
cacheFactory = () => new Memcached('127.0.0.1:11211', 10);
}
The second parameter to the Memcached constructor is the storage lifetime of each write in seconds.
Caches implement safe read and write methods:
export type Maybe<T> = T | null;
export interface Cache {
read: (key: string) => Maybe<string>;
write: (key: string, value: string) => void;
}
export interface AsyncCache {
read: (key: string) => Promise<Maybe<string>>;
write: (key: string, value: string) => Promise<void>;
}
We cache the following methods which do not mutate state:
- findUnique
- findMany
- findFirst
- queryRaw
- aggregate
- count
After any of the following state mutating methods we flush the cache:
- create
- createMany
- delete
- deleteMany
- executeRaw
- update
- updateMany
- upsert
Running locally
git clone https://github.com/JoelLefkowitz/cached-prisma.git
To start up a postgres and memcached container:
grunt database
grunt caches
Tests
To run tests:
grunt test
Profiling
Local performance profilers are included as a sanity check:
grunt profile
1000 read calls:
┌───────────────┬─────────────┐
│ (index) │ time /s │
├───────────────┼─────────────┤
│ Without cache │ 2.778027378 │
│ LruMap cache │ 0.106343917 │
│ Memcached │ 0.136733023 │
└───────────────┴─────────────┘
1000 read and write calls:
┌───────────────┬────────-─────┐
│ (index) │ time /s │
├───────────────┼──────────────┤
│ Without cache │ 11.241554884 │
│ LruMap cache │ 18.793905985 │
│ Memcached │ 18.799760361 │
└───────────────┴──────────────┘
Documentation
This repository's documentation is hosted on readthedocs.
Tooling
To run linters:
grunt lint
To run formatters:
grunt format
Continuous integration
This repository uses github actions to lint and test each commit. Formatting tasks and writing/generating documentation must be done before committing new code.
Versioning
This repository adheres to semantic versioning standards. For more information on semantic versioning visit SemVer.
Bump2version is used to version and tag changes. For example:
bump2version patch
Changelog
Please read this repository's changelog for details on changes that have been made.
Contributing
Please read this repository's guidelines on contributing for details on the process for submitting pull requests. Moreover, our code of conduct declares our collaboration standards.
Contributors
- Joel Lefkowitz - Initial work - Joel Lefkowitz
Remarks
Lots of love to the open source community!