import mongoose = require('mongoose'); import Mongo from './Mongo'; import { isEmpty } from 'lodash'; import { unix } from '../utils'; export default class Model { /** * Schema of model * * @memberof Model */ public native: mongoose.Model; /** * Create scheme * * @param {string} name * @param {object} scheme * @param {sring} altName * @param {object} plugin * @param {number} index * @returns * @memberof Model */ constructor(name: string, scheme: mongoose.Schema, altName?: string, plugin?: any, pluginOptions?: any, index?: string) { const schema = new mongoose.Schema(scheme); const connection = new Mongo().connect(); if (plugin) schema.plugin(plugin, pluginOptions); if (index) schema.index(index); try { if (altName) { this.native = connection.model(name, schema, altName); } else { this.native = connection.model(name, schema); } } catch (exception) { this.native = connection.model(name); } } /** * Return instance of model * * @param {object} data * @param {function} [callback=(err, result) => {}] * @memberof Model */ public instance(data, callback = (data: any) => {}): void { callback(new this.native(data)); } /** * Create new row * * @param {object} data * @param {function} [callback=(err, result) => {}] * @memberof Model */ public create(data, callback = (err, result = null) => {}): void { const instance: any = new this.native(data); const error = instance.validateSync(); if (error) { callback(error); } else { instance.save(callback); } } public findOneAndUpdate(condition, data: any, callback = (err, result) => {}): void { this.native.findOneAndUpdate( condition, { $set: { ...data, updatedAt: unix() } }, { new: true }, callback ); } /** * Update row by id * * @param {string} id * @param {object} data * @param {function} [callback=(err, result) => {}] * @memberof Model */ public update(id: string, data, callback = (err, result) => {}): void { this.native.findByIdAndUpdate(id, { $set: { ...data, updatedAt: unix() } }, { new: true }, callback); } /** * Destroy row by id * * @param {string} id * @param {function} [callback=(err, result) => {}] * @memberof Model */ public destroy(id: string, callback = (err, result) => {}): void { this.native.findByIdAndRemove(id, callback); } /** * Limit rows * * @param {string} count * @param {function} callback * @param {object} [condition={}] * @memberof Model */ public limit(count: string, callback = (err, result) => {}, condition = {}): void { this.native.find(condition, callback).limit(Number(count)); } public paginateSync(page, pageSize, condition) { if (!Number(page)) { return { code: 400, error: 'Parameter \'page\' should be a number.' }; } page = Number(page); pageSize = Number(pageSize) || 5; const query = this.native.find(condition).limit(pageSize).skip((page - 1) * pageSize); return { code: 200, query }; } }