prisma-cursorstream 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Hasan Arous (EtaBits)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # prisma-cursorstream
2
+
3
+ Prisma Stream Client Extension (Cursor-based Implementation)
4
+
5
+ ## Features
6
+
7
+ - Clean API (`for await`)
8
+ - Fully typed <img src="https://www.typescriptlang.org/favicon-32x32.png" height="16" width="16" alt="" />
9
+ - Minimal implementation. The [source](https://github.com/etabits/prisma-cursorstream/blob/main/src/index.ts) itself is well below 100 LOCs.
10
+
11
+ ## Installation & Activation
12
+
13
+ ```sh
14
+ npm install prisma-cursorstream
15
+ ```
16
+
17
+ Then, extend your prisma client like this:
18
+
19
+ ```js
20
+ import { PrismaClient } from "@prisma/client";
21
+ import cursorStream from "prisma-cursorstream";
22
+
23
+ const db = new PrismaClient().$extends(cursorStream);
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ```js
29
+ const stream = db.post.cursorStream({
30
+ // Your usual findMany args
31
+ select: {
32
+ id: true,
33
+ title: true,
34
+ },
35
+ where: {
36
+ published: true,
37
+ },
38
+ });
39
+ for await (const post of stream) {
40
+ console.log(post); // {id: 1, title: 'Hello!'}
41
+ }
42
+ ```
43
+
44
+ ## Advanced API
45
+
46
+ The following options provide additional controls over the streaming process.
47
+
48
+ - **Batch size**: The `take` property of the findMany arg is repurposed to specify how many rows are fetched each batch. Defaults to `100`
49
+ - **Pre-fill size**: Since the streaming happens asynchronously, it may be useful to fetch more rows well before current batch is completely consumed. Use the `skip` property of the findMany arg which is repurposed to specify the internal `highWaterMark` of the `Readable` stream. Defaults to double the batch size (usually `200`).
50
+ - **Batch transformation**: Sometimes you may need to pre-process the resulting rows in batches before they are consumed. This is where the `batchTransformer` comes in. If provided, it receives an array of the last fetched batch of rows, can operate on them asynchronously, and then return an array of transformed rows to be consumed instead. Types are properly handled.
51
+
52
+ ```js
53
+ const stream = db.post.cursorStream(
54
+ {
55
+ take: 42, // batches of 42 posts at a time
56
+ skip: 69, // prefetch up to 69 posts
57
+ },
58
+ {
59
+ async batchTransformer(posts) {
60
+ const translations = await translate(posts.map((p) => p.title));
61
+ return posts.map((p, i) => ({
62
+ ...p,
63
+ translatedTitle: translations[i],
64
+ }));
65
+ },
66
+ }
67
+ );
68
+
69
+ for await (const translatedPost of stream) {
70
+ console.log(translatedPost); // {..., translatedTitle: "مرحبا!"}
71
+ }
72
+ ```
@@ -0,0 +1,10 @@
1
+ import { Prisma, PrismaClientExtends } from "@prisma/client/extension";
2
+ import { DefaultArgs } from "@prisma/client/runtime/library";
3
+ declare const _default: (client: any) => PrismaClientExtends<import("@prisma/client/runtime/library").InternalArgs<{}, {
4
+ $allModels: {
5
+ cursorStream<T, A extends Prisma.Args<T, "findMany">, R extends Prisma.Result<T, A, "findMany">[number], C extends ((dataset: R[]) => Promise<unknown[]>) | undefined>(this: T, findManyArgs: A, { batchTransformer }?: {
6
+ batchTransformer?: C | undefined;
7
+ }): Iterable<C extends Function ? Awaited<ReturnType<C>>[number] extends object ? Awaited<ReturnType<C>>[number] : R : R>;
8
+ };
9
+ }, {}, {}> & DefaultArgs>;
10
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const extension_1 = require("@prisma/client/extension");
4
+ const node_stream_1 = require("node:stream");
5
+ exports.default = extension_1.Prisma.defineExtension((client) => {
6
+ return client.$extends({
7
+ model: {
8
+ $allModels: {
9
+ cursorStream(findManyArgs, { batchTransformer } = {}) {
10
+ const context = extension_1.Prisma.getExtensionContext(this);
11
+ const take = findManyArgs.take || 100;
12
+ const highWaterMark = findManyArgs.skip || take * 2;
13
+ const cursorField = Object.keys(findManyArgs.cursor || {})[0] || "id";
14
+ if (findManyArgs.select && !findManyArgs.select[cursorField]) {
15
+ throw new Error(`Must select cursor field "${cursorField}"`);
16
+ }
17
+ let cursorValue;
18
+ const readableStream = new node_stream_1.Readable({
19
+ objectMode: true,
20
+ highWaterMark,
21
+ async read() {
22
+ try {
23
+ const results = await context.findMany({
24
+ ...findManyArgs,
25
+ take,
26
+ skip: cursorValue ? 1 : 0,
27
+ cursor: cursorValue
28
+ ? {
29
+ [cursorField]: cursorValue,
30
+ }
31
+ : undefined,
32
+ });
33
+ const transformedResults = batchTransformer
34
+ ? await batchTransformer(results)
35
+ : results;
36
+ for (const result of transformedResults) {
37
+ this.push(result);
38
+ }
39
+ if (results.length < take) {
40
+ this.push(null);
41
+ return;
42
+ }
43
+ cursorValue = results[results.length - 1][cursorField];
44
+ }
45
+ catch (err) {
46
+ this.destroy(err);
47
+ }
48
+ },
49
+ });
50
+ return readableStream;
51
+ },
52
+ },
53
+ },
54
+ });
55
+ });
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "prisma-cursorstream",
3
+ "version": "0.1.0",
4
+ "description": "Prisma Stream Client Extension (Cursor-based Implementation)",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "keywords": [
8
+ "prisma-extension",
9
+ "prisma-client",
10
+ "prisma",
11
+ "streams"
12
+ ],
13
+ "author": "Hasan Arous <hasan.arous@gmail.com> (https://www.aularon.com/)",
14
+ "license": "MIT",
15
+ "devDependencies": {
16
+ "@prisma/client": "^5.1.1",
17
+ "@types/node": "^20.5.1",
18
+ "typescript": "^5.1.6"
19
+ },
20
+ "peerDependencies": {
21
+ "@prisma/client": "^5.1.1"
22
+ },
23
+ "scripts": {}
24
+ }