common-util.ts

import { Injectable } from '@nestjs/common';
import * as moment from 'moment';
import * as fs from 'fs';
import xlsx from 'node-xlsx';
import * as uuid from 'uuid';
import * as pinyin from 'pinyin';
import { RpcException } from '@nestjs/microservices';
import * as crypto from 'crypto';

@Injectable()
export class ToStr {

  /**
   * 去除字符串中的指定字符
   * @param str   指定字符串
   * @param split 指定字符
   * @param join  填充字符
   */
  public static splitJoinStr(str: string, split: string, join?: string): string {
    join = join || '';
    return str.split(split).join(join);
  }

  /** 对象深拷贝 */
  public static clone<T>(origin: T): T {
    return JSON.parse(JSON.stringify(origin));
  }

  /**
   * 格式化数字 补零
   * @param num
   * @param length
   */
  public static numberFormat(num, length) {
    return (Array(length).join('0') + num).slice(-length);
  }

  /**
   * 解决js中数字运算丢失精度问题
   * @param num   数字
   * @param digit 精度
   * @return 计算结果
   */
  public static computationalAccuracy(num, digit: number): number {
    const m = Math.pow(10, digit);
    return Math.round(num * m) / m;
  }

  /** md5加密 */
  public static md5(data) {
    const hash = crypto.createHash('md5');
    return hash.update(data).digest('hex');
  }

  // /** 检查是否数字 */
  // public static checkInputNumber(drugIds) {
  //   const re = /^[0-9]+$/;
  //   for (const key in drugIds) {
  //     if (!re.test(drugIds[key].amount)) {
  //       return false;
  //     }
  //   }
  //   return drugIds;
  // }

  /** date to str 20181125 */
  public static getDateForNumber(date?: Date): string {
    return moment(date || new Date()).format('YYYYMMDDHHmmssSSS');
  }

  /** 获得当前日期:YYYY-MM-DD */
  public static dateOfToday(): string {
    return moment(new Date()).format('YYYY-MM-DD');
  }

  /** 下载文件 @param:名称类型,@param:文件格式,@param:buffer,@param:Response */
  public static downloadXLSX(
    typeName: string,
    fileType: string,
    sheet: any,
    res: any,
  ) {
    const buffer = xlsx.build([{ data: sheet }]);
    const fileName = `${typeName}${this.getDateForNumber()}${fileType}`;
    // 生成文件
    fs.writeFile(`./${fileName}`, buffer, e => {
      if (e) {
        return console.log(e);
      }
      // 下载
      res.download(`./${fileName}`, fileName, e1 => {
        if (e1) {
          return console.log(e1);
        }
        console.log(`下载 ${fileName} 成功`);
        // 最后记得删除文件
        fs.unlink(`./${fileName}`, e2 => {
          if (e2) {
            return console.log(e);
          }
          console.log(`删除 ${fileName} 成功`);
        });
      });
    });
  }

  /** UUID:uuid */
  public static UUID(): string {
    return uuid.v1().replace(/-/g, '');
  }

  /** is empty string */
  public static isEmptyString(opts): boolean {
    if (!opts) return true;
    if (typeof opts === 'string') {
      return opts === '';
    }
  }

  /** is empty Object */
  public static isEmptyObject(opts): boolean {
    if (!opts) return true;
    if (typeof opts.rows === 'object' && !(opts.rows instanceof Array)) {
      let hasProp = false;
      for (const prop in opts.rows) {
        hasProp = true;
        break;
      }
      if (hasProp) {
        opts.rows = [opts.rows];
      } else {
        return false;
      }
    }
  }

  /** 获得当前年月日流水格式 */
  public static streamDateOfNow(date?: Date): string {
    return moment(date || new Date()).format('YYYYMMDD');
  }

  /** 获得当前具体时间流水格式 */
  public static streamTimeOfNow(date?: Date): string {
    return moment(date || new Date()).format('YYYYMMDDHHmmssSSS');
  }

  /** 获得具体时间:YYYY-MM-DD HH:mm:ss */
  public static datetimeOfNow(date?: Date): string {
    return moment(date || new Date()).format('YYYY-MM-DD HH:mm:ss');
  }

  /** 比较时间,前者大返回true */
  public static compTime(datetime1: string, datetime2?: string): boolean {
    let date1, date2;
    try {
      date1 = new Date(datetime1);
    } catch (e) {
      date1 = new Date();
    }
    try {
      date2 = !datetime2 ? new Date() : new Date(datetime2);
    } catch (e) {
      date2 = new Date();
    }
    return date1 > date2;
  }

