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
})
}
|