Switching to new Query mechanism

This commit is contained in:
Fabian Stamm
2019-11-14 17:28:07 +01:00
parent 72e5c0dedd
commit 0175822699
4 changed files with 132 additions and 135 deletions

View File

@ -5,6 +5,25 @@ import DocumentLock from "./lock";
import { DocumentQuery, CollectionQuery, Query } from "./query";
import Logging from "@hibas123/nodelogging";
import Session from "./session";
import nanoid = require("nanoid");
type IWriteQueries = "set" | "update" | "delete" | "add";
type ICollectionQueries = "get" | "add" | "keys" | "delete-collection" | "list";
type IDocumentQueries = "get" | "set" | "update" | "delete";
export interface ITypedQuery<T> {
path: string[];
type: T;
data?: any;
options?: any;
}
interface ITransaction {
queries: ITypedQuery<IWriteQueries>[];
}
export type IQuery = ITypedQuery<ICollectionQueries | IDocumentQueries>;
export class DatabaseManager {
static databases = new Map<string, Database>();
@ -115,6 +134,82 @@ export class Database {
return new Query(this, path, session);
}
async run(query: IQuery, session: Session) {
const isCollection = query.path.length % 2 === 1;
if (isCollection) {
const q = new CollectionQuery(this, query.path, session);
let type = query.type as ICollectionQueries;
switch (type) {
case "add":
return q.add(query.data);
case "get":
const limit = (query.options || {}).limit;
if (limit)
q.limit = limit;
const where = (query.options || {}).where;
if (where)
q.where = where;
return q.get();
case "keys":
return q.keys();
case "list":
return q.collections();
case "delete-collection":
return q.deleteCollection();
default:
return Promise.reject(new Error("Invalid query!"));
}
} else {
const q = new DocumentQuery(this, query.path, session);
let type = query.type as IDocumentQueries;
switch (type) {
case "get":
return q.get();
case "set":
return q.set(query.data, query.options || {});
case "update":
return q.update(query.data);
case "delete":
return q.delete();
default:
return Promise.reject(new Error("Invalid query!"));
}
}
}
async snapshot(query: ITypedQuery<"snapshot">, session: Session, onchange: (change: any) => void) {
const isCollection = query.path.length % 2 === 1;
let q: DocumentQuery | CollectionQuery;
if (isCollection) {
q = new CollectionQuery(this, query.path, session);
const limit = (query.options || {}).limit;
if (limit)
q.limit = limit;
const where = (query.options || {}).where;
if (where)
q.where = where;
} else {
q = new DocumentQuery(this, query.path, session);
}
const id = nanoid(16);
session.queries.set(id, q);
return {
id,
snaphot: await q.snapshot(onchange)
};
}
async unsubscribe(id: string, session: Session) {
let query: CollectionQuery | DocumentQuery = session.queries.get(id) as any;
if (query) {
query.unsubscribe();
session.queries.delete(id);
}
}
async stop() {
await this.data.close();
}