All files / tcb-admin-node/src/database query.ts

71.96% Statements 77/107
57.41% Branches 31/54
85% Functions 17/20
74.04% Lines 77/104
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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 4134x     4x 4x 4x 4x 4x                                                         4x                                                                                                                         22x 22x 22x 22x 22x 22x                   9x 9x 9x 1x                     9x     9x 2x   9x 1x   9x 1x   9x 2x     7x   9x 1x       9x 9x 8x     8x 8x       8x 8x 8x 8x                                                                                 4x                               1x 1x   1x       1x   1x                             2x   2x 2x   2x                             1x   1x 1x   1x                             1x             1x             1x                   1x 1x 1x     1x                               1x 1x 1x           1x 1x   1x                         1x             1x 1x   1x     1x                     4x 4x 1x   3x 3x 3x                                                     4x      
import { Request } from "./request";
import { OrderByDirection } from "./constant";
import { Db } from "./db";
import { Validate } from "./validate";
import { Util } from "./util";
import { Command } from "./command";
import { RegExp } from "./regexp";
import * as isRegExp from "is-regex";
 
interface getRes {
  data: any[];
  requestId: string;
  total: number;
  limit: number;
  offset: number;
}
 
interface QueryOrder {
  field?: string;
  direction?: "asc" | "desc";
}
 
interface QueryOption {
  // 查询数量
  limit?: number;
  // 偏移量
  offset?: number;
  // 指定显示或者不显示哪些字段
  projection?: Object;
}
 
/**
 * 查询模块
 *
 * @author haroldhu
 */
export class Query {
  /**
   * Db 的引用
   *
   * @internal
   */
  protected _db: Db;
 
  /**
   * Collection name
   *
   * @internal
   */
  protected _coll: string;
 
  /**
   * 过滤条件
   *
   * @internal
   */
  private _fieldFilters: Object;
 
  /**
   * 排序条件
   *
   * @internal
   */
  private _fieldOrders: QueryOrder[];
 
  /**
   * 查询条件
   *
   * @internal
   */
  private _queryOptions: QueryOption;
 
  /**
   * 请求实例
   *
   * @internal
   */
  private _request: Request;
 
  /**
   * 初始化
   *
   * @internal
   *
   * @param db            - 数据库的引用
   * @param coll          - 集合名称
   * @param fieldFilters  - 过滤条件
   * @param fieldOrders   - 排序条件
   * @param queryOptions  - 查询条件
   */
  constructor(
    db: Db,
    coll: string,
    fieldFilters?: Object,
    fieldOrders?: QueryOrder[],
    queryOptions?: QueryOption
  ) {
    this._db = db;
    this._coll = coll;
    this._fieldFilters = fieldFilters;
    this._fieldOrders = fieldOrders || [];
    this._queryOptions = queryOptions || {};
    this._request = new Request(this._db);
  }
 
  /**
   * 发起请求获取文档列表
   *
   * - 默认获取集合下全部文档数据
   * - 可以把通过 `orderBy`、`where`、`skip`、`limit`设置的数据添加请求参数上
   */
  get(): Promise<getRes> {
    let newOder = [];
    Eif (this._fieldOrders) {
      this._fieldOrders.forEach(order => {
        newOder.push(order);
      });
    }
    interface Param {
      collectionName: string;
      query?: Object;
      order?: string[];
      offset?: number;
      limit?: number;
      projection?: Object;
    }
    let param: Param = {
      collectionName: this._coll
    };
    if (this._fieldFilters) {
      param.query = this._fieldFilters;
    }
    if (newOder.length > 0) {
      param.order = newOder;
    }
    if (this._queryOptions.offset) {
      param.offset = this._queryOptions.offset;
    }
    if (this._queryOptions.limit) {
      param.limit =
        this._queryOptions.limit < 100 ? this._queryOptions.limit : 100;
    } else {
      param.limit = 100;
    }
    if (this._queryOptions.projection) {
      param.projection = this._queryOptions.projection;
    }
    // console.log("this._queryOptions", this._queryOptions);
    // console.log(param);
    return new Promise<any>(resolve => {
      this._request.send("queryDocument", param).then(res => {
        Iif (res.code) {
          resolve(res);
        } else {
          const documents = Util.formatResDocumentData(res.data.list);
          const result: any = {
            data: documents,
            requestId: res.requestId
          };
          Iif (res.TotalCount) result.total = res.TotalCount;
          Iif (res.Limit) result.limit = res.Limit;
          Iif (res.Offset) result.offset = res.Offset;
          resolve(result);
        }
      });
    });
  }
 
  /**
   * 获取总数
   */
  count() {
    interface Param {
      collectionName: string;
      query?: Object;
    }
    let param: Param = {
      collectionName: this._coll
    };
    if (this._fieldFilters) {
      param.query = this._fieldFilters;
    }
    return new Promise<any>(resolve => {
      this._request.send("countDocument", param).then(res => {
        // console.log(res);
        if (res.code) {
          resolve(res);
        } else {
          resolve({
            requestId: res.requestId,
            total: res.data.total
          });
        }
      });
    });
  }
 
