import * as Util from 'util' ; import * as Pluralize from 'pluralize' ; import { IModel } from '@interfaces' ; import { isObject } from '@utils/object.util' ; class SanitizeService { description private static instance : SanitizeService ; private constructor ( ) { } description static get ( ) { if ( ! SanitizeService . instance ) { SanitizeService . instance = new SanitizeService ( ) ; } return SanitizeService . instance ; } description param data hasEligibleMember ( data ) { return ( this . implementsWhitelist ( data ) && ! Array . isArray ( data ) ) || ( Array . isArray ( data ) && [ ] . concat ( data ) . some ( obj => this . implementsWhitelist ( obj ) ) || ( isObject ( data ) && Object . keys ( data ) . some ( key => this . implementsWhitelist ( data [ key ] ) ) ) ) ; } description param data process ( data ) { if ( Array . isArray ( data ) ) { return [ ] . concat ( data ) . map ( ( d ) => this . implementsWhitelist ( d ) ? this . sanitize ( d as IModel ) : d as Record < string , unknown > ) ; } if ( this . implementsWhitelist ( data ) ) { return this . sanitize ( data as IModel ) ; } if ( isObject ( data ) ) { return Object . keys ( data ) . reduce ( ( acc , current ) => { acc [ current ] = this . implementsWhitelist ( data [ current ] ) ? this . sanitize ( data [ current ] ) : data [ current ] ; return acc ; } , { } ) ; } } description param whitelist param entity private sanitize ( entity ) { const output = { } as Record < string , unknown > ; Object . keys ( entity ) . map ( ( key ) => { if ( entity . whitelist . includes ( key ) || entity . whitelist . includes ( Pluralize ( key ) ) ) { output [ key ] = this . isSanitizable ( entity [ key ] ) ? Array . isArray ( entity [ key ] ) ? entity [ key ] . length > 0 ? entity [ key ] . map ( e => this . sanitize ( e ) ) : [ ] : this . sanitize ( entity [ key ] ) : entity [ key ] ; } } ) ; return output ; } description param obj private implementsWhitelist ( obj ) { return isObject ( obj ) && 'whitelist' in obj ; } description param value private isSanitizable ( value ) { if ( ! value ) { return false ; } if ( Util . types . isDate ( value ) || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ) { return false ; } if ( isObject ( value ) && value . constructor === Object ) { return false ; } if ( isObject ( value ) && Array . isArray ( value ) && value . filter ( ( v ) => typeof v === 'string' || ( isObject ( v ) && v . constructor === Object ) ) . length > 0 ) { return false ; } return true ; } } const sanitizeService = SanitizeService . get ( ) ; export { sanitizeService as SanitizeService } ;