Ver código fonte

service基类修改,更换参数位

lrf 2 anos atrás
pai
commit
ea3a429cb0
3 arquivos alterados com 28 adições e 5 exclusões
  1. 3 0
      src/index.ts
  2. 15 5
      src/service/BaseService.ts
  3. 10 0
      src/service/options.ts

+ 3 - 0
src/index.ts

@@ -22,3 +22,6 @@ export { DefaultErrorFilter } from './filter/default.filter';
 export { GetModel } from './util/getModel';
 /**数据库业务服务 */
 export { TransactionService } from './util/transactions';
+
+/**service工具 */
+export { pageOptions, resultOptions } from './service/options';

+ 15 - 5
src/service/BaseService.ts

@@ -6,6 +6,7 @@ import _ = require('lodash');
 import { FrameworkErrorEnum, ServiceError } from '../error/service.error';
 import { GetModel } from '../util/getModel';
 import { SearchBase } from '../../dist';
+import { pageOptions, resultOptions } from './options';
 /**
  * Service基类,实现了一些基础的crud
  */
@@ -26,9 +27,15 @@ export abstract class BaseService<T extends AnyParamConstructor<any>> {
    * @param {Boolean} populate 是否进行ref关联数据
    * @returns {Promise<object>} 返回列表
    */
-  async query(filter: SearchBase, pageOptions: object = {}, lean = true, populate = true): Promise<object> {
+  async query(filter: SearchBase, pageOptions: pageOptions = {}, resultOptions: resultOptions = { lean: true, populate: true }): Promise<object> {
     const dup = _.cloneDeep(filter.getFilter());
-    const data = await this.model.find(dup, {}, { ...pageOptions }).lean(lean);
+    const { lean, populate } = resultOptions;
+    let refs = [];
+    if (populate) refs = this.getRefs();
+    const data = await this.model
+      .find(dup, {}, { ...pageOptions })
+      .populate(refs)
+      .lean(lean)
     return data;
   }
 
@@ -49,8 +56,11 @@ export abstract class BaseService<T extends AnyParamConstructor<any>> {
    * @param {boolean} lean 是否使用JavaScript形式数据
    * @returns {object|undefined}
    */
-  async fetch(id: string, lean = true): Promise<object | undefined> {
-    const data = await this.model.findById(id).lean(lean);
+  async fetch(id: string, resultOptions: resultOptions = { lean: true, populate: true }): Promise<object | undefined> {
+    const { lean, populate } = resultOptions;
+    let refs = [];
+    if (populate) refs = this.getRefs();
+    const data = await this.model.findById(id).populate(refs).lean(lean);
     return data;
   }
 
@@ -127,7 +137,7 @@ export abstract class BaseService<T extends AnyParamConstructor<any>> {
   /**
    * 获取本服务默认表的ref关系
    */
-  async getRefs() {
+  getRefs(): Array<object> {
     const schema = _.get(this.model, 'schema.tree');
     const refs = [];
     for (const key in schema) {

+ 10 - 0
src/service/options.ts

@@ -0,0 +1,10 @@
+/**分页处理参数 */
+export interface pageOptions {
+  skip?: number;
+  limit?: number;
+}
+/**对查询结果处理参数 */
+export interface resultOptions {
+  lean?: boolean;
+  populate?: boolean;
+}