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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@riyad_ahsan/typeorm-query-kit

v1.0.2

Published

A powerful query parser for TypeORM with filtering, sorting, pagination, and relation support

Readme

typeorm-query-kit

Magical Query Parsing for TypeORM APIs

npm version License: MIT TypeScript

A powerful, intuitive query parser middleware that transforms simple HTTP queries into complex TypeORM queries. Filter, sort, paginate, and include relations with elegant query parameters.

✨ Features

  • 🔍 Advanced Filtering - Support for operators ($eq, $ne, $in, $like, etc.)
  • 📊 Smart Sorting - Multi-field sorting with custom order
  • 📄 Built-in Pagination - Easy pagination with page/limit parameters
  • 🎯 Range Queries - Number and date range filtering
  • 🤝 Relation Loading - Automatic JOINs for related entities
  • 🛡️ Security First - Field-level permission controls
  • ⚡ TypeScript Ready - Full type definitions included
  • 🚀 Lightweight - Zero dependencies (except TypeORM and Express)

Installation

npm install typeorm-query-kit
# or
yarn add typeorm-query-kit

Quick Start

import express from 'express';
import { queryParser, applyQueryOptions } from 'typeorm-query-kit';
import { getRepository } from 'typeorm';
import { User } from './entities/User';

const app = express();
app.use(queryParser); // Add the middleware

app.get('/users', async (req, res) => {
  try {
    const userRepository = getRepository(User);
    let queryBuilder = userRepository.createQueryBuilder('user');
    
    // Apply query options magically!
    queryBuilder = await applyQueryOptions(queryBuilder, 'user', req.queryOptions);
    
    const [users, total] = await queryBuilder.getManyAndCount();
    
    res.json({
      data: users,
      total,
      page: req.queryOptions.page,
      limit: req.queryOptions.limit
    });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

🎯 Usage Examples

Basic Filtering

GET /api/users?filter={"name":"John Doe","status":"active"}

Advanced Operators

GET /api/users?filter={"age":{"$gte":18,"$lte":30},"email":{"$like":"@company.com"}}

Sorting

GET /api/products?sort={"field":"price","order":"DESC"}

Multi-field Sorting

GET /api/users?sort=[{"field":"lastName","order":"ASC"},{"field":"firstName","order":"ASC"}]

Pagination

GET /api/products?page=2&limit=20

Range Queries

GET /api/products?range={"price":{"gte":10,"lte":50},"createdAt":{"gte":"2023-01-01"}}

Including Relations

GET /api/users?relations=["profile","orders","orders.items"]

Complex Example

GET /api/orders?
  page=2&
  limit=10&
  filter={"status":"completed","user.role":"VIP"}&
  range={"total":{"gt":100},"createdAt":{"gte":"2023-10-01"}}&
  sort={"field":"createdAt","order":"DESC"}&
  relations=["user","items"]

🔧 API Reference

queryParser Middleware

Parses incoming query parameters and attaches a queryOptions object to the request.

app.use(queryParser);
// Now req.queryOptions is available in your routes

applyQueryOptions(queryBuilder, baseAlias, options, config?)

Applies the parsed query options to a TypeORM QueryBuilder.

Parameters:

  • queryBuilder: TypeORM SelectQueryBuilder instance
  • baseAlias: Main entity alias (e.g., 'user', 'product')
  • options: Query options from req.queryOptions
  • config?: Optional field configuration for security

🛡️ Field Configuration

Control which fields can be filtered, sorted, or used in range queries:

const fieldConfig = {
  user: {
    id: { filterable: true, sortable: true },
    email: { filterable: true, searchable: true },
    password: { filterable: false }, // Sensitive field
    createdAt: { filterable: true, sortable: true, rangeable: true }
  }
};

// Apply configuration
app.use((req, res, next) => {
  req.entityConfig = fieldConfig;
  next();
});

🚀 Advanced Usage

Custom Validation

app.use((req, res, next) => {
  // Add custom validation logic before applying queries
  if (req.queryOptions.filter?.email) {
    // Validate email format
  }
  next();
});

Error Handling

app.use((error: any, req: Request, res: Response, next: NextFunction) => {
  if (error.message.includes('Invalid filter') || error.message.includes('Range value')) {
    return res.status(400).json({ error: error.message });
  }
  next(error);
});

📋 Supported Operators

| Operator | Example | Description | |----------|---------|-------------| | $eq | {"status":"active"} | Equality | | $ne | {"status":{"$ne":"banned"}} | Not equal | | $gt | {"age":{"$gt":18}} | Greater than | | $gte | {"age":{"$gte":21}} | Greater than or equal | | $lt | {"price":{"$lt":100}} | Less than | | $lte | {"price":{"$lte":50}} | Less than or equal | | $in | {"id":{"$in":[1,2,3]}} | In array | | $nin | {"role":{"$nin":["guest"]}} | Not in array | | $like | {"name":{"$like":"john"}} | Case-sensitive search | | $isNull | {"deletedAt":{"$isNull":true}} | Is null check |

🤝 Contributing

We love contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

🏆 Credits

Made with ❤️ by [Riyad Ahsan]


Ready to work some magic?

npm install @riyad_ahsan/typeorm-query-kit

Transform your API queries from mundane to magical today!


This README provides:

1. **Eye-catching branding** with emojis and clear structure
2. **Quick start** section for immediate implementation
3. **Comprehensive examples** covering all features
4. **Clear API documentation** with code samples
5. **Advanced usage patterns** for complex scenarios
6. **Operator reference table** for easy lookup
7. **Contribution guidelines** for open-source collaboration
8. **Professional formatting** with badges and sections

The documentation is designed to be both beginner-friendly and comprehensive enough for advanced users. It highlights the magical aspect of your package while providing all the technical details developers need to implement it successfully.