npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

typeorm-pagination

v2.0.3

Published

A pagination plugin for typeorm written for node express

Downloads

3,002

Readme

GitHub Workflow Status (branch) GitHub Workflow Status GitHub issues npm npm npm

typeorm-pagination - The missing pagination extension for typeORM

TypeORM is one of the most popular ORM frameworks for node.js. This middleware is the missing pagination extension for typeORM specifically tailored apps running on the for expressjs or koajs frameworks.

Installation

Pre-requisites:

NPM:

npm install typeorm-pagination
Yarn
yarn add typeorm-pagination

Usage

Register the Middleware

Import the pagination function in your main express entry file (app.js, index.js, index.ts etc)

import {createConnection} from "typeorm";
import * as express from "express";
import * as bodyParser from "body-parser";
import {Request, Response} from "express";
import {pagination} from 'typeorm-pagination'
// Other imports

createConnection().then(async connection => {
    // create express app
    const app = express();
    app.use(bodyParser.json());
    app.use(pagination); // Register the pagination middleware
    // setup express app here
    // ...
    // start express server
    app.listen(process.env.PORT || 3000);
    console.log("Express server has started on port "+process.env.PORT||3000);
}).catch(error => console.log(error));

Using the middleware to paginate

Next, let's go ahead and paginate any typeorm entity using the query builder. For example, if we had the User entity and we wanted to paginate it, here is how:

If you are using the Data Mapper pattern (Repositories)

// UserController.ts
import {getRepository} from "typeorm";
import {NextFunction, Request, Response} from "express";
import {User} from "../entity/User";
export class UserController {

    private repo = getRepository(User);

    async all(request: Request, response: Response, next: NextFunction) {
        let users = await this.repo.createQueryBuilder('user')
        //...Enter more of your queries here... add relationships etc. THEN:
        .paginate();
        return response.status(200).json(users);
    }
}

Using the Active Record pattern

If your Entity extends BaseEntity, then you can query using the AR pattern as follows:

// UserController.ts
import {NextFunction, Request, Response} from "express";
import {User} from "../entity/User";
export class UserController {
    async all(request: Request, response: Response, next: NextFunction) {
        let users = await User.createQueryBuilder('user')
        //...Enter more of your queries here... add relationships etc. THEN:
        .paginate();
        return response.status(200).json(users);
    }
}

Read more on the two Patterns HERE

How to use with Routing Controllers

If you are using Routing Controllers to specify your routes as decorations, here is how you can set up and use typeorm-pagination:

Register the middleware

You can use the createExpressServer function provided by routing-controllers and register the pagination middleware by specifying it under the middlewares option.

// app.ts
import "reflect-metadata";
import {createConnection} from "typeorm";
import { pagination } from "typeorm-pagination";
import { createExpressServer } from "routing-controllers";
createConnection().then(async connection => {
    const port = process.env.PORT || 3000;
    createExpressServer({
        controllers: [
            __dirname +"/controller/**/*"
        ],
        middlewares: [
            //Other middleware
            pagination,
        ]
    }).listen(port);
    console.log("Express server has started on port "+port);
}).catch(error => console.log(error));

Your controller

In the controller, wherever you have a function that you need to paginate, you MUST specify the pagination middleware using the @UseBefore decorator:

// UserTypeController.ts
import { Request} from "express";
import { BodyParam, Get, JsonController, Post, Req, UseBefore } from "routing-controllers";
import { getRepository, Repository } from "typeorm";
import { pagination } from "typeorm-pagination";
import { UserType } from "../entity/UserType";

@JsonController()
export class UserTypeController {
    private repo: Repository<UserType>
    constructor() {
        this.repo = getRepository(UserType);
    }
    @Post("/user-types")
    async store(@Req() request, @BodyParam('slug') slug: string, @BodyParam("name") name: string) {
        const data = request.body;
        let type = new UserType();
        type.slug = slug;
        type.name = name;
        const res = await this.repo.insert(type);
        return {
            success: true,
            payload: res,
        }
    }
    @Get('/user-types')
    @UseBefore(pagination) // <---- MUST specify the pagination middleware here for it to work.
    async index(@Req() req: Request) {
        return await UserType.createQueryBuilder().paginate(); // If you are using the Active Record Pattern
    }
}

Using Koa.js

Since Koa.js is similar to express, the package should work flawlessly with Koa.js, but this is yet to be tested.

Documentation on how to use with the Koa.js framework is coming soon.

NOTES:

  • You can also call paginate(n) where n= default no. of records per page. However, it is important to note that this number n will be overwritten by the query parameter per_page if it is set on the current request, e.g in the sample request below.

Sample Request:

GET http://localhost:3000/user-types?page=1&per_page=15

Sample Response:

{
"from":1,
"to":2,
"per_page":15,
"total":2,
"current_page":1,
"prev_page":null,
"next_page":null,
"last_page":1,
"data":[
     {"id":1,"slug":"staff","name":"Staff"},
     {"id":4,"slug":"student","name":"Student"}
]}

Notice: There are two more helpers you can import from typeorm-pagination to help you extract the per_page and page query params, which will determine the number of records loaded per page and the current page respectively. You can pass optional defaults to each function. The default perPage when not set is currently 15 and the default page when not set is 1.

Contributions:

If you would like to improve the package, you can submit PRs on the github page. PULL REQUESTS

Issues

In case of any issues, please submit them to the issues page of the repo: ISSUES