helper.js 2.71 KB
/*
 * @Author: limin
 * @Date: 2019-11-21 11:19:43
 * @Last Modified by: limin
 * @Last Modified time: 2020-01-08 13:51:53
 */

const moment = require("moment");
const constant = require("../common/constant");

exports.moment = moment;
/*
 * string.replace_all()---字符替换所有指定字符
 * @parameter: from--原文本要替换值
 * @parameter: to--将要替换值
 */
String.prototype.replace_all = function (from, to) {
  var regExp = new RegExp(from, "g");
  return this.replace(regExp, to);
}
// exports.relativeTime = time => moment(new Date(time * 1000)).fromNow();
exports.date = (n, f = "YYYY-MM-DD") => moment().add(n, "days").format(f);

exports.format_date = (date, f = "YYYY-MM-DD") =>moment(date+'').format(f);
/**
 * 结束日期格式化函数
 */
exports.format_end_date = end => `${end} 23:59:59`;
/**
 * 字符串转json 如果是json字符串 返回json对象 如果不是JSON字符串 返回原始字符串
 */
exports.json_parser = str => {
  var res;
  try {
    res = JSON.parse(str);
  } catch (error) {
    res = str;
  }
  return res;
};
/**
 * json对象转字符串
 */
exports.json_stringify = obj => {
  var res;
  if (typeof obj === "string") {
    return obj;
  }
  try {
    res = JSON.stringify(obj);
  } catch (error) {
    res = obj;
  }
  return res;
};
/**
 *
 */
exports.percent = (num, total, fixed = 2) =>
   (Math.round(num / total * 10000) / 100.00 + "%");
  // (~~((~~num / ~~total) * 100).toFixed(fixed)) + "%";

/**
 * 简单封装 sequelize 查询参数
 */
// exports.seq_option = function({
//   pid,
//   cid,
//   n,
//   limit,
//   order,
//   day,
//   beginDate,
//   endDate
// }) {
//   let where = {};
//   const { between } = this.ctx.app.Sequelize.Op;
//   if (cid) {
//     where.city_code = cid;
//   } else if (pid) {
//     where.prov_code = pid;
//   }
//   if (day) {
//     //如果有具体天数 就直接查询具体一天的数据(优先具体哪一天)
//     where.day = day;
//   } else if (n) {
//     // 查询近N天的数据  不包括今天
//     where.day = {
//       [between]: [this.date(n), this.format_end_date(this.date(-1))]
//     };
//   } else if (n === 0) {
//     // 查询
//     where.day = {
//       [between]: [this.date(0), this.format_end_date(this.date(0))]
//     };
//   } else if (beginDate) {
//     if (!endDate) {
//       endDate = beginDate;
//     }
//     if (!endDate.includes(":")) {
//       endDate = this.format_end_date(endDate);
//     }
//     where.day = {
//       [between]: [beginDate, endDate]
//     };
//   }
//   const option = {
//     where,
//     raw: true
//   };
//   if (limit) {
//     option.limit = +limit;
//   }
//   if (order) {
//     option.order = order;
//   }
//   return option;
// };
exports.constant = constant;