  /** 根据时间差得到具体时间:YYYY-MM-DD HH:mm:ss */
  public static datetimeByTimeDifference(timeDifference: {
    year?: number;
    month?: number;
    date?: number;
    hours?: number;
    minutes?: number;
    seconds?: number;
    milliseconds?: number;
    beforeTime?: Date | string;
  }): string {
    let laterTime: Date;
    try {
      laterTime = !timeDifference.beforeTime
        ? new Date()
        : typeof timeDifference.beforeTime === 'string'
        ? new Date(timeDifference.beforeTime)
        : timeDifference.beforeTime;
    } catch (e) {
      console.log(`日期格式化错误,${e}`);
      laterTime = new Date();
    }
    if (!this.isEmptyValue(timeDifference.year)) {
      laterTime.setFullYear(laterTime.getFullYear() + timeDifference.year);
    }
    if (!this.isEmptyValue(timeDifference.month)) {
      laterTime.setMonth(laterTime.getMonth() + timeDifference.month);
    }
    if (!this.isEmptyValue(timeDifference.date)) {
      laterTime.setDate(laterTime.getDate() + timeDifference.date);
    }
    if (!this.isEmptyValue(timeDifference.hours)) {
      laterTime.setHours(laterTime.getHours() + timeDifference.hours);
    }
    if (!this.isEmptyValue(timeDifference.minutes)) {
      laterTime.setMinutes(laterTime.getMinutes() + timeDifference.minutes);
    }
    if (!this.isEmptyValue(timeDifference.seconds)) {
      laterTime.setSeconds(laterTime.getSeconds() + timeDifference.seconds);
    }
    if (!this.isEmptyValue(timeDifference.milliseconds)) {
      laterTime.setMilliseconds(
        laterTime.getMilliseconds() + timeDifference.milliseconds,
      );
    }
    return moment(laterTime).format('YYYY-MM-DD HH:mm:ss');
  }

  /**
   * SQL:在列中查找
   */
  public static findInSetForSQL(
    fieldList: string[],
    fieldName: string,
    andOr: 'and' | 'or',
    keyName: string,
  ): { sql: string; condition: [] } {
    let sql = `(`;
    const condition: any = {};
    for (const key in fieldList) {
      if (+key !== 0) {
        sql += ` ${andOr === 'and' ? 'AND' : 'OR'} `;
      }
      if (fieldList[key].toUpperCase() === 'NULL') {
        sql += `${fieldName} IS NULL`;
      } else if (fieldList[key] === '') {
        sql += `${fieldName} = ''`;
      } else {
        sql += `FIND_IN_SET(:${keyName}${key},${fieldName})`;
      }
      condition[`${keyName}${key}`] = fieldList[key];
    }
    sql += `)`;
    return { sql, condition };
  }

  /**
   * 多个查询
   */
  public static findMoreForSQL(data: {
    valueList: string[];
    fieldName: string;
    andOr: 'and' | 'or';
    like?: boolean;
    unique?: number;
  }): { sql: string; condition: [] } {
    let sql = `(`;
    const condition: any = {};
    for (const key in data.valueList) {
      // 生成一个keyName
      const keyName = `${data.fieldName}${key}${
        !this.isEmptyValue(data.unique) ? data.unique : ''
      }`;
      if (+key === 0) {
        sql += `${data.fieldName} ${
          data.like === true ? 'like' : '='
        } :${keyName}`;
      } else {
        sql += ` ${data.andOr === 'and' ? 'AND' : 'OR'} ${data.fieldName} ${
          data.like === true ? 'like' : '='
        } :${keyName}`;
      }
      condition[keyName] =
        data.like === true ? `%${data.valueList[key]}%` : data.valueList[key];
    }
    sql += `)`;
    return { sql, condition };
  }

  /**
   * 对象拷贝
   */
  public static copyProperties(requestData: {
    oldObj: object;
    returnObj: any;
    copyFieldNameArray?: string[];
    passFieldNameArray?: string[];
  }): any {
    try {
      if (
        requestData.copyFieldNameArray === undefined ||
        requestData.copyFieldNameArray.length === 0
      ) {
        for (const key in requestData.oldObj) {
          // 判断是否有要跳过的参数
          if (
            requestData.passFieldNameArray === undefined ||
            !requestData.passFieldNameArray.includes(key)
          ) {
            requestData.returnObj[key] = this.copyField(
              requestData.oldObj[key],
            );
          }
        }
      } else {
        for (const key in requestData.copyFieldNameArray) {
          const fieldName: string = requestData.copyFieldNameArray[key];
          if (!this.isEmptyValue(requestData.oldObj[fieldName])) {
            requestData.returnObj[fieldName] = this.copyField(
              requestData.oldObj[fieldName],
            );
          }
        }
      }
    } catch (e) {
      console.log(e);
      this.throwExceptionOfRpc(500, e);
    }
    return requestData.returnObj;
  }

