All files / database repository.ts

62.5% Statements 60/96
42.59% Branches 23/54
72.22% Functions 13/18
63.04% Lines 58/92

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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188  3x 3x   3x   3x     1x 1x     1x 1x 1x     1x 1x                                             2x 2x   2x       2x 2x     2x                   2x 2x 2x   2x       2x 2x 2x   2x       2x                       2x 12x       12x                 1x 1x 1x 1x   2x 1x 1x   1x       1x 1x 1x   1x 1x 1x 1x   1x           1x                   2x 2x     2x   2x 7x 7x           2x 2x   2x 2x 7x 2x                                                
 
import { Model, Document, Types, DocumentQuery, Query, Connection } from 'mongoose';
import { pick, PartialDeep, groupBy } from 'lodash';
import { KeyValue } from '../types/data.types';
const treeify = require('array-to-tree');
 
export class Repository {
 
    static async remove(model: Model<Document>, id: string): Promise<any> {
        const ids = id.split(',');
        Iif (ids.length > 1) {
            return this.removeItems(model, ids);
        } else {
            return new Promise((resolve, reject) => {
                model.findOneAndRemove({ _id: id }).exec((err, res) => {
                    Iif (err) {
                        reject(err);
                    } else {
                        Eif (res)
                            resolve(true);
                        else {
                            resolve(false);
                        }
                    }
                });
            });
        }
    }
 
    static async removeItems(model: Model<Document>, ids: string[]): Promise<any> {
        return new Promise((resolve, reject) => {
            model.remove({ _id: { $in: ids } }).exec((err, res) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(true);
                }
            });
        });
    }
 
    static async get(model: Model<Document>, id: string, populates?: any[]): Promise<any> {
        const option: any = {};
        return new Promise((resolve, reject) => {
 
            Iif (populates && populates.length) {
                option.populate = populates;
            }
 
            model.findOne({ _id: id }, null, option).exec((err, res: any) => {
                Iif (err) {
                    reject(err);
                } else {
                    resolve(res);
                }
            });
        });
    }
 
    static async search(model: Model<Document>,
        keyword?: string, id?: string,
        category = '', limit: number = 10, labelField = 'name', valueField = '_id', searchField = 'name'): Promise<Array<KeyValue>> {
 
        const critical: any = {};
        critical[searchField] = new RegExp(keyword, 'i');
        const query: any = keyword ? critical : {};
 
        Iif (category) {
            query.category = category;
        }
 
        const fields: any = {};
        fields[labelField] = 1;
        fields[valueField] = 1;
 
        const docs = await model.find(query).select(fields)
            .limit(limit)
            .exec() || [];
 
        Iif (id && (Types.ObjectId.isValid(id) || valueField !== '_id')) {
            const conditions: any = {};
            conditions[valueField] = id;
            const selected = await model.findOne(conditions).select(fields);
            if (selected) {
                const found = docs.findIndex((doc: any) => doc[valueField] == id);
                if (found === -1) {
                    docs.push(selected);
                }
            }
        }
 
        return docs.map((item: any) => {
            const result: KeyValue = {
                label: item[labelField],
                value: item[valueField]
            };
            return result;
        });
    }
 
    static async deeplyFind(
        query: Model<Document>,
        id: string
    ): Promise<string[]> {
 
        let current: any = await query.findOne({ _id: id }).select({ _id: 1, parent: 1 }).exec();
        Iif (!current) { return []; }
        const items = await query.find().select({ _id: 1, parent: 1 }).exec() || [];
        const currentId = current.toObject()._id;
 
        const data = items.map(item => item.toObject());
        const cached = groupBy(data, 'parent');
        const children = cached[currentId];
 
        Iif (!Array.isArray(children)) {
            return [currentId];
        }
 
        const result: string[] = [currentId];
        const stack = [];
        stack.push(...children);
 
        while (stack.length > 0) {
            const node: any = stack.pop();
            result.push(node._id);
            const items = cached[node._id];
 
            Iif (Array.isArray(items)) {
                for (let item of items) {
                    stack.push(item);
                }
            }
        }
        return result;
    }
 
    static async query<T extends Document, TResponse>(
        query: DocumentQuery<T[], T>,
        collection: DocumentQuery<T[], T>,
        page: number = 1,
        size: number = 20,
        fields: string[]
    ) {
        page = page - 1;
        Iif (page < 0) {
            page = 0;
        }
        const countPromise = collection.count().exec();
 
        const pure = (doc: Document, fields: Array<string>) => {
            Eif (fields && Array.isArray(fields)) {
                return pick(doc, fields);
            } else {
                return doc.toJSON();
            }
        }
 
        const docsPromise = query.skip(page * size).limit(size).exec();
        const result = await Promise.all([countPromise, docsPromise]);
 
        let [count, docs] = result;
        docs = docs || [];
        const list = docs.map((doc) => pure(doc, fields) as TResponse);
        return {
            list: list,
            total: count
        }
    }
 
    static mergeProfile(user?: Document) {
        if (!user) {
            return null;
        }
        const doc = user.toObject();
        const instance = Object.assign({}, doc, doc.profile);
        instance.id = doc._id;
        delete instance.profile;
        delete instance._id;
        delete instance.__v;
        delete instance.password;
        instance.createdAt = doc.createdAt;
        return instance;
    }
 
 
 
 
}