keycloak-demo/utils/response/index.js
2021-09-01 21:15:26 +08:00

74 lines
2.1 KiB
JavaScript

/* 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
*/
const mod = {}
module.exports = mod
mod.respDefault = (status = 200, codeMsg) => ({ status, object: codeMsg })
mod.APIError = class extends Error {
/**
* @param {string} message
* @param {respObject} resp
*/
constructor (message = '', resp) {
super(message)
this._object = resp || {}
}
get object () {
return this._object
}
}
/**
* check response object struct
* @param {respObject} v
*/
mod.checkStruct = v => {
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
}
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' },
CodeInternalError: { code: 1007, message: 'internal error' },
CodeAccountNoPermission: { code: 1008, message: 'account no permission' }
}
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),
InternalError: mod.respDefault(500, mod.codeMessage.CodeInternalError)
}