deptyped / prisma-extension-pagination Goto Github PK
View Code? Open in Web Editor NEWPrisma Client extension for pagination
Home Page: https://npmjs.com/prisma-extension-pagination
License: MIT License
Prisma Client extension for pagination
Home Page: https://npmjs.com/prisma-extension-pagination
License: MIT License
Hi!
Can you export the total count as part of PageNumberPaginationMeta?
There's a working implementation for that in Sahid Miller's fork - here:
https://github.com/SahidMiller/prisma-extension-pagination/tree/feat/total-counts - I believe you can just merge it with main...
Thanks!
Also going to hijack my own issue to ask if it's possible to add config globally. For example, I want to add includePageCount: true
as default to all responses, and instead disable it for the few where I may not want it.
Originally posted by @jaaneh in #11 (comment)
Node Version: v18.16.1
Typescript Version: 5.1.6
Nest Version: 10.1.0
Prisma Client Version: 5.0.0
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
},
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"alwaysStrict": true,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": false,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUncheckedIndexedAccess": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strictFunctionTypes": true,
"useUnknownInCatchVariables": false,
"noImplicitOverride": true
}
}
Error message:
src/**/user.repository.ts:13:48 - error TS2339: Property 'withPages' does not exist on type 'usermodelsDelegate<DefaultArgs>'.
Reproduce Code
return await this.prismaService.usermodels.withPages({
limit: 10,
page: 2,
includePageCount: true,
});
Hi,
When using pagination with NestJs it's necessary to code like this:
// prisma.service.ts
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
public readonly pagination;
constructor() {
super();
this.pagination = this.$extends(pagination);
}
async onModuleInit(): Promise<void> {
await this.$connect();
}
}
// in any repository class
findAll(id: string) {
return this.prismaService.pagination. // no type identification from here on
// expected: return this.prismaService.pagination.any_model.paginate().withPages();
}
But since pagination variable is not typed, when you try to use paginator, autocomplete is not generated anywhere, and also, any schema breakchanges are not detected by prisma.
Is It possible to add pagination types to this library?
Problem reference: #7 (comment)
Hey, trying to get this working with v5 and saw #10 was merged. However, it doesn't seem to be functional with this still.
Prisma v4.16.2 works fine with no errors.
Here's my prisma setup
import { PrismaClient } from "@prisma/client"
import pagination from "prisma-extension-pagination"
const prismaClient = new PrismaClient()
const prisma = prismaClient.$extends(pagination)
export default prisma
For example, to find all users between cursors "1" and "100" (exclusive):
const [users, meta] = await prisma.user
.paginate()
.withCursor({
after: "1",
before: "100"
});
First of all, very nice pagination implementation!
Would it be possible to add pageSize
/ perPage
property to the paginated response? Also, in line with currentPage
, previousPage
, nextPage
variables, maybe pageCount
can be renamed to lastPage
, or in line with totalCount
-> totalPages
?
// Suggested:
{
pageSize: 10, // <- Added
currentPage: 2,
isFirstPage: false,
isLastPage: false,
previousPage: 1,
nextPage: 3,
lastPage: 10, // or totalPages <- Updated
totalCount: 100
}
lastPage could be calculated using `Math.ceil(total / perPage)`
Also, perhaps the return format can be updated like so:
// Current:
[
[
item1,
item2,
...
],
{
// pagination meta
}
]
// Suggested:
{
"data": [
item1,
item2,
...
],
"meta": {
// pagination meta
}
}
Thank you!
const { limit, after, before, getCursor, parseCursor } = Object.assign(Object.assign({
// @ts-expect-error actual fields of the model are not known
getCursor({ id }) {
// if (typeof id !== "number") {
// throw new Error("Unable to serialize cursor");
// }
return id
},
parseCursor(cursor) {
// const id = parseInt(cursor, 10);
// if (Number.isNaN(id)) {
// throw new Error("Unable to parse cursor");
// }
return {
id: cursor,
};
} }, globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.cursor), options);
extension.js
Because of the annotation in the "extension.js" file, the integrer type cursor id does not work.
I am using mongodb and the type of Id I am using is objectId
Hi, I'm running into the following error after building this package
import { paginate } from "prisma-extension-pagination";
SyntaxError: Named export 'paginate' not found. The requested module 'prisma-extension-pagination' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
Fixing this error using default exports generates TS errors.
I believe this is caused by the package.json not having a type: "module"
or not having microbundle emit with .mjs extension.
Removing "module": "/dist/index.mjs"
and then running npm run build
emits /dist/index.esm.mjs
.
Hello,
It would be interesting to be able to enter 'limit' and 'page' as undefined, so we could also manage the pagination and the total display with the same function
When using this library with NestJs, this error occurs:
class UsersRepository {
constructor(private readonly prisma: PrismaService) {}
findMany() {
return this.prisma.users.paginate(); // "The property 'paginate' does not exist on type 'UserDelegate'."
}
}
// Prisma instantiation
import pagination from 'prisma-extension-pagination';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
async onModuleInit(): Promise<void> {
await this.$connect();
this.$extends(pagination());
}
}
NestJs: 8.4.7
Typescript: 4.7.4
Prisma: 5.2.0
prisma-extension-pagination: 0.5.0
Sorry for making an issue here,
is there any way to use this extension on nestjs?
I've been using it like this
import pagination from 'prisma-extension-pagination';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$extends(pagination).$connect();
}
async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
await app.close();
});
}
}
but it doesn't seems work as it say
Property 'paginate' does not exist on type 'GetModel<InstancesDelegate<RejectOnNotFound | RejectPerOperation, DefaultArgs>, unknown>'
It's a great package, but it seems it can't be used with raw queries, is there any way to use it with raw queries, I think this is a necessity when doing pagination?
We're using ESM modules in Node v18, the default export isn't working properly so it's not possible to import the extension correctly and use it. Using the example at the top of the readme gives the error "pagination is not a function".
I've recreated the issue here https://codesandbox.io/p/devbox/recursing-swartz-zyffh8?file=%2Findex.mjs%3A5%2C1
The named exports are working fine, if we can add the extension as a named export that would solve the issue.
For some reason, in most tutorials and articles about cursor pagination it is written that, unlike offset pagination, cursor does not allow you to jump to the desired page (skip a certain amount).
But that's a lie!
You can simply perform a normal cursor search and then skip the required amount.
Thus, the advantages of the cursor and offset capabilities will remain, and the speed will hardly change (if you do not skip a lot).
neo4j/neo4j#12695
https://arpitbhayani.me/blogs/fast-and-efficient-pagination-in-mongodb/
https://www.mongodb.com/docs/manual/reference/method/cursor.skip/
Even the prisma documentation says that with the cursor pagination, you need to skip 1 row in order not to include it in the result. What prevents you from skipping more?
I suggest adding a skip
and includePageCount
in the cursor pagination options and changing the meta accordingly.
For example, to iterate over all users:
const users = await prisma.user
.paginate()
.toStream({
limit: 25, // batch size
});
for await (const user of users) {
console.log(user); // {id: 1, name: 'John Doe'}
}
Would be nice with an option to skip limiting the results
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.