@live-change/db
Advanced tools
Comparing version 0.2.3 to 0.2.4
@@ -174,4 +174,12 @@ const Table = require('./Table.js') | ||
queryObjectGet(code) { | ||
return queryGet.single(this, code) | ||
} | ||
queryObjectObservable(code) { | ||
return queryObservable.single(this, code) | ||
} | ||
} | ||
module.exports = Database |
@@ -127,2 +127,10 @@ const { TableWriter, LogWriter } = require('./queryUpdate.js') | ||
async function querySingleGet(database, code) { | ||
const reader = new QueryReader(database) | ||
const writer = new QueryWriter(database) | ||
await code(reader, writer) | ||
return writer.getResults()[0] || null | ||
} | ||
queryGet.single = querySingleGet | ||
queryGet.QueryWriter = QueryWriter | ||
@@ -129,0 +137,0 @@ queryGet.QueryReader = QueryReader |
@@ -268,2 +268,12 @@ const ReactiveDao = require("@live-change/dao") | ||
} | ||
getSingleResultAndStartObservation() { | ||
this.#observationMode = true | ||
const value = ( | ||
Array.from(this.#results.entries()) | ||
.sort((a,b)=>a[0]>b[0]?1:(a[0]<b[0]?-1:0) ) | ||
.map(a => a[1]) | ||
)[0] || null | ||
this.#observable.set(value) | ||
} | ||
async synchronized(key, code) { | ||
@@ -342,2 +352,59 @@ let promise = this.#locks.get(key) | ||
class QuerySingleObservable extends ReactiveDao.ObservableValue { | ||
constructor(database, code) { | ||
super() | ||
this.database = database | ||
this.code = code | ||
this.disposed = false | ||
this.ready = false | ||
this.respawnId = 0 | ||
this.forward = null | ||
this.readPromise = this.startReading() | ||
} | ||
async startReading() { | ||
this.reader = new QueryReader(this.database) | ||
this.writer = new QueryWriter(this, this.database) | ||
await this.code(this.reader, this.writer) | ||
this.reader.state = READER_OBSERVING | ||
this.writer.getSingleResultAndStartObservation() | ||
} | ||
async putObject(object, oldObject) { | ||
await this.readPromise | ||
this.set(object, oldObject) | ||
} | ||
async deleteObject(object) { | ||
await this.readPromise | ||
this.set(null, object) | ||
} | ||
dispose() { | ||
if(this.forward) { | ||
this.forward.unobserve(this) | ||
this.forward = null | ||
return | ||
} | ||
if(this.reader) this.reader.dispose() | ||
this.disposed = true | ||
this.respawnId++ | ||
} | ||
respawn() { | ||
this.respawnId++ | ||
this.ready = false | ||
this.disposed = false | ||
this.startReading() | ||
} | ||
} | ||
function queryObservable(database, code) { | ||
@@ -347,2 +414,7 @@ return new QueryObservable(database, code) | ||
function querySingleObservable(database, code) { | ||
return new QuerySingleObservable(database, code) | ||
} | ||
queryObservable.single = querySingleObservable | ||
queryObservable.QueryWriter = QueryWriter | ||
@@ -349,0 +421,0 @@ queryObservable.QueryReader = QueryReader |
{ | ||
"name": "@live-change/db", | ||
"version": "0.2.3", | ||
"version": "0.2.4", | ||
"description": "Database with observable data for live queries", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
66123
2038