npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cached-prisma

v1.4.0

Published

A Prisma client abstraction that simplifies caching.

Downloads

4,526

Readme

Cached Prisma

A Prisma client abstraction that simplifies caching.

Review Version Downloads Size Quality Coverage

1000 read calls:
┌─────────────────┬─────────────┐
│     (index)     │   time /s   │
├─────────────────┼─────────────┤
│  Without cache  │ 0.982411792 │
│  LruMap cache   │  0.034117   │
│ Memcached cache │ 0.053526041 │
│   Redis cache   │ 0.046146417 │
└─────────────────┴─────────────┘

1000 read and write calls:
┌─────────────────┬─────────────┐
│     (index)     │   time /s   │
├─────────────────┼─────────────┤
│  Without cache  │ 2.298558208 │
│  LruMap cache   │  2.304989   │
│ Memcached cache │ 2.305258458 │
│   Redis cache   │ 2.307943167 │
└─────────────────┴─────────────┘

Installing

npm install cached-prisma

Documentation

Documentation and more detailed examples are hosted on Github Pages.

Usage

client.user.create({ data: { name: "Joel" } });

// This populates the cache
client.user.findFirst({ where: { name: "Joel" } });

// This is retrieved from the cache
client.user.findFirst({ where: { name: "Joel" } });

To control the object used for cache storage you can extend the Prisma class:

import { LruCache } from "cached-prisma";

class CustomPrisma extends Prisma {
  static override cacheFactory = () => new LruCache(100);
}

To implement the 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 a singleton instance 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;

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 the 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

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.

npx prisma generate

Migrate the database.

npx 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" } });

Discussion

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 {
  static override cacheFactory = () => new Memcached("127.0.0.1", 11211, 10);
}

Also Redis support is provided out of the box:

import { Redis } from "cached-prisma";

class CustomPrisma extends Prisma {
  static override cacheFactory = () => new Redis("127.0.0.1", 6379, 10);
}

The third constructor parameter each time is the storage lifetime of each write in seconds.

Caches implement safe read and write methods:

export interface Cache {
  read: (key: string) => Promise<Maybe<string>>;
  write: (key: string, value: string) => Promise<void>;
  flush: () => 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

Tooling

Dependencies

To install dependencies:

yarn install

Tests

To run tests:

docker run --rm -d              \
  -p 5432:5432                  \
  -e POSTGRES_DB=db             \
  -e POSTGRES_USER=user         \
  -e POSTGRES_PASSWORD=password \
  postgres

docker run --rm -d \
  -p 11211:11211   \
  memcached

docker run --rm -d \
  -p 6379:6379   \
  redis
export DATABASE_URL=postgresql://user:password@localhost:5432/db
yarn prisma generate --schema ./test/prisma/schema.prisma
yarn prisma migrate dev --schema ./test/prisma/schema.prisma
yarn test

Documentation

To generate the documentation locally:

yarn docs

Linters

To run linters:

yarn lint

Formatters

To run formatters:

yarn format

Contributing

Please read this repository's Code of Conduct which outlines our collaboration standards and the Changelog for details on breaking changes that have been made.

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

Contributors

Remarks

Lots of love to the open source community!