89 lines
2.7 KiB
JavaScript
89 lines
2.7 KiB
JavaScript
export const apiUrl = 'https://bot.trj.tw'
|
|
|
|
export const padleft = (str, len, pad = '0') => {
|
|
if (typeof str !== 'string') str = str.toString()
|
|
if (str.length < len) return padleft(`${pad}${str}`, len, pad)
|
|
return str
|
|
}
|
|
|
|
/**
|
|
* check is number
|
|
* @param {any} v input value
|
|
* @return {boolean}
|
|
*/
|
|
export const isNumber = (v) => {
|
|
if (!isFinite(v) || v === true || v === false) return false
|
|
return true
|
|
}
|
|
|
|
/**
|
|
* src value to int
|
|
* @param {object} v src value
|
|
* @param {number} defVal default value
|
|
* @param {number} min range min
|
|
* @param {number} max range max
|
|
*/
|
|
export const toInt = (v, defVal = 0, min = null, max = null) => {
|
|
if (!isNumber(defVal)) defVal = 0
|
|
if (typeof defVal === 'string') defVal = parseInt(defVal)
|
|
min = !isNumber(min) ? null : (typeof min === 'string' ? parseInt(min) : min)
|
|
max = !isNumber(max) ? null : (typeof max === 'string' ? parseInt(max) : max)
|
|
if (!isNumber(v)) return defVal
|
|
if (typeof v === 'string') v = parseInt(v)
|
|
if (min !== null && v < min) v = min
|
|
if (max !== null && v > max) v = max
|
|
return v
|
|
}
|
|
/**
|
|
* check Object
|
|
* @param {string} key key name
|
|
* @param {string} type type name
|
|
* @param {boolean} empty can empty
|
|
* @param {number} max max value
|
|
*/
|
|
export const chkObject = function (key = '', type = '', empty = false, max = null) {
|
|
const uuidChk = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
|
if (!(key in this.body)) return false
|
|
|
|
if (isFinite(empty) && (empty !== false && empty !== true)) {
|
|
max = toInt(empty, 0)
|
|
empty = false
|
|
}
|
|
|
|
switch (type) {
|
|
case 'string':
|
|
if (typeof this.body[key] !== 'string' || (!empty && !this.body[key])) return false
|
|
if (max !== null && this.body[key].length > max) return false
|
|
break
|
|
case 'number':
|
|
if (!isNumber(this.body[key])) return false
|
|
if (max !== null && this.body[key] > max) return false
|
|
break
|
|
case 'boolean':
|
|
if (typeof this.body[key] !== 'boolean') return false
|
|
break
|
|
case 'array':
|
|
if (!Array.isArray(this.body[key]) || (!empty && this.body[key].length === 0)) return false
|
|
if (max !== null && this.body[key].length > max) return false
|
|
break
|
|
case 'uuid':
|
|
if (typeof this.body[key] !== 'string') return false
|
|
if (!empty && this.body[key] === '') return false
|
|
if (!empty && !uuidChk.test(this.body[key])) return false
|
|
break
|
|
case 'object':
|
|
if (typeof this.body[key] !== 'object' || this.body[key] === null || this.body[key] === undefined) return false
|
|
try {
|
|
let str = JSON.stringify(this.body[key])
|
|
JSON.parse(str)
|
|
} catch (err) {
|
|
return false
|
|
}
|
|
break
|
|
default:
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|