43 lines
992 B
JavaScript
43 lines
992 B
JavaScript
const crypto = require('crypto')
|
|||
|
|
|
||
|
|
class HttpError extends Error {
|
||
|
|
constructor(status, message) {
|
||
|
|
super(message)
|
||
|
|
this.status = status
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function uid(prefix) {
|
||
|
|
return `${prefix}${Date.now().toString(36)}${crypto.randomBytes(2).toString('hex')}`
|
||
|
|
}
|
||
|
|
|
||
|
|
function token() {
|
||
|
|
return crypto.randomBytes(24).toString('hex')
|
||
|
|
}
|
||
|
|
|
||
|
|
function ok(res, data) {
|
||
|
|
res.json({ ok: true, data })
|
||
|
|
}
|
||
|
|
|
||
|
|
function fail(res, status, message) {
|
||
|
|
res.status(status).json({ ok: false, message })
|
||
|
|
}
|
||
|
|
|
||
|
|
// Express 4 does not forward rejected promises to the error handler.
|
||
|
|
function wrap(handler) {
|
||
|
|
return (req, res, next) => Promise.resolve(handler(req, res, next)).catch(next)
|
||
|
|
}
|
||
|
|
|
||
|
|
function str(value, max) {
|
||
|
|
const text = value == null ? '' : String(value).trim()
|
||
|
|
return max ? text.slice(0, max) : text
|
||
|
|
}
|
||
|
|
|
||
|
|
function has(body, key) {
|
||
|
|
return Object.prototype.hasOwnProperty.call(body || {}, key)
|
||
|
|
}
|
||
|
|
|
||
|
|
const PHONE_RE = /^1\d{10}$/
|
||
|
|
|
||
|
|
module.exports = { HttpError, uid, token, ok, fail, wrap, str, has, PHONE_RE }
|