  /** 深拷贝字段 */
  private static copyField(fieldValue: any): any {
    if (typeof fieldValue === 'object') {
      const tmp = JSON.stringify(fieldValue);
      return JSON.parse(tmp);
    }
    return fieldValue;
  }

  /** 获取汉语拼音首字母,https://www.npmjs.com/package/pinyin */
  public static getFirstWordByChinese(word: string): string {
    let firstWord = '';
    try {
      const alias = pinyin(word, {
        // 首字母风格,只返回拼音的首字母部分
        style: pinyin.STYLE_FIRST_LETTER,
      });
      for (const key in alias) {
        firstWord +=
          alias[key] && alias[key].length > 0
            ? alias[key][0].substring(0, 1)
            : '';
      }
    } catch (e) {
      console.log(`获取首字母失败,${e}`);
    }
    return firstWord.toUpperCase();
  }

  /** 检查布尔类型数据是否错误或空 */
  public static isCheckBooleanEmpty(value: string): boolean {
    return (
      !this.isEmptyValue(value) &&
      (value.toString() === '0' || value.toString() === '1')
    );
  }

  /** 检查布尔类型数据是否错误 */
  public static isCheckBooleanValue(validate: {}, failedMsg: string) {
    for (const fieldName in validate) {
      if (+validate[fieldName] !== 1 && +validate[fieldName] !== 0) {
        this.throwExceptionOfRpc(
          500,
          `${failedMsg}${fieldName}字段的值${validate[fieldName]}不正确`,
        );
      }
    }
  }

  /** 检查布尔类型数据是否为空 */
  public static isEmptyBooleanValue(value: string) {
    return (
      this.isEmptyValue(value) ||
      !(value.toString() === '0' || value.toString() === '1')
    );
  }

  /** 统一抛出异常 */
  public static throwExceptionOfRpc(code: number, message: any): never {
    throw new RpcException({ code, message });
  }

  /** 对象比对,返回数据不一样的字段名称,略过新对象是undefined的字段 */
  public static diffFieldList(
    obj1: any,
    obj2: any,
    passFieldList?: string[],
  ): string[] {
    const diffFieldList: string[] = [];
    for (const key in obj2) {
      if (passFieldList !== undefined && passFieldList.indexOf(key) !== -1) {
        continue;
      }
      if (obj2[key] !== undefined && obj2[key] !== obj1[key]) {
        diffFieldList.push(key);
      }
    }
    return diffFieldList;
  }

  /** 驼峰转下划线 */
  public static toHump(str: string): string {
    return str.replace(/([A-Z])/g, '_$1').toLowerCase();
  }

  /** 匹配字符串 */
  public static equals(
    targetStr: string,
    equalsStrList: string[],
    failedMsg: string,
  ) {
    let result = false;
    for (const key in equalsStrList) {
      const equalsStr = equalsStrList[key];
      if (targetStr === equalsStr) {
        result = true;
        break;
      }
    }
    if (!result) {
      this.throwExceptionOfRpc(500, failedMsg);
    }
  }

  /**
   * 匹配YYYY-MM
   * @param param
   */
  public static isYeahMonth(param: string): boolean {
    return /^\d{4}-((0([1-9]))|(1(0|1|2)))$/.test(param);
  }

  /**
   * 匹配YYYY-mm-dd
   * @param param
   */
  public static isDate(param: string): boolean {
    return /(\d{4}-(((0(1|3|5|7|8))|(1(0|2)))(-((0[1-9])|([1-2][0-9])|(3[0-1])))?)|(((0(2|4|6|9))|(11))(-((0[1-9])|([1-2][0-9])|(30)))?)|((02)(-((0[1-9])|(1[0-9])|(2[0-8])))?))|(((([0-9]{2})((0[48])|([2468][048])|([13579][26]))|(((0[48])|([2468][048])|([3579][26]))00)))-02-29)/.test(
      param,
    );
  }

  /** date to str */
  public static getDateStr(date?: Date): string {
    return moment(date || new Date()).format('llll');
  }

  /** current_time */
  public static getCurrentTimestamp(date?): number {
    const time = (date ? new Date(date) : new Date()).getTime();
    return `${time}`.length > 10 ? +`${time}`.substr(0, 10) : time;
  }

  /** current_time */
  public static getCurrentTimes(date?): number {
    return (date ? new Date(date) : new Date()).getTime();
  }

  /** get day startTimes */
  public static getDateStartTimes(date?): number {
    date = date ? new Date(date) : new Date();
    date.setHours(0);
    date.setMinutes(0);
    date.setSeconds(0);
    date.setMilliseconds(0);
    return date.getTime();
  }

