qast
v2.2.0
Published
Query to AST to ORM - Parse human-readable query strings into AST and transform them into ORM-compatible filters
Maintainers
Readme
QAST — Query to AST to ORM
QAST is a small, ORM-agnostic, zero-dependency library that turns human‑readable query strings
(for example: age gt 25 and (name eq "John" or city eq "Paris")) into an AST and then into ORM filters.
It is designed to be simple to adopt, safe by default, and easy to integrate into existing REST APIs.
Why QAST?
- One query param —
?filter=age gt 25 and active eq trueinstead of many query keys - Zero runtime dependencies — safe to embed anywhere
- Whitelist-first — fields and operators are explicitly allowed
- OpenAPI-ready — document the filter param and generate whitelists from schemas
Try the playground → · See a working API →
Features
- Zero runtime dependencies – lightweight and easy to embed
- ORM‑agnostic adapters – Prisma, TypeORM, Sequelize, Mongoose, Knex, Drizzle
- Safe by default – optional whitelists, per-field value rules, and complexity limits
- TypeScript first – fully typed API and AST
- OpenAPI helpers – generate query-parameter / JSON Schema descriptions from your whitelists
Installation
npm install qastQuick Start (Prisma example)
import { parseQuery, toPrismaFilter } from 'qast';
// Example: ?filter=age gt 25 and name eq "John"
const raw = req.query.filter as string;
// Parse and (optionally) validate
const ast = parseQuery(raw, {
allowedFields: ['age', 'name', 'city', 'active'],
allowedOperators: ['eq', 'ne', 'gt', 'lt', 'gte', 'lte', 'in'],
validate: true,
});
// Transform to Prisma filter
const filter = toPrismaFilter(ast);
const users = await prisma.user.findMany(filter);Nested relations (Prisma)
Use dot notation for to-one relations and relation.some|every|none.field for to-many filters:
// author.name eq "John"
// → { where: { author: { name: { equals: "John" } } } }
// posts.some.title contains "Hello"
// → { where: { posts: { some: { title: { contains: "Hello" } } } } }
const ast = parseQuery('author.country eq "France" and posts.some.published eq true', {
allowedFields: ['author.country', 'posts.some.published'],
allowedOperators: ['eq', 'contains'],
validate: true,
});
const filter = toPrismaFilter(ast);Core Concepts
- Query string → parsed into an AST
- AST can be:
- used directly, or
- passed to an adapter (Prisma, TypeORM, etc.) to get an ORM‑specific filter
- Security and performance can be tuned via:
allowedFields,allowedOperatorsfieldConstraints(types, enums, min/max, regex on values)maxDepth,maxNodes,maxQueryLength,maxArrayLength,maxStringLength
You do not need any of the ORMs installed if you only work with the AST; ORM packages are optional peer dependencies.
Minimal API Surface
parseQuery(query, options?)– parse a filter expression into an ASTparseQueryFull(query, options?)– parse filters +orderBy/limit/offsetvalidateQueryFieldConstraints(ast, constraints?)– validate values againstfieldConstraintsrulesopenApiFilterParameter(options?)– OpenAPI 3.x query parameter object for the filter stringjsonSchemaFilterStringProperty(options?)– JSON Schemastringproperty with generated descriptionwhitelistFromOpenApiSchema(schema)– deriveallowedFieldsandfieldConstraintsfrom a JSON Schema objecttoPrismaFilter(ast)– convert AST / QueryAST to Prisma filter objecttoTypeORMFilter(ast)– convert AST / QueryAST to a TypeORM‑style filtertoSequelizeFilter(ast)– convert AST / QueryAST to a Sequelize‑style filtertoMongooseFilter(ast)– convert AST / QueryAST to a Mongoose‑style filtertoKnexFilter(ast)– convert AST / QueryAST to a Knex‑style filtertoDrizzleFilter(ast)– convert AST / QueryAST to a Drizzle‑style filter
All advanced utilities (caching, cost estimation, AST transforms, etc.) are kept small and dependency‑free.
Field constraints (value validation)
After parsing, you can enforce rules on values per field. Only fields you list in fieldConstraints are checked; other fields are unchanged.
Pass fieldConstraints to parseQuery / parseQueryFull (runs when validate is not false). You can also run validation yourself on an existing AST with validateQueryFieldConstraints(ast, constraints).
| Constraint | Meaning |
|------------|---------|
| type | 'string' | 'number' | 'boolean' | 'date' | 'null' |
| allowNull | Allow eq null / ne null (and null inside in / notIn) |
| enum | Allowed strings (scalars and each in / notIn element) |
| min / max | Numbers: inclusive bounds. Strings: UTF‑16 length bounds |
| pattern | ECMAScript regex (strings only) |
import { parseQuery } from 'qast';
const ast = parseQuery('age gte 0 and role eq "admin"', {
allowedFields: ['age', 'role'],
allowedOperators: ['eq', 'gte', 'lte'],
fieldConstraints: {
age: { type: 'number', min: 0, max: 130 },
role: { type: 'string', enum: ['admin', 'user'] },
},
});For date, values may be ISO-like strings or numeric timestamps; min / max are compared as milliseconds when set. between is supported for number, string, and date constraints.
OpenAPI and JSON Schema
Use these to document the filter query string in OpenAPI 3.x or to embed a string property in a larger JSON Schema.
import { openApiFilterParameter, jsonSchemaFilterStringProperty } from 'qast';
// OpenAPI 3.x style parameter object (serialize to JSON for your spec)
const param = openApiFilterParameter({
name: 'filter', // default
required: false,
allowedFields: ['age', 'name', 'active'],
allowedOperators: ['eq', 'gt', 'lt', 'contains'],
description: 'Optional extra note for API consumers.',
examples: ['age gt 18', 'active eq true and name contains "Ada"'],
});
// Reusable string property with a generated description
const filterProp = jsonSchemaFilterStringProperty({
allowedFields: ['id', 'status'],
allowedOperators: ['eq', 'in'],
});
// => { type: 'string', description: '...' }When to use something else
| Use case | Consider | |----------|----------| | NestJS-only, decorator-based filters | nestjs-rest-query | | Prisma-only, HTTP param conventions | prisma-qb | | Client-side filter builder + codegen | @nestjs-filter-grammar |
License
MIT © 2025
GitHub: https://github.com/hocestnonsatis/qast
