import { Types } from 'mongoose' ; import { isObject } from 'graphql-compose' ; import type { NestedAliasesMap } from '../resolvers/helpers' ; const primitives = [ Types . ObjectId , Date , String , Number , Boolean , Types . Decimal128 ] ; const operatorsWithExpression = [ '$or' , '$and' , '$not' , '$nor' ] ; function isPrimitive ( value ) { return primitives . some ( ( p ) => value instanceof p ) ; } function _toMongoDottedObject ( obj , aliases , target = { } , prefix = '' , collapseArray = false ) { if ( ( ( ! isObject ( obj ) as any ) && ! Array . isArray ( obj ) ) || isPrimitive ( obj ) ) { if ( prefix ) target [ prefix ] = obj ; return obj ; } const objKeys = Object . keys ( obj ) ; objKeys . forEach ( ( key ) => { let newKey ; if ( aliases && aliases ?. [ key ] ) { const alias = aliases ?. [ key ] ; let aliasValue ; if ( typeof alias === 'string' ) { aliasValue = alias ; } else if ( isObject ( alias ) ) { aliasValue = alias ?. __selfAlias ; } newKey = aliasValue || key ; } else { newKey = key ; } if ( prefix ) { newKey = `${ prefix }.${ newKey }` ; } if ( key . startsWith ( '$' ) ) { let val ; if ( operatorsWithExpression . includes ( key ) ) { val = Array . isArray ( obj [ key ] ) ? obj [ key ] . map ( ( v ) => _toMongoDottedObject ( v , aliases , { } , '' , collapseArray ) ) : _toMongoDottedObject ( obj [ key ] , aliases , { } , '' , collapseArray ) ; } else { val = obj [ key ] ; } if ( ! prefix ) { target [ key ] = val ; } else { target [ prefix ] = { ... target [ prefix ] , [ key ] : val , } ; } } else if ( Object ( obj [ key ] ) === obj [ key ] && ! isPrimitive ( obj [ key ] ) ) { const subAliases = aliases ?. [ key ] ; _toMongoDottedObject ( obj [ key ] , isObject ( subAliases ) ? subAliases : undefined , target , Array . isArray ( obj ) && collapseArray ? prefix : newKey , collapseArray ) ; } else { target [ newKey ] = obj [ key ] ; } } ) ; if ( objKeys . length === 0 ) { target [ prefix ] = obj ; } return target ; } param { Object } obj param { Object } aliases param { Object } target param { Array } path export function toMongoDottedObject ( obj , aliases ? , target = { } ) { return _toMongoDottedObject ( obj , aliases , target , '' ) ; } param { Object } obj param { Object } target param { Array } path export function toMongoFilterDottedObject ( obj , aliases ? , target = { } , prefix = '' ) { return _toMongoDottedObject ( obj , aliases , target , prefix , true ) ; }