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
| const _ = require('lodash') const axios = require('axios')
class ApiError extends Error { constructor(message, code) { super(message) this.code = code this.timestamp = Date.now() }
toJSON() { return { timestamp: this.timestamp, code: this.code, message: this.message } } }
const http = axios.create({ method: 'POST', headers: { 'content-type': 'application/json;charset=utf-8' }, timeout: 10 * 60 * 1000, maxContentLength: 100 * 1024 * 1024 }) http.interceptors.response.use(function (response) { if (response.data) { if (response.data.code === 1) { return response.data.result } } return Promise.reject(response) })
const excludes = new Set([ 'host', 'connection', 'content-length', 'content-type', 'accept-encoding' ])
function headerx(headers) { return _.pickBy(headers, (value, key) => { return !excludes.has(key) }) };
function ok(result, message) { return { timestamp: Date.now(), code: 1, message: message || '请求成功', result } }
function error(e) { console.log('--------------->',e) return new ApiError(e.message || '出错了', e.code || 9) }
function transformError(e) { if (e.request && e.status && e.data) { e = e.data } if (e.timestamp && e.code && e.message) { return e } else { return error() } }
function validate(b, message) { if (!b) { throw error({ message: message || '参数错误', code: 10 }) } }
function equal(value, expected, message) { if (value != expected) { throw error({ message: message || '参数错误', code: 10 }) } }
function maxlength(value, expected, message) { if (value) { validate(value.length <= expected, message) } }
function gt(value, expected, message) { validate(value > expected, message) }
function notEmpty(value, message) { validate(value, message) }
module.exports = { http, headerx, ok, error, transformError, validator: { gt, notEmpty, equal, maxlength } }
|