  /**
   * 查询条件
   *
   * @param query
   */
  where(query: object) {
    return new Query(
      this._db,
      this._coll,
      this.convertParams(query),
      this._fieldOrders,
      this._queryOptions
    );
  }
 
  /**
   * 设置排序方式
   *
   * @param fieldPath     - 字段路径
   * @param directionStr  - 排序方式
   */
  orderBy(fieldPath: string, directionStr: OrderByDirection): Query {
    Validate.isFieldPath(fieldPath);
    Validate.isFieldOrder(directionStr);
 
    const newOrder: QueryOrder = {
      field: fieldPath,
      direction: directionStr
    };
    const combinedOrders = this._fieldOrders.concat(newOrder);
 
    return new Query(
      this._db,
      this._coll,
      this._fieldFilters,
      combinedOrders,
      this._queryOptions
    );
  }
 
  /**
   * 设置查询条数
   *
   * @param limit - 限制条数
   */
  limit(limit: number): Query {
    Validate.isInteger("limit", limit);
 
    let option = Object.assign({}, this._queryOptions);
    option.limit = limit;
 
    return new Query(
      this._db,
      this._coll,
      this._fieldFilters,
      this._fieldOrders,
      option
    );
  }
 
  /**
   * 设置偏移量
   *
   * @param offset - 偏移量
   */
  skip(offset: number): Query {
    Validate.isInteger("offset", offset);
 
    let option = Object.assign({}, this._queryOptions);
    option.offset = offset;
 
    return new Query(
      this._db,
      this._coll,
      this._fieldFilters,
      this._fieldOrders,
      option
    );
  }
 
  /**
   * 发起请求批量更新文档
   *
   * @param data 数据
   */
  update(data: Object): Promise<any> {
    Iif (!data || typeof data !== "object") {
      return Promise.resolve({
        code: "INVALID_PARAM",
        message: "参数必需是非空对象"
      });
    }
 
    Iif (data.hasOwnProperty("_id")) {
      return Promise.resolve({
        code: "INVALID_PARAM",
        message: "不能更新_id的值"
      });
    }
 
    let param = {
      collectionName: this._coll,
      query: this._fieldFilters,
      multi: true,
      merge: true,
      upsert: false,
      data: Util.encodeDocumentDataForReq(data, true)
      // data: this.convertParams(data)
    };
 
    return new Promise<any>(resolve => {
      this._request.send("updateDocument", param).then(res => {
        Iif (res.code) {
          resolve(res);
        } else {
          resolve({
            requestId: res.requestId,
            updated: res.data.updated,
            upsertId: res.data.upsert_id
          });
        }
      });
    });
  }
 
  /**
   * 指定要返回的字段
   *
   * @param projection
   */
  field(projection: Object): Query {
    for (let k in projection) {
      Eif (projection[k]) {
        projection[k] = 1;
      } else {
        projection[k] = 0;
      }
    }
 
    let option = Object.assign({}, this._queryOptions);
    option.projection = projection;
 
    return new Query(
      this._db,
      this._coll,
      this._fieldFilters,
      this._fieldOrders,
      option
    );
  }
 
  /**
   * 条件删除文档
   */
  remove() {
    const param = {
      collectionName: this._coll,
      query: this._fieldFilters,
      multi: true
    };
    // console.log("this._queryOptions", this._queryOptions);
    // console.log(param);
    return new Promise<any>(resolve => {
      this._request.send("deleteDocument", param).then(res => {
        // console.log(res)
        Iif (res.code) {
          resolve(res);
        } else {
          resolve({
            requestId: res.requestId,
            deleted: res.data.deleted
          });
        }
      });
    });
  }
 
  convertParams(query: object) {
    // console.log(JSON.stringify(query));
    let queryParam = {};
    if (query instanceof Command) {
      queryParam = query.parse();
    } else {
      for (let key in query) {
        Eif (query[key] instanceof Command || query[key] instanceof RegExp) {
          queryParam = Object.assign({}, queryParam, query[key].parse(key));
        } else if (isRegExp(query[key])) {
          queryParam = {
            [key]: {
              $regex: query[key].source,
              $options: query[key].flags
            }
          };
        } else if (typeof query[key] === "object") {
          let command = new Command();
          let tmp = {};
          command.concatKeys({ [key]: query[key] }, "", tmp);
          let keys = Object.keys(tmp)[0];
          let value = tmp[keys];
          if (value instanceof Command) {
            value = value.parse(keys);
          } else {
            value = { [keys]: value };
          }
 
          queryParam = Object.assign({}, queryParam, value);
        } else {
          queryParam = Object.assign({}, queryParam, { [key]: query[key] });
        }
      }
    }
    // console.log(JSON.stringify(queryParam));
    return queryParam;
  }
}