  /** get day endTimes */
  public static getDateEndTimes(date?): number {
    date = date ? new Date(date) : new Date();
    date.setHours(23);
    date.setMinutes(59);
    date.setSeconds(59);
    date.setMilliseconds(999);
    return date.getTime();
  }

  /**
   * 对请求字符串进行拼接
   * @param parm
   */
  public static getSign(param: object) {
    const keys = [];
    for (const i in param) {
      if (param[i] !== undefined && param[i] !== '') {
        keys.push(i);
      }
    }
    // 对参数键进行ASCII 码从小到大排序
    keys.sort();
    let sign = '';
    keys.forEach((value, index) => {
      sign += value;
      sign += '=';
      sign += param[value];
      sign += '&';
    });
    return sign.substring(0, sign.length - 1);
  }

  /**
   * 获取指定字符在当前字符串中出现的所有索引
   * @param str1 目标字符串
   * @param str2 指定字符(比str1短)
   */
  public static getAllIndex(str1: string, str2: string) {
    const arrLen = str1.length > str2.length ? str1.length % str2.length : 0;
    const indexList = [];
    for (let i = 0; i++; i < arrLen) {
      const index = str1.indexOf(str2);
      if (index !== -1) {
        str1 = str1.substring(index + str2.length);
        indexList.push(
          (indexList.length > 0 ? indexList[indexList.length - 1] : 0) + index,
        );
      }
    }
    return indexList;
  }

  /** 生成随机字符串 (5K8264ILTKCH16CQ2502SI8ZNMTM67VS) */
  genRandomString(len): string {
    const text = 'abcdefghijklmnopqrstuvwxyz0123456789';
    const rdmIndex = text => (Math.random() * text.length) | 0;
    let rdmString = '';
    for (; rdmString.length < len; rdmString += text.charAt(rdmIndex(text)));
    return rdmString;
  }

  /**
   * 20191012111215 ---> 2019-10-12 11-12-15
   * @param date
   */
  getStringToDte(date: string): Date {
    const timeStr =
      date.substring(0, 4) +
      '-' +
      date.substring(4, 6) +
      '-' +
      date.substring(6, 8) +
      ' ' +
      date.substring(8, 10) +
      ':' +
      date.substring(10, 12) +
      ':' +
      date.substring(12, 14);
    const nyrArr = timeStr.split(' ')[0].split('-');
    const sfmArr = timeStr.split(' ')[1].split(':');
    const resDate = new Date(
      +nyrArr[0],
      +nyrArr[1] - 1,
      +nyrArr[2],
      +sfmArr[0],
      +sfmArr[1],
      0,
      0,
    );
    return resDate;
  }

  /** date to str 20181125 */
  getDateForNumber(date?: Date): string {
    return moment(date || new Date()).format('YYYYMMDDHHmmssSSS');
  }

  /** 下载文件 @param:名称类型,@param:文件格式,@param:buffer,@param:Response */
  async download(typeName: string, fileType: string, sheet: any, res: any) {
    const buffer = await xlsx.build([{ data: sheet }]);
    const fileName = `${typeName}${this.getDateForNumber()}${fileType}`;
    // 生成文件
    fs.writeFile(`./${fileName}`, buffer, e => {
      if (!e) {
        res.download(`./${fileName}`, fileName, e1 => {
          if (!e1) {
            console.log(`download ${fileName} successful`);
            fs.unlink(`./${fileName}`, e => {
              if (!e) {
                console.log(`deleted ${fileName} successful`);
              } else {
                return console.log(e);
              }
            });
          } else {
            return console.log(e1);
          }
        });
      } else {
        return console.log(e);
      }
      // 下载
    });
  }

  /** 判断值是否为空 */
  public static isEmptyValue(opts, trim?: boolean): boolean {
    if (
      (opts === undefined || opts === 'undefined' || opts === undefined) &&
      typeof opts !== 'number'
    ) {
      return true;
    }
    return (trim ? `${opts}`.trim() : `${opts}`) === '';
  }

  /** 得到昨天的时间 */
  getYesterdaysTime(): string {
    const day1 = new Date();
    day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000);
    return moment(day1).format('YYYYMMDD');
  }

  /** 得到昨天的时间 YYYY-MM-DD */
  getYesterdaysTimeYMD(): string {
    const day1 = new Date();
    day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000);
    return moment(day1).format('YYYY-MM-DD');
  }

  /** 得到今天时间 YYYY-MM-DD */
  public static getDateYMD(date?: Date): string {
    return moment(date || new Date()).format('YYYY-MM-DD');
  }

  public static prefixInteger(num: number, length: number) {
    return (Array(length).join('0') + num).slice(-length);
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值