119 lines
2.6 KiB
JavaScript
119 lines
2.6 KiB
JavaScript
const bodyParser = require("body-parser");
|
|
const express = require("express");
|
|
const { getErrorMessage } = require("../constants/api_constans.js");
|
|
|
|
const success = (data, msg, param = null) => {
|
|
var dataJson = data;
|
|
var data = {};
|
|
if (param != null) data[param] = dataJson;
|
|
else data = dataJson;
|
|
|
|
return {
|
|
success: true,
|
|
message: msg,
|
|
data,
|
|
};
|
|
};
|
|
|
|
const succes = (res, data, msg, param) => {
|
|
var dataJson = data;
|
|
var data = {};
|
|
if (param != null) data[param] = dataJson;
|
|
else data = dataJson;
|
|
|
|
return res.status(200).json({
|
|
success: true,
|
|
message: msg,
|
|
data,
|
|
});
|
|
};
|
|
|
|
const error = (res, errorCode, code, message = null) => {
|
|
var errorMessage = getErrorMessage(errorCode);
|
|
|
|
return res.status(code).json({
|
|
success: false,
|
|
message: message ?? errorMessage,
|
|
error_code: errorCode,
|
|
data: null,
|
|
});
|
|
};
|
|
|
|
const failed = (errorCode, message = null) => {
|
|
var errorMessage = getErrorMessage(errorCode);
|
|
|
|
return {
|
|
success: false,
|
|
message: message ?? errorMessage,
|
|
error_code: errorCode,
|
|
data: null,
|
|
};
|
|
};
|
|
|
|
const pagination = (page, size) => {
|
|
let limit = null;
|
|
let offset = null;
|
|
if (page != null) {
|
|
limit = size ? +size : 5;
|
|
offset = limit ? 0 + (page - 1) * limit : null;
|
|
}
|
|
|
|
return {
|
|
limit,
|
|
offset,
|
|
};
|
|
};
|
|
|
|
const pagingData = (data) => {
|
|
const { count: totalItems, rows: items } = data;
|
|
return items;
|
|
};
|
|
|
|
const pagingInfo = (data, page, limit) => {
|
|
const { count: totalItems, rows: items } = data;
|
|
const currentPage = page ? +page : 0;
|
|
const totalPages = Math.ceil(totalItems / limit);
|
|
const pageSize = +limit;
|
|
|
|
return {
|
|
page: currentPage,
|
|
per_page: pageSize,
|
|
total: totalItems,
|
|
total_pages: totalPages,
|
|
};
|
|
};
|
|
|
|
const paginationResponse = (data, page, limit = 5, key) => {
|
|
const response = {};
|
|
|
|
if (page != null) {
|
|
const items = pagingData(data);
|
|
const paginate = pagingInfo(data, page, limit);
|
|
|
|
response[key] = items;
|
|
if (paginate != null) response["pagination"] = paginate;
|
|
} else {
|
|
const items = pagingData(data);
|
|
response[key] = items;
|
|
}
|
|
|
|
return response;
|
|
};
|
|
|
|
const json = (res, data) => {
|
|
var statusCode = data.success == true ? 200 : 500;
|
|
return res.status(statusCode).json(data);
|
|
};
|
|
|
|
module.exports = {
|
|
success,
|
|
succes,
|
|
error,
|
|
pagination,
|
|
pagingData,
|
|
pagingInfo,
|
|
paginationResponse,
|
|
failed,
|
|
json,
|
|
};
|