refactor: collection setup

This commit is contained in:
2026-01-03 00:44:59 +01:00
parent b9b12f790d
commit 7df5ed685d
30 changed files with 1056 additions and 1234 deletions

View File

@@ -1,16 +1,16 @@
import { hashCodeQuery } from "../../hash.ts";
import { Options } from "../../storage/mod.ts";
import type { Document, Filter, WithId } from "../../types.ts";
import type { QueryOptions } from "../../storage/mod.ts";
import type { Document, Filter } from "../../types.ts";
export class IndexedDbCache<TSchema extends Document = Document> {
export class IndexedDBCache<TSchema extends Document = Document> {
readonly #cache = new Map<number, string[]>();
readonly #documents = new Map<string, WithId<TSchema>>();
readonly #documents = new Map<string, TSchema>();
hash(filter: Filter<WithId<TSchema>>, options: Options): number {
hash(filter: Filter<TSchema>, options: QueryOptions): number {
return hashCodeQuery(filter, options);
}
set(hashCode: number, documents: WithId<TSchema>[]) {
set(hashCode: number, documents: TSchema[]) {
this.#cache.set(
hashCode,
documents.map((document) => document.id),
@@ -20,10 +20,10 @@ export class IndexedDbCache<TSchema extends Document = Document> {
}
}
get(hashCode: number): WithId<TSchema>[] | undefined {
get(hashCode: number): TSchema[] | undefined {
const ids = this.#cache.get(hashCode);
if (ids !== undefined) {
return ids.map((id) => this.#documents.get(id) as WithId<TSchema>);
return ids.map((id) => this.#documents.get(id) as TSchema);
}
}

View File

@@ -1,29 +1,32 @@
import { IDBPDatabase, openDB } from "idb";
import { type IDBPDatabase, openDB } from "idb";
import { Collection } from "../../collection.ts";
import { DBLogger } from "../../logger.ts";
import { Document } from "../../types.ts";
import { Registrars } from "../registrars.ts";
import { IndexedDbStorage } from "./storage.ts";
import type { DBLogger } from "../../logger.ts";
import type { Document } from "../../types.ts";
import type { Registrars } from "../registrars.ts";
import { IndexedDBStorage } from "./storage.ts";
export class IndexedDatabase<TCollections extends StringRecord<Document>> {
export class IndexedDB<TCollections extends StringRecord<Document>> {
readonly #collections = new Map<keyof TCollections, Collection<TCollections[keyof TCollections]>>();
readonly #db: Promise<IDBPDatabase<unknown>>;
constructor(readonly options: Options) {
this.#db = openDB(options.name, options.version ?? 1, {
upgrade: (db: IDBPDatabase) => {
for (const { name, indexes = [] } of options.registrars) {
const store = db.createObjectStore(name as string, { keyPath: "id" });
store.createIndex("id", "id", { unique: true });
for (const { name, primaryKey = "id", indexes = [] } of options.registrars) {
const store = db.createObjectStore(name as string, { keyPath: primaryKey });
store.createIndex(primaryKey, primaryKey, { unique: true });
for (const [keyPath, options] of indexes) {
store.createIndex(keyPath, keyPath, options);
}
}
},
});
for (const { name } of options.registrars) {
this.#collections.set(name, new Collection(name, new IndexedDbStorage(name, this.#db, options.log ?? log)));
for (const { name, primaryKey = "id" } of options.registrars) {
this.#collections.set(
name,
new Collection(name, new IndexedDBStorage(name, primaryKey, this.#db, options.log ?? log)),
);
}
}
@@ -33,9 +36,7 @@ export class IndexedDatabase<TCollections extends StringRecord<Document>> {
|--------------------------------------------------------------------------------
*/
collection<TSchema extends TCollections[Name], Name extends keyof TCollections = keyof TCollections>(
name: Name,
): Collection<TSchema> {
collection<Name extends keyof TCollections = keyof TCollections>(name: Name) {
const collection = this.#collections.get(name);
if (collection === undefined) {
throw new Error(`Collection '${name as string}' not found`);

View File

@@ -1,9 +1,10 @@
import { IDBPDatabase } from "idb";
import { createUpdater, Query } from "mingo";
import { UpdateOptions } from "mingo/core";
import { UpdateExpression } from "mingo/updater";
import type { IDBPDatabase } from "idb";
import { Query, update } from "mingo";
import type { Criteria, Options } from "mingo/types";
import type { CloneMode, Modifier } from "mingo/updater";
import { DBLogger, InsertLog, QueryLog, RemoveLog, ReplaceLog, UpdateLog } from "../../logger.ts";
import { type DBLogger, InsertLog, QueryLog, RemoveLog, ReplaceLog, UpdateLog } from "../../logger.ts";
import { getDocumentWithPrimaryKey } from "../../primary-key.ts";
import { DuplicateDocumentError } from "../../storage/errors.ts";
import {
getInsertManyResult,
@@ -13,17 +14,18 @@ import {
} from "../../storage/operators/insert.ts";
import { RemoveResult } from "../../storage/operators/remove.ts";
import { UpdateResult } from "../../storage/operators/update.ts";
import { addOptions, Index, Options, Storage } from "../../storage/storage.ts";
import type { Document, Filter, WithId } from "../../types.ts";
import { IndexedDbCache } from "./cache.ts";
import { addOptions, type Index, type QueryOptions, Storage } from "../../storage/storage.ts";
import type { Document, Filter } from "../../types.ts";
import { IndexedDBCache } from "./cache.ts";
const OBJECT_PROTOTYPE = Object.getPrototypeOf({});
const OBJECT_TAG = "[object Object]";
const update = createUpdater({ cloneMode: "deep" });
export class IndexedDbStorage<TSchema extends Document = Document> extends Storage<TSchema> {
readonly #cache = new IndexedDbCache<TSchema>();
export class IndexedDBStorage<TPrimaryKey extends string, TSchema extends Document = Document> extends Storage<
TPrimaryKey,
TSchema
> {
readonly #cache = new IndexedDBCache<TSchema>();
readonly #promise: Promise<IDBPDatabase>;
@@ -31,10 +33,11 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
constructor(
name: string,
primaryKey: TPrimaryKey,
promise: Promise<IDBPDatabase>,
readonly log: DBLogger,
) {
super(name);
super(name, primaryKey);
this.#promise = promise;
}
@@ -66,11 +69,12 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
|--------------------------------------------------------------------------------
*/
async insertOne(data: Partial<TSchema>): Promise<InsertOneResult> {
async insertOne(values: TSchema | Omit<TSchema, TPrimaryKey>): Promise<InsertOneResult> {
const logger = new InsertLog(this.name);
const document = { ...data, id: data.id ?? crypto.randomUUID() } as any;
if (await this.has(document.id)) {
const document = getDocumentWithPrimaryKey(this.primaryKey, values);
if (await this.has(document[this.primaryKey])) {
throw new DuplicateDocumentError(document, this as any);
}
await this.db.transaction(this.name, "readwrite", { durability: "relaxed" }).store.add(document);
@@ -83,15 +87,15 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
return getInsertOneResult(document);
}
async insertMany(data: Partial<TSchema>[]): Promise<InsertManyResult> {
async insertMany(values: (TSchema | Omit<TSchema, TPrimaryKey>)[]): Promise<InsertManyResult> {
const logger = new InsertLog(this.name);
const documents: WithId<TSchema>[] = [];
const documents: TSchema[] = [];
const tx = this.db.transaction(this.name, "readwrite", { durability: "relaxed" });
await Promise.all(
data.map((data) => {
const document = { ...data, id: data.id ?? crypto.randomUUID() } as WithId<TSchema>;
values.map((values) => {
const document = getDocumentWithPrimaryKey(this.primaryKey, values);
documents.push(document);
return tx.store.add(document);
}),
@@ -112,11 +116,11 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
|--------------------------------------------------------------------------------
*/
async findById(id: string): Promise<WithId<TSchema> | undefined> {
async findById(id: string): Promise<TSchema | undefined> {
return this.db.getFromIndex(this.name, "id", id);
}
async find(filter: Filter<WithId<TSchema>>, options: Options = {}): Promise<WithId<TSchema>[]> {
async find(filter: Filter<TSchema>, options: QueryOptions = {}): Promise<TSchema[]> {
const logger = new QueryLog(this.name, { filter, options });
const hashCode = this.#cache.hash(filter, options);
@@ -132,7 +136,7 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
cursor = addOptions(cursor, options);
}
const documents = cursor.all() as WithId<TSchema>[];
const documents = cursor.all() as TSchema[];
this.#cache.set(this.#cache.hash(filter, options), documents);
this.log(logger.result());
@@ -151,8 +155,8 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
if (indexNames.contains(key) === true) {
let val: any;
if (isObject(filter[key]) === true) {
if ((filter as any)[key]["$in"] !== undefined) {
val = (filter as any)[key]["$in"];
if ((filter as any)[key].$in !== undefined) {
val = (filter as any)[key].$in;
}
} else {
val = filter[key];
@@ -168,7 +172,7 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
return {};
}
async #getAll({ index, offset, range, limit }: Options) {
async #getAll({ index, offset, range, limit }: QueryOptions) {
if (index !== undefined) {
return this.#getAllByIndex(index);
}
@@ -230,34 +234,34 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
*/
async updateOne(
filter: Filter<WithId<TSchema>>,
expr: UpdateExpression,
arrayFilters?: Filter<WithId<TSchema>>[],
condition?: Filter<WithId<TSchema>>,
options?: UpdateOptions,
filter: Filter<TSchema>,
modifier: Modifier<TSchema>,
arrayFilters?: Filter<TSchema>[],
condition?: Criteria<TSchema>,
options: { cloneMode?: CloneMode; queryOptions?: Partial<Options> } = { cloneMode: "deep" },
): Promise<UpdateResult> {
if (typeof filter.id === "string") {
return this.#update(filter.id, expr, arrayFilters, condition, options);
return this.#update(filter.id, modifier, arrayFilters, condition, options);
}
const documents = await this.find(filter);
if (documents.length > 0) {
return this.#update(documents[0].id, expr, arrayFilters, condition, options);
return this.#update(documents[0].id, modifier, arrayFilters, condition, options);
}
return new UpdateResult(0, 0);
}
async updateMany(
filter: Filter<WithId<TSchema>>,
expr: UpdateExpression,
arrayFilters?: Filter<WithId<TSchema>>[],
condition?: Filter<WithId<TSchema>>,
options?: UpdateOptions,
filter: Filter<TSchema>,
modifier: Modifier<TSchema>,
arrayFilters?: Filter<TSchema>[],
condition?: Criteria<TSchema>,
options: { cloneMode?: CloneMode; queryOptions?: Partial<Options> } = { cloneMode: "deep" },
): Promise<UpdateResult> {
const logger = new UpdateLog(this.name, { filter, expr, arrayFilters, condition, options });
const logger = new UpdateLog(this.name, { filter, modifier, arrayFilters, condition, options });
const ids = await this.find(filter).then((data) => data.map((d) => d.id));
const documents: WithId<TSchema>[] = [];
const documents: TSchema[] = [];
let modifiedCount = 0;
const tx = this.db.transaction(this.name, "readwrite", { durability: "relaxed" });
@@ -267,7 +271,7 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
if (current === undefined) {
return;
}
const modified = update(current, expr, arrayFilters, condition, options);
const modified = update(current, modifier, arrayFilters, condition, options);
if (modified.length > 0) {
modifiedCount += 1;
documents.push(current);
@@ -287,12 +291,12 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
return new UpdateResult(ids.length, modifiedCount);
}
async replace(filter: Filter<WithId<TSchema>>, document: WithId<TSchema>): Promise<UpdateResult> {
async replace(filter: Filter<TSchema>, document: TSchema): Promise<UpdateResult> {
const logger = new ReplaceLog(this.name, document);
const ids = await this.find(filter).then((data) => data.map((d) => d.id));
const documents: WithId<TSchema>[] = [];
const documents: TSchema[] = [];
const count = ids.length;
const tx = this.db.transaction(this.name, "readwrite", { durability: "relaxed" });
@@ -315,12 +319,12 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
async #update(
id: string | number,
expr: UpdateExpression,
arrayFilters?: Filter<WithId<TSchema>>[],
condition?: Filter<WithId<TSchema>>,
options?: UpdateOptions,
modifier: Modifier<TSchema>,
arrayFilters?: Filter<TSchema>[],
condition?: Criteria<TSchema>,
options: { cloneMode?: CloneMode; queryOptions?: Partial<Options> } = { cloneMode: "deep" },
): Promise<UpdateResult> {
const logger = new UpdateLog(this.name, { id, expr });
const logger = new UpdateLog(this.name, { id, modifier });
const tx = this.db.transaction(this.name, "readwrite", { durability: "relaxed" });
@@ -330,7 +334,7 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
return new UpdateResult(0, 0);
}
const modified = await update(current, expr, arrayFilters, condition, options);
const modified = await update(current, modifier, arrayFilters, condition, options);
if (modified.length > 0) {
await tx.store.put(current);
}
@@ -352,7 +356,7 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
|--------------------------------------------------------------------------------
*/
async remove(filter: Filter<WithId<TSchema>>): Promise<RemoveResult> {
async remove(filter: Filter<TSchema>): Promise<RemoveResult> {
const logger = new RemoveLog(this.name, { filter });
const documents = await this.find(filter);
@@ -375,7 +379,7 @@ export class IndexedDbStorage<TSchema extends Document = Document> extends Stora
|--------------------------------------------------------------------------------
*/
async count(filter?: Filter<WithId<TSchema>>): Promise<number> {
async count(filter?: Filter<TSchema>): Promise<number> {
if (filter !== undefined) {
return (await this.find(filter)).length;
}

View File

@@ -1,6 +1,6 @@
import { Collection } from "../../collection.ts";
import { Document } from "../../types.ts";
import { Registrars } from "../registrars.ts";
import type { Document } from "../../types.ts";
import type { Registrars } from "../registrars.ts";
import { MemoryStorage } from "./storage.ts";
type Options = {

View File

@@ -1,145 +1,155 @@
import { createUpdater, Query } from "mingo";
import { UpdateOptions } from "mingo/core";
import { UpdateExpression } from "mingo/updater";
import { Query, update } from "mingo";
import type { AnyObject } from "mingo/types";
import { DuplicateDocumentError } from "../../storage/errors.ts";
import { getDocumentWithPrimaryKey } from "../../primary-key.ts";
import { Collections } from "../../storage/collections.ts";
import type { UpdatePayload } from "../../storage/mod.ts";
import type { InsertResult } from "../../storage/operators/insert.ts";
import type { UpdateResult } from "../../storage/operators/update.ts";
import {
getInsertManyResult,
getInsertOneResult,
type InsertManyResult,
type InsertOneResult,
} from "../../storage/operators/insert.ts";
import { RemoveResult } from "../../storage/operators/remove.ts";
import { UpdateResult } from "../../storage/operators/update.ts";
import { addOptions, Options, Storage } from "../../storage/storage.ts";
import type { Document, Filter, WithId } from "../../types.ts";
addOptions,
type CountPayload,
type FindByIdPayload,
type FindPayload,
type InsertManyPayload,
type InsertOnePayload,
type RemovePayload,
type ReplacePayload,
Storage,
} from "../../storage/storage.ts";
import type { AnyDocument } from "../../types.ts";
const update = createUpdater({ cloneMode: "deep" });
export class MemoryStorage<TSchema extends Document = Document> extends Storage<TSchema> {
readonly #documents = new Map<string, WithId<TSchema>>();
export class MemoryStorage extends Storage {
readonly #collections = new Collections();
async resolve() {
return this;
}
async has(id: string): Promise<boolean> {
return this.#documents.has(id);
}
async insertOne({ pkey, values, ...payload }: InsertOnePayload): Promise<InsertResult> {
const collection = this.#collections.get(payload.collection);
async insertOne(data: Partial<TSchema>): Promise<InsertOneResult> {
const document = { ...data, id: data.id ?? crypto.randomUUID() } as WithId<TSchema>;
if (await this.has(document.id)) {
throw new DuplicateDocumentError(document, this as any);
const document = getDocumentWithPrimaryKey(pkey, values);
if (collection.has(document[pkey])) {
return { insertCount: 0, insertIds: [] };
}
this.#documents.set(document.id, document);
collection.set(document[pkey], document);
this.broadcast("insertOne", document);
return getInsertOneResult(document);
return { insertCount: 1, insertIds: [document[pkey]] };
}
async insertMany(documents: Partial<TSchema>[]): Promise<InsertManyResult> {
const result: TSchema[] = [];
for (const data of documents) {
const document = { ...data, id: data.id ?? crypto.randomUUID() } as WithId<TSchema>;
result.push(document);
this.#documents.set(document.id, document);
async insertMany({ pkey, values, ...payload }: InsertManyPayload): Promise<InsertResult> {
const collection = this.#collections.get(payload.collection);
const documents: AnyDocument[] = [];
for (const insert of values) {
const document = getDocumentWithPrimaryKey(pkey, insert);
if (collection.has(document[pkey])) {
continue;
}
collection.set(document[pkey], document);
documents.push(document);
}
this.broadcast("insertMany", result);
if (documents.length > 0) {
this.broadcast("insertMany", documents);
}
return getInsertManyResult(result);
return { insertCount: documents.length, insertIds: documents.map((document) => document[pkey]) };
}
async findById(id: string): Promise<WithId<TSchema> | undefined> {
return this.#documents.get(id);
async findById({ collection, id }: FindByIdPayload): Promise<AnyObject | undefined> {
return this.#collections.get(collection).get(id);
}
async find(filter?: Filter<WithId<TSchema>>, options?: Options): Promise<WithId<TSchema>[]> {
let cursor = new Query(filter ?? {}).find<TSchema>(Array.from(this.#documents.values()));
async find({ condition = {}, options, ...payload }: FindPayload): Promise<AnyDocument[]> {
let cursor = new Query(condition).find<AnyDocument>(this.#collections.documents(payload.collection));
if (options !== undefined) {
cursor = addOptions(cursor, options);
}
return cursor.all() as WithId<TSchema>[];
return cursor.all();
}
async updateOne(
filter: Filter<WithId<TSchema>>,
expr: UpdateExpression,
arrayFilters?: Filter<WithId<TSchema>>[],
condition?: Filter<WithId<TSchema>>,
options?: UpdateOptions,
): Promise<UpdateResult> {
for (const document of await this.find(filter)) {
const modified = update(document, expr, arrayFilters, condition, options);
if (modified.length > 0) {
this.#documents.set(document.id, document);
this.broadcast("updateOne", document);
return new UpdateResult(1, 1);
}
return new UpdateResult(1, 0);
}
return new UpdateResult(0, 0);
}
async updateMany(
filter: Filter<WithId<TSchema>>,
expr: UpdateExpression,
arrayFilters?: Filter<WithId<TSchema>>[],
condition?: Filter<WithId<TSchema>>,
options?: UpdateOptions,
): Promise<UpdateResult> {
const documents: WithId<TSchema>[] = [];
async updateOne({ pkey, condition, modifier, arrayFilters, ...payload }: UpdatePayload): Promise<UpdateResult> {
const collection = this.#collections.get(payload.collection);
let matchedCount = 0;
let modifiedCount = 0;
for (const document of await this.find(filter)) {
for (const document of await this.find({ collection: payload.collection, condition, options: { limit: 1 } })) {
const modified = update(document, modifier, arrayFilters, undefined, { cloneMode: "deep" });
if (modified.length > 0) {
collection.set(document[pkey], document);
this.broadcast("updateOne", document);
modifiedCount += 1;
}
matchedCount += 1;
const modified = update(document, expr, arrayFilters, condition, options);
}
return { matchedCount, modifiedCount };
}
async updateMany({ pkey, condition, modifier, arrayFilters, ...payload }: UpdatePayload): Promise<UpdateResult> {
const collection = this.#collections.get(payload.collection);
const documents: AnyDocument[] = [];
let matchedCount = 0;
let modifiedCount = 0;
for (const document of await this.find({ collection: payload.collection, condition })) {
matchedCount += 1;
const modified = update(document, modifier, arrayFilters, undefined, { cloneMode: "deep" });
if (modified.length > 0) {
modifiedCount += 1;
documents.push(document);
this.#documents.set(document.id, document);
collection.set(document[pkey], document);
}
}
this.broadcast("updateMany", documents);
return new UpdateResult(matchedCount, modifiedCount);
return { matchedCount, modifiedCount };
}
async replace(filter: Filter<WithId<TSchema>>, document: WithId<TSchema>): Promise<UpdateResult> {
const documents: WithId<TSchema>[] = [];
async replace({ pkey, condition, document, ...payload }: ReplacePayload): Promise<UpdateResult> {
const collection = this.#collections.get(payload.collection);
let matchedCount = 0;
let modifiedCount = 0;
for (const current of await this.find(filter)) {
const documents: AnyDocument[] = [];
for (const current of await this.find({ collection: payload.collection, condition })) {
matchedCount += 1;
modifiedCount += 1;
documents.push(document);
this.#documents.set(current.id, document);
collection.set(current[pkey], document);
}
this.broadcast("updateMany", documents);
return new UpdateResult(matchedCount, modifiedCount);
return { matchedCount, modifiedCount };
}
async remove(filter: Filter<WithId<TSchema>>): Promise<RemoveResult> {
const documents = await this.find(filter);
async remove({ pkey, condition, ...payload }: RemovePayload): Promise<number> {
const collection = this.#collections.get(payload.collection);
const documents = await this.find({ collection: payload.collection, condition });
for (const document of documents) {
this.#documents.delete(document.id);
collection.delete(document[pkey]);
}
this.broadcast("remove", documents);
return new RemoveResult(documents.length);
return documents.length;
}
async count(filter?: Filter<WithId<TSchema>>): Promise<number> {
return new Query(filter ?? {}).find(Array.from(this.#documents.values())).count();
async count({ collection, condition = {} }: CountPayload): Promise<number> {
return new Query(condition).find(this.#collections.documents(collection)).all().length;
}
async flush(): Promise<void> {
this.#documents.clear();
this.#collections.flush();
}
}

View File

@@ -1,23 +1,16 @@
import { createUpdater, Query } from "mingo";
import { UpdateOptions } from "mingo/core";
import { UpdateExpression } from "mingo/updater";
import { Query, update } from "mingo";
import type { Criteria, Options } from "mingo/types";
import type { CloneMode, Modifier } from "mingo/updater";
import { getDocumentWithPrimaryKey } from "../../primary-key.ts";
import { DuplicateDocumentError } from "../../storage/errors.ts";
import {
getInsertManyResult,
getInsertOneResult,
InsertManyResult,
InsertOneResult,
} from "../../storage/operators/insert.ts";
import { RemoveResult } from "../../storage/operators/remove.ts";
import type { InsertResult } from "../../storage/operators/insert.ts";
import { UpdateResult } from "../../storage/operators/update.ts";
import { addOptions, Options, Storage } from "../../storage/storage.ts";
import { Document, Filter, WithId } from "../../types.ts";
import { addOptions, type QueryOptions, Storage } from "../../storage/storage.ts";
import type { AnyDocument } from "../../types.ts";
const update = createUpdater({ cloneMode: "deep" });
export class ObserverStorage<TSchema extends Document = Document> extends Storage<TSchema> {
readonly #documents = new Map<string, WithId<TSchema>>();
export class ObserverStorage extends Storage {
readonly #documents = new Map<string, AnyDocument>();
async resolve() {
return this;
@@ -27,48 +20,48 @@ export class ObserverStorage<TSchema extends Document = Document> extends Storag
return this.#documents.has(id);
}
async insertOne(data: Partial<TSchema>): Promise<InsertOneResult> {
const document = { ...data, id: data.id ?? crypto.randomUUID() } as WithId<TSchema>;
if (await this.has(document.id)) {
async insertOne(values: AnyDocument): Promise<InsertResult> {
const document = getDocumentWithPrimaryKey(this.primaryKey, values);
if (await this.has(document[this.primaryKey])) {
throw new DuplicateDocumentError(document, this as any);
}
this.#documents.set(document.id, document);
this.#documents.set(document[this.primaryKey], document);
return getInsertOneResult(document);
}
async insertMany(documents: Partial<TSchema>[]): Promise<InsertManyResult> {
async insertMany(list: TSchema[]): Promise<InsertResult> {
const result: TSchema[] = [];
for (const data of documents) {
const document = { ...data, id: data.id ?? crypto.randomUUID() } as WithId<TSchema>;
for (const values of list) {
const document = getDocumentWithPrimaryKey(this.primaryKey, values);
result.push(document);
this.#documents.set(document.id, document);
}
return getInsertManyResult(result);
}
async findById(id: string): Promise<WithId<TSchema> | undefined> {
async findById(id: string): Promise<TSchema | undefined> {
return this.#documents.get(id);
}
async find(filter?: Filter<WithId<TSchema>>, options?: Options): Promise<WithId<TSchema>[]> {
async find(filter?: Filter<TSchema>, options?: QueryOptions): Promise<TSchema[]> {
let cursor = new Query(filter ?? {}).find<TSchema>(Array.from(this.#documents.values()));
if (options !== undefined) {
cursor = addOptions(cursor, options);
}
return cursor.all() as WithId<TSchema>[];
return cursor.all();
}
async updateOne(
filter: Filter<WithId<TSchema>>,
expr: UpdateExpression,
arrayFilters?: Filter<WithId<TSchema>>[],
condition?: Filter<WithId<TSchema>>,
options?: UpdateOptions,
filter: Filter<TSchema>,
modifier: Modifier<TSchema>,
arrayFilters?: Filter<TSchema>[],
condition?: Criteria<TSchema>,
options: { cloneMode?: CloneMode; queryOptions?: Partial<Options> } = { cloneMode: "deep" },
): Promise<UpdateResult> {
const query = new Query(filter);
for (const document of Array.from(this.#documents.values())) {
if (query.test(document) === true) {
const modified = update(document, expr, arrayFilters, condition, options);
const modified = update(document, modifier, arrayFilters, condition, options);
if (modified.length > 0) {
this.#documents.set(document.id, document);
this.broadcast("updateOne", document);
@@ -81,15 +74,15 @@ export class ObserverStorage<TSchema extends Document = Document> extends Storag
}
async updateMany(
filter: Filter<WithId<TSchema>>,
expr: UpdateExpression,
arrayFilters?: Filter<WithId<TSchema>>[],
condition?: Filter<WithId<TSchema>>,
options?: UpdateOptions,
filter: Filter<TSchema>,
modifier: Modifier<TSchema>,
arrayFilters?: Filter<TSchema>[],
condition?: Criteria<TSchema>,
options: { cloneMode?: CloneMode; queryOptions?: Partial<Options> } = { cloneMode: "deep" },
): Promise<UpdateResult> {
const query = new Query(filter);
const documents: WithId<TSchema>[] = [];
const documents: TSchema[] = [];
let matchedCount = 0;
let modifiedCount = 0;
@@ -97,7 +90,7 @@ export class ObserverStorage<TSchema extends Document = Document> extends Storag
for (const document of Array.from(this.#documents.values())) {
if (query.test(document) === true) {
matchedCount += 1;
const modified = update(filter, expr, arrayFilters, condition, options);
const modified = update(document, modifier, arrayFilters, condition, options);
if (modified.length > 0) {
modifiedCount += 1;
documents.push(document);
@@ -111,10 +104,10 @@ export class ObserverStorage<TSchema extends Document = Document> extends Storag
return new UpdateResult(matchedCount, modifiedCount);
}
async replace(filter: Filter<WithId<TSchema>>, document: WithId<TSchema>): Promise<UpdateResult> {
async replace(filter: Filter<TSchema>, document: TSchema): Promise<UpdateResult> {
const query = new Query(filter);
const documents: WithId<TSchema>[] = [];
const documents: TSchema[] = [];
let matchedCount = 0;
let modifiedCount = 0;
@@ -131,7 +124,7 @@ export class ObserverStorage<TSchema extends Document = Document> extends Storag
return new UpdateResult(matchedCount, modifiedCount);
}
async remove(filter: Filter<WithId<TSchema>>): Promise<RemoveResult> {
async remove(filter: Filter<TSchema>): Promise<RemoveResult> {
const documents = Array.from(this.#documents.values());
const query = new Query(filter);
let count = 0;
@@ -144,8 +137,8 @@ export class ObserverStorage<TSchema extends Document = Document> extends Storag
return new RemoveResult(count);
}
async count(filter?: Filter<WithId<TSchema>>): Promise<number> {
return new Query(filter ?? {}).find(Array.from(this.#documents.values())).count();
async count(filter?: Filter<TSchema>): Promise<number> {
return new Query(filter ?? {}).find(Array.from(this.#documents.values())).all().length;
}
async flush(): Promise<void> {

View File

@@ -1,6 +1,23 @@
export type Registrars = {
/**
* Name of the collection.
*/
name: string;
/**
* Set the primary key of the collection.
* Default: "id"
*/
primaryKey?: string;
/**
* List of custom indexes for the collection.
*/
indexes?: Index[];
};
type Index = [string, any?];
type Index = [IndexKey, IndexOptions?];
type IndexKey = string;
type IndexOptions = { unique: boolean };