class HttpResponse { constructor (httpStatus, idString, message, data = {}) { this.httpStatus = httpStatus this.idString = idString this.message = message this.data = data } send (res) { const response = {} if (this.httpStatus >= 400) response.error = this.idString else if (this.idString) response.action = this.idString if (this.message) response.message = this.message res.status(this.httpStatus).send({ ...this.data, ...response }) } } // ############################################################################ // ############################## SUCCESS ##################################### // General HttpResponse.success = (action, type, id) => new HttpResponse(200, action.toUpperCase(), `Successfully ${action} ${type} ${id}.`, { id }) HttpResponse.successBatch = (action, type, count) => { if (Array.isArray(type)) type = type[count === 1 ? 0 : 1] else if (count !== 1) type += 's' return new HttpResponse(200, action.toUpperCase() + '_MULTIPLE', `Successfully ${action} ${count} ${type}.`, { count }) } // ############################################################################ // ############################## WARNING ##################################### HttpResponse.warningBatch = (action, type, successfull, count, errors) => { const failed = count - successfull let tmpType = type if (failed > 1) tmpType += 's' if (Array.isArray(type)) type = type[successfull === 1 ? 0 : 1] else if (successfull !== 1) type += 's' return new HttpResponse(200, action.toUpperCase() + '_MULTIPLE', `Warning: ${action} ${successfull}/${count} ${type}. ${failed} ${tmpType} failed. ${errors.length} external errors occurred.`, { successfull, count, errors }) } // ############################################################################ // ############################### ERROR ###################################### // General HttpResponse.notFound = (id) => new HttpResponse(404, 'NOT_FOUND', 'ID ' + id + ' does not exist.') HttpResponse.invalidId = (zeroAllowed) => new HttpResponse(400, 'INVALID_ID', 'ID has to be an integer' + (zeroAllowed ? '' : ' greater than 0') + '.') HttpResponse.invalidBodyValue = (key, rule) => new HttpResponse(400, 'BAD_REQUEST', 'JSON body value for key "' + key + '" has to be ' + rule + '.') HttpResponse.noPermission = (id, permission) => new HttpResponse(403, 'NO_PERMISSION', 'Missing permission ' + permission + ' for object ' + id + '.') // Authentication HttpResponse.invalidToken = () => new HttpResponse(401, 'INVALID_TOKEN', 'The provided token is invalid.') // ############################################################################ // ############################################################################ module.exports = HttpResponse