import type { SortDirection } from 'mongodb'; export interface IFieldsObject { [key: string]: number; } export interface ISortObject { [key: string]: SortDirection; } export interface IMongoUpdate { $set?: Record; $unset?: Record; } /** * Parses a page query parameter into a positive integer. * * @param value - Page number as a string or number. Defaults to `1`. * @returns Parsed page number or `1` if the value is invalid. * * @example * parsePage('10') // => 10 * parsePage(10) // => 10 * parsePage('abc') // => 1 * parsePage(0) // => 1 */ export declare function parsePage(value?: string | number): number; /** * Parses a page size query parameter into a positive integer. * * @param value - Number of records per page. Defaults to `10`. * @returns Parsed page size or `10` if the value is invalid. * * @example * parsePageSize('10') // => 10 * parsePageSize(10) // => 10 * parsePageSize('abc') // => 10 * parsePageSize(0) // => 10 */ export declare function parsePageSize(value?: string | number): number; /** * Calculates the number of records to skip for pagination. * * @param currentPage - Current page number. * @param pageSize - Number of records per page. * @returns Number of records to skip. * * @example * calculateSkip(1, 10) // => 0 * calculateSkip(2, 10) // => 10 * calculateSkip(3, 10) // => 20 */ export declare function calculateSkip(currentPage: string | number, pageSize: string | number): number; /** * Converts a comma-separated or space-separated field string * into a MongoDB projection object. * * Supports either inclusion or exclusion projections. * Excluded fields cannot be combined with included fields, * except for MongoDB's special `_id` field. * * @param value - Comma-separated or space-separated field names to include. * @param excludedFields - Field names to exclude. * @returns MongoDB projection object. * * @example * parseProjection('name, address') * // => { name: 1, address: 1 } * * parseProjection('', ['password', 'token']) * // => { password: 0, token: 0 } * * parseProjection('name, address', ['_id']) * // => { name: 1, address: 1, _id: 0 } */ export declare function parseProjection(value?: string, excludedFields?: string[]): IFieldsObject; /** * Converts a comma-separated or space-separated string into an array of field names. * * @param value - String containing field names. * @returns Array of trimmed, non-empty field names. * * @example * parseFieldList('name, address') * // => ['name', 'address'] * * parseFieldList('name address') * // => ['name', 'address'] * * parseFieldList(' name, address ') * // => ['name', 'address'] */ export declare function parseFieldList(value: string): string[]; /** * Creates a MongoDB projection object from an array of field names. * * @param fields - Array of field names. * @param value - Projection value assigned to each field. Defaults to `1`. * @returns MongoDB projection object. * * @example * createProjection(['name', 'address']) * // => { name: 1, address: 1 } * * createProjection(['name', 'address'], 0) * // => { name: 0, address: 0 } */ export declare function createProjection(fields: string[], value?: number): IFieldsObject; /** * Creates a MongoDB sort object from an array of field names. * * A field prefixed with `-` is sorted in descending order. * Fields without a prefix are sorted in ascending order. * * @param fields - Array of field names with optional negative prefixes. * @returns MongoDB sort object. * * @example * createSort(['-firstName', 'lastName', 'created_at']) * // => { firstName: -1, lastName: 1, created_at: 1 } */ export declare function createSort(fields: string[]): Record; /** * Excludes specified fields from a MongoDB projection object. * * Modifies the original projection object by assigning `0` * to each excluded field. * * @param projection - MongoDB projection object to modify. * @param fields - Array of field names to exclude. * @returns The modified projection object. * * @example * excludeFields({ name: 1, address: 1 }, ['_id']) * // => { name: 1, address: 1, _id: 0 } */ export declare function excludeFields(projection: IFieldsObject, fields: string[]): IFieldsObject; /** * Parses a comma-separated field string into a MongoDB sort object. * * A field prefixed with `-` is sorted in descending order. * Fields without a prefix are sorted in ascending order. * * @param value - Comma-separated field names with optional negative prefixes. * @returns MongoDB sort object. * * @example * parseSort('name, -createdAt') * // => { name: 1, createdAt: -1 } * * parseSort('-createdAt, name') * // => { createdAt: -1, name: 1 } */ export declare function parseSort(value: string): ISortObject; /** * Adds a case-insensitive regex filter to the filters array if a value is provided. * * @param filters - An array of MongoDB filter objects to be modified. * @param field - The field name to apply the regex on. * @param value - The string value to search for (optional). If empty or only whitespace, no filter is added. * * @example * const filters: Record[] = [] * * addRegexFilter(filters, 'name', 'john') * * // Result: * // [{ name: { $regex: 'john', $options: 'i' } }] */ export declare const addRegexFilter: (filters: Record[], field: string, value?: string) => void; /** * Adds an exact-match filter when the value is not null, undefined, or an empty string. * String values are trimmed before being added to the filters array. * * @template T - The type of the filter value. * @param filters - The array of MongoDB filter conditions. * @param field - The field name to filter by. * @param value - The value to match exactly. Null, undefined, and empty strings are ignored. */ export declare const addExactFilter: (filters: Record[], field: string, value?: T | null) => void; /** * Adds an exact-match ObjectId filter when the provided value is a valid ObjectId. * The value is trimmed before validation and converted to a MongoDB ObjectId. * Invalid, null, undefined, and empty values are ignored. * * @param filters - The array of MongoDB filter conditions. * @param field - The field name to filter by. * @param value - The string representation of the ObjectId. */ export declare const addObjectIdFilter: (filters: Record[], field: string, value?: string) => void; /** * Parses a boolean value from a string or boolean input. * * - Accepts `true` / `false` booleans directly. * - Converts string values `"true"` and `"false"` to booleans. * - Returns `undefined` for any other value. * * @param value - A boolean or a string representation of a boolean. * @returns `true`, `false`, or `undefined` if the value cannot be parsed. * * @example * parseBoolean(true) // true * parseBoolean('true') // true * parseBoolean('false') // false * parseBoolean('invalid') // undefined * parseBoolean() // undefined */ export declare const parseBoolean: (value?: string | boolean) => boolean | undefined; /** * Adds a boolean exact-match filter to the filters array. * * The filter is only added if the value can be successfully parsed * into a boolean (`true` or `false`). * * @param filters - An array of MongoDB filter objects to be modified. * @param field - The field name to match. * @param value - A boolean or string (`"true"` / `"false"`) to match. * * @example * const filters: Record[] = [] * * addBooleanFilter(filters, 'is_active', 'true') * addBooleanFilter(filters, 'is_verified', false) * * // Result: * // [ * // { is_active: true }, * // { is_verified: false } * // ] */ export declare const addBooleanFilter: (filters: Record[], field: string, value?: string | boolean) => void; /** * Adds a MongoDB date range filter (`$gte` / `$lte`) to the filters array. * * The filter is only added if at least one of `value_from` or `value_to` * is provided and non-empty. * * @param filters - An array of MongoDB filter objects to be modified. * @param field - The date field name to apply the range filter on. * @param value_from - The start date (inclusive) as a string. * @param value_to - The end date (inclusive) as a string. * * @example * const filters: Record[] = [] * * addDateRangeFilter(filters, 'created_at', '2026-01-01', '2026-12-31') * * // Result: * // [ * // { * // created_at: { * // $gte: new Date('2026-01-01'), * // $lte: new Date('2026-12-31') * // } * // } * // ] * * @example * const filters: Record[] = [] * * addDateRangeFilter(filters, 'created_at', '2026-01-01') * * // Result: * // [{ created_at: { $gte: new Date('2026-01-01') } }] */ export declare const addDateRangeFilter: (filters: Record[], field: string, value_from?: string, value_to?: string) => void; /** * Adds a numeric filter to the filters array based on comparison operators or a single value. * * Accepts expressions like `">10<20"`, `"<=15"`, `"=5"` or `"50"` (interpreted as equality). * * @param filters - An array of MongoDB filter objects to be modified. * @param field - The field name to apply the numeric comparison on. * @param value - A string representing the numeric comparison(s). * * @example * const filters: Record[] = [] * * addNumberFilter(filters, 'age', '>=18<65') * addNumberFilter(filters, 'score', '90') * * // Result: * // [ * // { age: { $gte: 18, $lt: 65 } }, * // { score: 90 } * // ] */ export declare const addNumberFilter: (filters: Record[], field: string, value?: string) => void; /** * Parses a string expression into MongoDB-style numeric comparison operators. * * Supported formats: * - `"50"` → `{ eq: 50 }` * - `">10"` → `{ gt: 10 }` * - `"<=15"` → `{ lte: 15 }` * - `">=5<20"` → `{ gte: 5, lt: 20 }` * * Constraints: * - Only one lower-bound (`>` or `>=`) and one upper-bound (`<` or `<=`) operator are allowed. * - Returns an empty object for malformed or ambiguous expressions. * * @param expr - A string representing numeric comparisons. * @returns An object with numeric comparison constraints. * * @example * parseComparisons('50') * // { eq: 50 } * * parseComparisons('>10') * // { gt: 10 } * * parseComparisons('>=5<20') * // { gte: 5, lt: 20 } * * parseComparisons('<=15') * // { lte: 15 } * * parseComparisons('invalid') * // {} * * @throws Will throw an API error if the input format is invalid or has duplicate bounds. */ export declare const parseComparisons: (expr: string) => { gt?: number; gte?: number; lt?: number; lte?: number; eq?: number; }; /** * Builds a MongoDB update document from input data. * * Nested plain objects are recursively flattened into dot-notation paths. * Arrays and other non-plain objects are treated as complete values and * assigned using `$set`. * * Explicit dot-notation keys can be used to update individual nested fields * or array indexes without replacing the entire array. * * Value handling: * - `undefined`: Ignored; the existing field remains unchanged. * - `null`: Added to `$unset` to remove the existing field. * - Plain object: Recursively flattened into dot-notation paths. * - Array: Added to `$set` as a complete array. * - Other values: Added to `$set`. * * @param rawInput - Input data to convert into MongoDB update operations. * @returns MongoDB update document containing `$set` and/or `$unset`. * Returns an empty object when there are no applicable updates. * * @example * // Update primitive and nested fields. * buildUpdateData({ * name: 'John', * profile: { * city: 'Surabaya', * postal_code: '60123', * }, * }); * * // Returns: * { * $set: { * name: 'John', * 'profile.city': 'Surabaya', * 'profile.postal_code': '60123', * }, * } * * @example * // Replace an entire array. * buildUpdateData({ * tags: ['developer', 'admin'], * }); * * // Returns: * { * $set: { * tags: ['developer', 'admin'], * }, * } * * @example * // Update a specific array index without replacing the entire array. * buildUpdateData({ * 'tags.500': 'admin', * }); * * // Returns: * { * $set: { * 'tags.500': 'admin', * }, * } * * @example * // Update a nested property inside an array. * buildUpdateData({ * 'tasks.500.completed': true, * }); * * // Returns: * { * $set: { * 'tasks.500.completed': true, * }, * } * * @example * // Remove fields using null values. * buildUpdateData({ * department_id: null, * profile: { * avatar: null, * }, * }); * * // Returns: * { * $unset: { * department_id: true, * 'profile.avatar': true, * }, * } * * @example * // Ignore undefined values. * buildUpdateData({ * name: undefined, * email: undefined, * }); * * // Returns: * {} * * @example * // Preserve Date and other non-plain object values. * buildUpdateData({ * updated_at: new Date(), * }); * * // Returns: * { * $set: { * updated_at: Date, * }, * } */ export declare const buildUpdateData: (rawInput: Record) => IMongoUpdate; /** * Converts the listed fields of a document from string IDs to `ObjectId`. * * Only the given dot-notation paths are converted. Everything else is left * untouched. The input is not mutated, and a new object is returned. * * - Missing, `undefined` and `null` fields are skipped. * - Values that are already `ObjectId`, or are not 24-character hex strings, * are left as they are, so invalid IDs fail loudly at schema validation. * - Arrays are traversed automatically, both arrays of IDs and arrays of objects. * * @param document - Document to convert. * @param paths - Dot-notation paths of the fields that hold IDs. * @returns A copy of the document with the listed fields converted. * * @example Plain field * ```ts * toObjectIds({ name: 'Admin', created_by_id: '665f1c2e8a1b2c3d4e5f6a7b' }, ['created_by_id']); * // { name: 'Admin', created_by_id: ObjectId('665f1c2e8a1b2c3d4e5f6a7b') } * ``` * * @example Nested object * ```ts * toObjectIds({ owner: { user_id: '665f1c2e8a1b2c3d4e5f6a7b', name: 'Ann' } }, ['owner.user_id']); * // { owner: { user_id: ObjectId('665f1c2e8a1b2c3d4e5f6a7b'), name: 'Ann' } } * ``` * * @example Array of IDs * ```ts * toObjectIds({ permission_ids: ['665f1c2e8a1b2c3d4e5f6a7b', '665f1c2e8a1b2c3d4e5f6a7c'] }, ['permission_ids']); * // { permission_ids: [ObjectId('...7b'), ObjectId('...7c')] } * ``` * * @example Nested array of objects * ```ts * toObjectIds( * { * approvers: [ * { user_id: '665f1c2e8a1b2c3d4e5f6a7b', level: 1 }, * { user_id: '665f1c2e8a1b2c3d4e5f6a7c', level: 2 }, * ], * }, * ['approvers.user_id'], * ); * // { approvers: [{ user_id: ObjectId('...7b'), level: 1 }, { user_id: ObjectId('...7c'), level: 2 }] } * ``` * * @example Several paths at once * ```ts * toObjectIds(data, ['created_by_id', 'owner.user_id', 'permission_ids', 'approvers.user_id']); * ``` */ export declare const toObjectIds: (document: object, paths: readonly string[]) => Record; /** * Converts the listed fields of a document from `ObjectId` to hex strings. * * Use this on read, so use cases only see plain strings. It follows the same * rules as `toObjectIds`: only the given dot-notation paths are converted, * arrays are traversed automatically, missing, `undefined` and `null` fields * are skipped, and the input is not mutated. Values that are not `ObjectId` * instances are left as they are. * * @typeParam T - Shape of the returned document. * @param document - Document to convert. * @param paths - Dot-notation paths of the fields that hold IDs. * @returns A copy of the document with the listed fields converted. * * @example Plain field and `_id` * ```ts * fromObjectIds(doc, ['_id', 'created_by_id']); * // { _id: '665f1c2e8a1b2c3d4e5f6a7b', created_by_id: '665f1c2e8a1b2c3d4e5f6a7c', ... } * ``` * * @example Nested object * ```ts * fromObjectIds(doc, ['owner.user_id']); * // { owner: { user_id: '665f1c2e8a1b2c3d4e5f6a7b', name: 'Ann' } } * ``` * * @example Array of IDs * ```ts * fromObjectIds(doc, ['permission_ids']); * // { permission_ids: ['665f1c2e8a1b2c3d4e5f6a7b', '665f1c2e8a1b2c3d4e5f6a7c'] } * ``` * * @example Nested array of objects * ```ts * fromObjectIds(doc, ['approvers.user_id']); * // { approvers: [{ user_id: '665f1c2e8a1b2c3d4e5f6a7b', level: 1 }, ...] } * ``` */ export declare const fromObjectIds: >(document: object, paths: readonly string[]) => T; /** * Collection of utility functions. */ declare const _default: { parsePage: typeof parsePage; parsePageSize: typeof parsePageSize; calculateSkip: typeof calculateSkip; parseProjection: typeof parseProjection; parseSort: typeof parseSort; parseFieldList: typeof parseFieldList; createProjection: typeof createProjection; createSort: typeof createSort; excludeFields: typeof excludeFields; addRegexFilter: (filters: Record[], field: string, value?: string) => void; addExactFilter: (filters: Record[], field: string, value?: T | null) => void; addObjectIdFilter: (filters: Record[], field: string, value?: string) => void; parseBoolean: (value?: string | boolean) => boolean | undefined; addBooleanFilter: (filters: Record[], field: string, value?: string | boolean) => void; addDateRangeFilter: (filters: Record[], field: string, value_from?: string, value_to?: string) => void; addNumberFilter: (filters: Record[], field: string, value?: string) => void; parseComparisons: (expr: string) => { gt?: number; gte?: number; lt?: number; lte?: number; eq?: number; }; buildUpdateData: (rawInput: Record) => IMongoUpdate; toObjectIds: (document: object, paths: readonly string[]) => Record; fromObjectIds: >(document: object, paths: readonly string[]) => T; }; export default _default; //# sourceMappingURL=mongo-query-builder.utils.d.ts.map