# @windychen/trans-form-typeorm TypeORM 适配包:把 `@windychen/trans-form-middleware` 解析出的结构化过滤器转为 **FindOptionsWhere**(对象式查询)或 **QueryBuilder** 条件(支持嵌套分组)。 > 版本 0.1.0 — 首个可发布版本:`toFindOptionsWhere` / `applyToQueryBuilder`,覆盖 EQ/NE/GT/GTE/LT/LTE/LIKE/IN/NOT_IN/BETWEEN/IS_NULL/IS_NOT_NULL 全部操作符。 ## 安装 ```bash npm install @windychen/trans-form-typeorm typeorm ``` ## 用法 ```js import { parseFilters } from '@windychen/trans-form-middleware'; import { toFindOptionsWhere, applyToQueryBuilder } from '@windychen/trans-form-typeorm'; // 1. middleware 解析 const filters = parseFilters( [ { field: 'name', value: 'xx', query: 'EQ' }, { field: 'tags', value: 'a,b', query: 'IN', logic: 'OR' }, { field: 'created', value: '2024-01-01,2024-12-31', query: 'BETWEEN', logic: 'AND' }, ], { allowedFields: ['name', 'tags', 'created'] }, ); // 2a. FindOptionsWhere(repository.find) const where = toFindOptionsWhere(filters); // [{ name: Equal('xx') }, { tags: In(['a','b']), created: Between('2024-01-01','2024-12-31') }] await repo.find({ where }); // 2b. QueryBuilder(支持嵌套分组) const { qb, parameters } = applyToQueryBuilder(repo.createQueryBuilder('u'), filters, { alias: 'u' }); // u.name = :p1 OR (u.tags IN (:...p2) AND u.created BETWEEN :p3 AND :p4) ``` ## API | 函数 | 说明 | |------|------| | `toFindOptionsWhere(filters, options?)` | → `FindOptionsWhere[]`。AND 项合并进同一对象,OR 项拆成数组元素(`where: [{a:1},{b:2}]` = a=1 OR b=2) | | `applyToQueryBuilder(qb, filters, options?)` | → `{ qb, parameters }`。支持嵌套分组括号表达式、参数绑定、alias 前缀 | | `mapOperator(query, operatorMap?)` | 操作符码 → 工厂函数 | | `DEFAULT_OPERATOR_MAP` | 默认操作符映射表 | ### 选项 **toFindOptionsWhere**:`{ skipFlags = ['disabled','hidden'], skipEmpty = false, operatorMap }` **applyToQueryBuilder**:`{ skipFlags = ['disabled','hidden'], skipEmpty = false, operatorMap, alias = '', paramPrefix = 'p', method = 'andWhere' }` - `method`: `'where' | 'andWhere' | 'orWhere'`,首条件挂载方式 - 空 value 且非 IS_NULL/IS_NOT_NULL 的条件自动跳过;LIKE 值自动加 `%` ## 操作符映射 | query | FindOptionsWhere | SQL | |-------|------------------|-----| | EQ | `Equal(v)` | `= :p` | | NE | `Not(Equal(v))` | `<> :p` | | GT | `MoreThan(v)` | `> :p` | | GTE | `MoreThanOrEqual(v)` | `>= :p` | | LT | `LessThan(v)` | `< :p` | | LTE | `LessThanOrEqual(v)` | `<= :p` | | LIKE | `Like(v)` | `LIKE :p`(自动加 %) | | IN | `In(values)` | `IN (:...p)` | | NOT_IN | `Not(In(values))` | `NOT IN (:...p)` | | BETWEEN | `Between(a, b)` | `BETWEEN :p1 AND :p2` | | IS_NULL | `IsNull()` | `IS NULL` | | IS_NOT_NULL | `Not(IsNull())` | `IS NOT NULL` | ## 依赖 零运行时依赖;`typeorm` 为 peerDependency(`^0.3.0`)。 ## 相关包 - `@windychen/trans-form-component` — Vue 3 动态查询表单(schema 入 → filters 出) - `@windychen/trans-form-middleware` — 结构化过滤器解析(不碰 SQL)