import { Model } from './Model' ; import { utils } from 'realm-utils' ; import { Config } from './FuseDB' ; import { MongoAdapter , getMongoModule , MongoAdapterImpl } from './adapters/MongoAdapter' ; export function storeProp ( target , key , fn ) { let data = target [ key ] ; if ( ! data ) { Object . defineProperty ( target , key , { value : fn ( ) , enumerable : false } ) ; data = target [ key ] ; } return data ; } export function isValidObjectID ( str ) { str = str + '' ; var len = str . length , valid = false ; if ( len == 12 || len == 24 ) { valid = /^[0-9a-fA-F]+$/ . test ( str ) ; } return valid ; } export function fastHash ( text ) { let hash = 0 ; if ( text . length == 0 ) return hash ; for ( let i = 0 ; i < text . length ; i ++ ) { let char = text . charCodeAt ( i ) ; hash = ( ( hash << 5 ) - hash ) + char ; hash = hash & hash ; } return hash . toString ( 16 ) ; } export function ensureValidMongoID ( id ) { if ( Config . adapter instanceof MongoAdapterImpl ) { const ObjectID = getMongoModule ( ) . ObjectID ; if ( id instanceof ObjectID ) { return id ; } if ( typeof id === "string" && isValidObjectID ( id ) ) { return ObjectID ( id ) ; } } } export function ensureDatabaseCorrectValues ( value ) { if ( Config . adapter instanceof MongoAdapterImpl ) { if ( typeof value === "string" && isValidObjectID ( value ) ) { const ObjectID = getMongoModule ( ) . ObjectID ; return ObjectID ( value ) ; } } if ( value instanceof Model ) { return value . _id ; } else { if ( utils . isArray ( value ) ) { return value . map ( i => ensureDatabaseCorrectValues ( i ) ) ; } if ( utils . isPlainObject ( value ) ) { let obj = { } ; for ( let key in value ) { value [ key ] = ensureDatabaseCorrectValues ( value [ key ] ) ; } return value ; } return value ; } return value ; }