Coder Social home page Coder Social logo

deptyped / prisma-extension-pagination Goto Github PK

View Code? Open in Web Editor NEW
191.0 2.0 14.0 270 KB

Prisma Client extension for pagination

Home Page: https://npmjs.com/prisma-extension-pagination

License: MIT License

JavaScript 0.84% TypeScript 99.16%
nodejs orm prisma prisma-client prisma-extension typescript pagination

prisma-extension-pagination's Introduction

Hi there ๐Ÿ‘‹

prisma-extension-pagination's People

Contributors

aprilnea avatar deptyped avatar katt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

prisma-extension-pagination's Issues

Custom default options

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)

Pagniate not working in prisma 5

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,
});

Add typing for Prisma client with pagination extension

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)

Not compatible with Prisma v5

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.

Prisma v5.0.0:
image

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

Add ability to query data between cursors

For example, to find all users between cursors "1" and "100" (exclusive):

const [users, meta] = await prisma.user
  .paginate()
  .withCursor({
    after: "1",
    before: "100"
  });

Suggestions for pagination object

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!

Why does the cursor id have to be an integrer type?

 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

ESM error at build time "SyntaxError: Named export 'paginate' not found."

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.

Possibility to disable pagination

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

Paginate not working in prisma 5 with NestJs

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

NestJS usage

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>'

Raw query support

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?

Default export doesn't work with ESM modules

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.

Add a skip option to the cursor pagination

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.

Add ability to stream data

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'}
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.