All files / src mongo.backend.ts

100% Statements 32/32
100% Branches 12/12
100% Functions 11/11
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81    3x           3x   3x       27x       2x       1x       2x         2x 2x   2x       3x 3x 2x   3x       3x 3x 3x   3x       1x       10x 6x 5x 1x       6x       2x 2x 2x   2x       2x      
'use strict';
 
import {cloneDeep, isArray, omit} from 'lodash';
import {Model} from 'mongoose';
import {Observable} from 'rxjs';
 
import type {IObservableBackend} from '@owservable/core';
 
import observableMongoModel from './functions/observable.model.factory';
 
export default class MongoBackend implements IObservableBackend {
	private readonly _model: Model<any>;
 
	constructor(model: Model<any>) {
		this._model = model;
	}
 
	public target(): string {
		return this._model.collection.collectionName;
	}
 
	public changes(): Observable<any> {
		return observableMongoModel(this._model);
	}
 
	public async find(query: any, fields: any, paging: any, sort: any, populates: any[]): Promise<any[]> {
		const documents: any[] = await this._model //
			.find(query, fields, paging)
			.sort(sort)
			.setOptions({allowDiskUse: true});
 
		for (const populate of populates) {
			await this._model.populate(documents, populate);
		}
		return documents;
	}
 
	public async findOne(query: any, fields: any, populates: any[]): Promise<any> {
		const document: any = await this._model.findOne(query, fields);
		for (const populate of populates) {
			await this.populate(document, populate);
		}
		return document;
	}
 
	public async findById(id: string, fields: any, populates: any[]): Promise<any> {
		const document: any = await this._model.findById(id, fields);
		for (const populate of populates) {
			await this.populate(document, populate);
		}
		return document;
	}
 
	public async count(query: any): Promise<number> {
		return this._model.countDocuments(query);
	}
 
	public async populate(document: any, populate: any): Promise<any> {
		if (!document) return document;
		if (isArray(document)) return this._model.populate(document, populate);
		if (document.populate) return document.populate(populate);
		return this._model.populate(document, populate);
	}
 
	public toJSON(document: any): any {
		return document?.toJSON ? document.toJSON() : document;
	}
 
	public async resolveVirtuals(document: any, virtuals: string[]): Promise<any> {
		const replacement: any = cloneDeep(omit(this.toJSON(document), virtuals));
		for (const virtual of virtuals) {
			replacement[virtual] = await Promise.resolve(document[virtual]);
		}
		return replacement;
	}
 
	public get model(): Model<any> {
		return this._model;
	}
}