Skip to content

Commit

Permalink
Close open test handles
Browse files Browse the repository at this point in the history
  • Loading branch information
Joel Lefkowitz committed Feb 5, 2024
1 parent 62e6e95 commit a974873
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 17 deletions.
33 changes: 21 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,27 @@ Documentation and more detailed examples are hosted on [Github Pages](https://jo

## Usage

To implement a cache we need to divert the prisma client's internals so that we
```ts
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:

```ts
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.

Expand All @@ -42,17 +62,6 @@ 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:

```ts
import { LruCache } from "cached-prisma";

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

## Minimal example

Create a prisma schema.
Expand Down
11 changes: 6 additions & 5 deletions src/Memcached.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ describe("Memcached", () => {

expect(await cache.read("a")).toBe("1");
expect(await cache.read("b")).toBeNull();
cache.close();
});

it("should update entries.", async () => {
Expand All @@ -15,16 +16,16 @@ describe("Memcached", () => {
await cache.write("a", "2");

expect(await cache.read("a")).toBe("2");
cache.close();
});

it("should not cache for longer than its set lifetime.", async () => {
const cache = new Memcached("127.0.0.1:11211", 1);

await cache.write("a", "1");
await new Promise((resolve) => setTimeout(resolve, 1000));

setTimeout(() => {
cache.read("a").then((read) => {
expect(read).toBeNull();
});
}, 1000);
expect(await cache.read("a")).toBeNull();
cache.close();
});
});
4 changes: 4 additions & 0 deletions src/Memcached.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,8 @@ export class Memcached implements Cache {
});
});
}

close(): void {
this.client.end();
}
}

0 comments on commit a974873

Please sign in to comment.