2021-08-31 10:24:42 +00:00
|
|
|
/* eslint-disable no-underscore-dangle */
|
|
|
|
/**
|
|
|
|
* @exports
|
|
|
|
* @typedef {Object} codeMessage
|
|
|
|
* @prop {number} code
|
|
|
|
* @prop {string} message
|
|
|
|
*/
|
|
|
|
/**
|
|
|
|
* @exports
|
|
|
|
* @typedef {Object} respObject
|
|
|
|
* @prop {number} status
|
|
|
|
* @prop {codeMessage} object
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* create respobject
|
|
|
|
* @param {number} status
|
|
|
|
* @param {codeMessage} codeMsg
|
|
|
|
*/
|
|
|
|
|
2021-09-01 12:46:41 +00:00
|
|
|
const mod = {}
|
|
|
|
module.exports = mod
|
2021-08-31 10:24:42 +00:00
|
|
|
|
2021-09-01 12:46:41 +00:00
|
|
|
mod.respDefault = (status = 200, codeMsg) => ({ status, object: codeMsg })
|
2021-08-31 10:24:42 +00:00
|
|
|
|
|
|
|
mod.APIError = class extends Error {
|
|
|
|
/**
|
|
|
|
* @param {string} message
|
|
|
|
* @param {respObject} resp
|
|
|
|
*/
|
2021-09-01 12:46:41 +00:00
|
|
|
constructor (message = '', resp) {
|
|
|
|
super(message)
|
|
|
|
this._object = resp || {}
|
2021-08-31 10:24:42 +00:00
|
|
|
}
|
|
|
|
|
2021-09-01 12:46:41 +00:00
|
|
|
get object () {
|
|
|
|
return this._object
|
2021-08-31 10:24:42 +00:00
|
|
|
}
|
2021-09-01 12:46:41 +00:00
|
|
|
}
|
2021-08-31 10:24:42 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* check response object struct
|
|
|
|
* @param {respObject} v
|
|
|
|
*/
|
|
|
|
mod.checkStruct = v => {
|
2021-09-01 12:46:41 +00:00
|
|
|
if (typeof v !== 'object' || v === null || v === undefined) return false
|
|
|
|
if (!('status' in v) || !('object' in v)) return false
|
|
|
|
if (typeof v.object !== 'object' || !('code' in v.object) || !('message' in v.object)) return false
|
|
|
|
return true
|
|
|
|
}
|
2021-08-31 10:24:42 +00:00
|
|
|
|
|
|
|
mod.codeMessage = {
|
|
|
|
CodeSuccess: { code: 1000, message: 'success' },
|
|
|
|
CodeCreated: { code: 1001, message: 'created' },
|
|
|
|
CodeAccepted: { code: 1002, message: 'accepted' },
|
|
|
|
CodeDataFormat: { code: 1003, message: 'data format error' },
|
|
|
|
CodeUnauthorized: { code: 1004, message: 'unauthorized' },
|
|
|
|
CodeForbidden: { code: 1005, message: 'forbidden' },
|
|
|
|
CodeNotFound: { code: 1006, message: 'not found' },
|
2021-09-01 12:46:41 +00:00
|
|
|
CodeInternalError: { code: 1007, message: 'internal error' }
|
|
|
|
}
|
2021-08-31 10:24:42 +00:00
|
|
|
|
|
|
|
mod.resp = {
|
|
|
|
Success: mod.respDefault(200, mod.codeMessage.CodeSuccess),
|
|
|
|
Created: mod.respDefault(201, mod.codeMessage.CodeCreated),
|
|
|
|
Accepted: mod.respDefault(202, mod.codeMessage.CodeAccepted),
|
|
|
|
DataFormat: mod.respDefault(400, mod.codeMessage.CodeDataFormat),
|
|
|
|
Unauthorized: mod.respDefault(401, mod.codeMessage.CodeUnauthorized),
|
|
|
|
Forbidden: mod.respDefault(403, mod.codeMessage.CodeForbidden),
|
|
|
|
NotFound: mod.respDefault(404, mod.codeMessage.CodeNotFound),
|
2021-09-01 12:46:41 +00:00
|
|
|
InternalError: mod.respDefault(500, mod.codeMessage.CodeInternalError)
|
|
|
|
}
|