Js常用方法

Posted by Xiaosa's Blog on September 26, 2021
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
const util = require('util')
const ms = require('humanize-ms')
const crypto = require('crypto')
const path = require('path')

const { URL } = require('url')

/**
 *
 * @param {Object} obj - 目标对象
 * @param {*} keys - 指定需要从目标对象里提取的 key
 */
util.pick = (obj, keys) => {
  if (!(obj && Array.isArray(keys))) return {}
  return keys.reduce((items, key) => {
    if (obj[key] !== undefined) items[key] = obj[key]
    return items
  }, {})
}

util.toString = function toString(val) {
  switch (typeof val) {
    case 'object':
      return JSON.stringify(val)
    case 'number':
      return (val += '')
    default:
      return val
  }
}

util.time = {
  ms(time) {
    switch (typeof time) {
      case 'number':
        return Math.ceil(time)
      case 'string':
        return Math.ceil(ms(time))
      default:
        return time
    }
  },

  mm(time) {
    return util.time.ms(time) / 1000
  },
}

util.detectStatus = function detectStatus(err) {
  // detect status
  let status = err.status || 200
  if (status < 200) {
    // invalid status consider as 500, like urllib will return -1 status
    status = 500
  }
  return status
}

util.detectErrorMessage = function detectErrorMessage(err, ctx) {
  // detect json parse error
  if (
    err.status === 400 &&
    err.name === 'SyntaxError' &&
    ctx.request.is('application/json', 'application/vnd.api+json', 'application/csp-report')
  ) {
    return 'Problems parsing JSON'
  }
  return err.message
}

util.jsonErrorHandle = function jsonErrorHandle(err, ctx) {
  const body = {
    code: err.code || err.type || 'unknown',
    message: err.message,
    errno: err.errno || -1,
    errors: err.errors || [],
  }

  ctx.type = 'json'
  ctx.status = err.status || 200
  ctx.body = JSON.stringify(body)
}

util.JSONparse = (str, ctx) => {
  try {
    return JSON.parse(str)
  } catch (err) {
    if (ctx) ctx.logger.warn(err)
    return {}
  }
}

util.SQLStringTemplate = function SQLStringTemplate([ sql ]) {
  return sql.replace(/[\n\s]+/g, ' ').trim()
}

util.sha1 = function sha1(data) {
  return crypto.createHash('sha1').update(data).digest('hex')
}

util.uriJoin = function uriJoin(urlPath, base) {
  const url = new URL(base)
  urlPath = urlPath[0] === '/' ? urlPath.substring(1) : urlPath
  url.pathname = path.join(url.pathname, urlPath)
  return url.toString()
}
util.signature = function name(appId, appKey, time) {
  return crypto
    .createHash('md5')
    .update(appId + appKey.toLowerCase() + time)
    .digest('hex')
}
util.uniqueTimestamp = function uniqueTimestamp() {
  const currentDate = new Date()
  const month = `${currentDate.getMonth() + 1}`.padStart(2, '0')
  const day = `${currentDate.getDate()}`.padStart(2, '0')
  const h = `${currentDate.getHours()}`.padStart(2, '0')
  const m = `${currentDate.getMinutes()}`.padStart(2, '0')
  const s = `${currentDate.getSeconds()}`.padStart(2, '0')
  return `RES_${currentDate.getFullYear()}${month}${day}_${h}${m}${s}`
}

// app_id => appId
util.sCtoCc = function sCtoCc(str) {
  return str.replace(/_\w/g, x => `${x[1].toUpperCase()}`)
}
// appId => app_id
util.cCToSc = function cCToSc(str) {
  return str.replace(/[A-Z]/g, x => `_${x.toLowerCase()}`)
}

util.objectKeyFormat = (object, caseType) => {
  let fn
  switch (caseType) {
    case 'camelCase': fn = util.sCtoCc;break;
    case 'snakeCase': fn = util.cCToSc;break;
    default:console.error('unexpected caseType');return;
  }
  const res = {}
  Object.keys(object).forEach(
    key => {
      res[fn(key)] = object[key]
    }
  )
  return res
}

module.exports = util

// ocr图片压缩处理
// ImageData 为 file.content
export const ocrImageDeal = (ImageData, width = 1280, degree = 1) => {
  return new Promise((resolve, reject) => {
    if (!ImageData) {
      reject('图片不存在')
      return
    }
      const image = new Image()
      image.onload = function() {
        const drawWidth = width
        const drawHeight = this.naturalHeight * (drawWidth / this.naturalWidth)
        const canvas = document.createElement('canvas')
        canvas.width = drawWidth
        canvas.height = drawHeight
        const ctx = canvas.getContext('2d')
        ctx.drawImage(this, 0, 0, drawWidth, drawHeight)
        const dataURL = canvas.toDataURL('image/jpeg', degree)
        resolve(dataURL)
      }
      image.src = ImageData
  })
}


深对比

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
const diff = (value1, value2, key1 = 'value1', key2 = 'value2', strict = false) => {
  if (!strict && value1 === '' || value1 === null) value1 = undefined
  if (!strict && value2 === '' || value2 === null) value2 = undefined

  if (value1 === value2) return null

  if (typeof value1 !== typeof value2)
    return { diff: `inconsistent data types! ${key1}[${typeof value1}], ${key2}[${typeof value2}]`, [key1]: value1, [key2]: value2 }

  if (!(value1 === null && value2 === null || value1 !== null && value2 !== null))
    return { diff: `inconsistent data types! ${key1}[${typeof value1}], ${key2}[${typeof value2}]`, [key1]: value1, [key2]: value2 }

  if (Array.isArray(value1) !== Array.isArray(value2))
    return { diff: `inconsistent data types! ${key1}[${Array.isArray(value1) && 'Array' || typeof value1}], ${key2}[${Array.isArray(value2) && 'Array' || typeof value2}]`, [key1]: value1, [key2]: value2 }


  if (Boolean(Array.isArray(value1) && Array.isArray(value2))
    && value1.length !== value2.length)
    return { diff: `Array length is inconsistent! value1.length[${value1.length}], value2.length[${value2.length}]`, [key1]: value1, [key2]: value2 }

  if (Array.isArray(value1)) {
    value1 = value1.sort()
    value2 = value2.sort()
    const result = {}
    for (let index = 0; index < value1.length; index++) {
      const element1 = value1[index]
      const element2 = value2[index]
      const item = diff(element1, element2, key1, key2)
      if (item) result[index] = item
    }
    return Object.keys(result).length && result || null
  }

  if (typeof value1 === 'object') {
    const keys1 = value1 ? Object.keys(value1).sort() : []
    const keys2 = value2 ? Object.keys(value2).sort() : []
    const keysDiff1 = keys1.filter(key => !keys2.includes(key))
    const keysDiff2 = keys2.filter(key => !keys1.includes(key))

    const result = {
      keysDiff: undefined
    }

    if (keysDiff1.length || keysDiff2.length) result.keysDiff = { [key1]: keysDiff1, [key2]: keysDiff2 }
    for (const key of keys1.concat(keysDiff2)) {

      // if (key.lastIndexOf("Time") != -1) return null

      const element1 = value1[key]
      const element2 = value2[key]
      const item = diff(element1, element2, key1, key2)
      if (item) result[key] = item
    }
    return Object.keys(result).length && result || null
  }

  if (value1 !== value2) return { diff: 'inconsistent value!', [key1]: value1, [key2]: value2 }

  return null
}