UNPKG

prisma-extension-random

Version:

Add some randomness to your favorite Prisma queries!

68 lines (65 loc) 1.63 kB
// src/index.ts import { Prisma } from "@prisma/client"; // src/helpers.ts var $findRandom = async (context, args) => { const numRows = await context.count({ where: args?.where }); return await context.findFirst({ ...args, skip: Math.max(0, Math.floor(Math.random() * numRows)) }); }; var $findManyRandom = async (context, num, args) => { const uniqueKey = args?.custom_uniqueKey ?? "id"; const rows = []; const rowIds = []; const select = args?.select ?? {}; select[uniqueKey] = true; const where = args?.where ?? {}; where[uniqueKey] = { notIn: rowIds }; let numRows = await context.count({ where }); for (let i = 0; i < num && numRows > 0; ++i) { const row = await context.findFirst({ select, where, skip: Math.max(0, Math.floor(Math.random() * numRows)) }); if (!row) { console.error( `get random row failed. Where clause: ${JSON.stringify(where)}` ); break; } rows.push(row); rowIds.push(row[uniqueKey]); numRows--; } return rows; }; // src/index.ts var src_default = (_extensionArgs) => Prisma.getExtensionContext({ name: "prisma-extension-random", model: { $allModels: { async findRandom(args) { const context = Prisma.getExtensionContext(this); return await $findRandom( context, args ); }, async findManyRandom(num, args) { const context = Prisma.getExtensionContext(this); return await $findManyRandom( context, num, args ); } } } }); export { src_default as default };