import { Config , PathItem , DBConfig , Entity , JsonObject , IStorageAdapter } from '../types' ; import constants from './constants' ; import { S3Adapter , uuid , Cache , isReservedKey , checkValidObject , } from '../internal' ; const defaultConfig = { cacheExpiration : 500 } ; export class NearDB { /** Config that is used to init NearDB */ config : DBConfig ; /** UUID of Instance of NearDB */ instanceId : string ; adapter : IStorageAdapter ; static field = { deleteValue : constants . deleteValue } ; param config constructor ( config ) { this . instanceId = uuid ( ) ; /** Overwrites config param with default configuration */ this . config = { ... defaultConfig , ... config } ; this . adapter = new S3Adapter ( config ) ; } param config returns static database ( config ) { return new NearDB ( Object . assign ( defaultConfig , config ) ) ; } param key returns collection ( key ) { return new Collection ( this , key ) ; } } export class Collection implements Entity { readonly uri : PathItem [ ] ; readonly instance : NearDB ; constructor ( instance , key , path ? ) { if ( isReservedKey ( key ) ) { throw Error ( key + ': is a reserved keyword' ) ; } this . instance = instance ; const newPath = path ? [ ... path ] : [ ] ; newPath . push ( { type : 'collection' , key } ) ; this . uri = newPath ; } doc ( key ) { return new Document ( this . instance , key , this . uri ) ; } param value returns async add ( value ) { return new Document ( this . instance , uuid ( ) , this . uri ) . set ( value ) ; } } export class Document implements Entity { /** Data path that is used to interact with storage */ readonly uri : PathItem [ ] ; /** Instance of NearDB with all the configuration and env settings */ readonly instance : NearDB ; /** Offline cache of data */ readonly cache : Cache ; /** String path for storage */ constructor ( instance , key , path ) { if ( isReservedKey ( key ) ) { throw Error ( key + ': is a reserved keyword' ) ; } const newPath = [ ... path ] ; newPath . push ( { type : 'document' , key } ) ; this . uri = newPath ; this . instance = instance ; this . cache = new Cache ( this . instance . config . cacheExpiration ) ; } param key returns collection ( key ) { return new Collection ( this . instance , key , this . uri ) ; } param value returns async set ( value ) { checkValidObject ( value ) ; return this . instance . adapter . set ( value , this . uri ) ; } param options returns async get ( ) { try { return await this . instance . adapter . get ( this . uri ) ; } catch ( err ) { return null ; } } param value returns async update ( value ) { checkValidObject ( value ) ; await this . instance . adapter . update ( value , this . uri ) ; } returns async delete ( ) { await this . instance . adapter . remove ( this . uri ) ; } }