prisma-extension-pagination
Version:
Prisma Client extension for pagination
86 lines (85 loc) • 3.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.paginate = void 0;
exports.createPaginator = createPaginator;
exports.extension = extension;
const extension_1 = require("@prisma/client/extension");
const cursor_1 = require("./cursor");
const page_number_1 = require("./page-number");
function createPaginator(globalOptions) {
return function paginate(args) {
return {
withPages: async (options = {}) => {
const { page = 1, limit, includePageCount = false, } = {
...globalOptions?.pages,
...options,
};
if (typeof page !== 'number'
|| page < 1
|| page > Number.MAX_SAFE_INTEGER) {
throw new Error('Invalid page value');
}
if (limit !== null && typeof limit !== 'number') {
throw new Error('Missing limit value');
}
if (limit !== null && (limit < 1 || limit > Number.MAX_SAFE_INTEGER)) {
throw new Error('Invalid limit value');
}
const query = (args ?? {});
return (0, page_number_1.paginateWithPages)(this, query, {
limit,
page,
includePageCount,
});
},
withCursor: async (options = {}) => {
const { limit, after, before, getCursor = ({ id }) => {
if (typeof id !== 'number') {
throw new TypeError('Unable to serialize cursor');
}
return id.toString();
}, parseCursor = (cursor) => {
const id = Number.parseInt(cursor, 10);
if (Number.isNaN(id)) {
throw new TypeError('Unable to parse cursor');
}
return {
id,
};
}, } = {
...globalOptions?.cursor,
...options,
};
if (limit !== null && typeof limit !== 'number') {
throw new Error('Missing limit value');
}
if (limit !== null && (limit < 1 || limit > Number.MAX_SAFE_INTEGER)) {
throw new Error('Invalid limit value');
}
if (typeof after === 'string' && typeof before === 'string') {
throw new TypeError('Invalid cursor. Options after and before cannot be provided at the same time');
}
const query = (args ?? {});
return (0, cursor_1.paginateWithCursor)(this, query, {
limit,
after,
before,
getCursor,
parseCursor,
});
},
};
};
}
exports.paginate = createPaginator();
function extension(options) {
const paginate = createPaginator(options);
return extension_1.Prisma.defineExtension({
name: 'pagination',
model: {
$allModels: {
paginate,
},
},
});
}