UNPKG

prisma-cursorstream

Version:

Prisma Stream Client Extension (Cursor-based Implementation)

55 lines (54 loc) 2.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const extension_1 = require("@prisma/client/extension"); const node_stream_1 = require("node:stream"); exports.default = extension_1.Prisma.defineExtension((client) => { return client.$extends({ model: { $allModels: { cursorStream(findManyArgs, { batchSize, prefill, batchTransformer } = {}) { findManyArgs = findManyArgs !== null && findManyArgs !== void 0 ? findManyArgs : {}; const context = extension_1.Prisma.getExtensionContext(this); const take = batchSize || 100; const highWaterMark = prefill || take * 2; const cursorField = Object.keys(findManyArgs.cursor || {})[0] || "id"; if (findManyArgs.select && !findManyArgs.select[cursorField]) { throw new Error(`Must select cursor field "${cursorField}"`); } let cursorValue; const readableStream = new node_stream_1.Readable({ objectMode: true, highWaterMark, async read() { try { const results = await context.findMany({ ...findManyArgs, take, skip: cursorValue ? 1 : 0, ...(typeof cursorValue !== "undefined" ? { cursor: { [cursorField]: cursorValue } } : {}), }); const transformedResults = batchTransformer ? await batchTransformer(results) : results; for (const result of transformedResults) { this.push(result); } if (results.length < take) { this.push(null); return; } cursorValue = results[results.length - 1][cursorField]; } catch (err) { this.destroy(err); } }, }); return readableStream; }, }, }, }); });