Add skeleton
This commit is contained in:
89
helpers/utils.js
Normal file
89
helpers/utils.js
Normal file
@@ -0,0 +1,89 @@
|
||||
const setResponse = async (data = [], message = "success", statusCode = 200) => {
|
||||
const response = {
|
||||
data,
|
||||
total: data.length,
|
||||
message,
|
||||
statusCode
|
||||
}
|
||||
|
||||
return response
|
||||
};
|
||||
|
||||
const setResponsePaging = async (data = [], total, limit, page, message = "success", statusCode = 200) => {
|
||||
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
const response = {
|
||||
message,
|
||||
statusCode,
|
||||
data,
|
||||
total: data.length,
|
||||
paging: {
|
||||
total,
|
||||
limit,
|
||||
page,
|
||||
page_total: totalPages
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
};
|
||||
|
||||
const setPaging = async (total, limit, page) => {
|
||||
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
const response = {
|
||||
total,
|
||||
limit,
|
||||
page,
|
||||
page_total: totalPages
|
||||
}
|
||||
|
||||
return response
|
||||
};
|
||||
|
||||
function convertId(items, id, fieldId = "id", fieldName = "name") {
|
||||
var match = ""
|
||||
items.forEach(element => {
|
||||
if (element[fieldId] == id) {
|
||||
match = element[fieldName]
|
||||
}
|
||||
});
|
||||
|
||||
return match
|
||||
}
|
||||
|
||||
function formatToYYYYMMDD(date) {
|
||||
return new Intl.DateTimeFormat('id-ID', {
|
||||
timeZone: 'Asia/Jakarta',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).format(date).split('/').reverse().join('-'); // Ubah format dari dd/mm/yyyy ke yyyy-mm-dd
|
||||
}
|
||||
|
||||
function ensureArray(param) {
|
||||
return Array.isArray(param) ? param : [param];
|
||||
}
|
||||
|
||||
function orderByClauseQuery(orderParams) {
|
||||
orderParams = ensureArray(orderParams)
|
||||
|
||||
// Transform order parameters to SQL ORDER BY syntax
|
||||
const validDirections = ['ASC', 'DESC'];
|
||||
const orderConditions = orderParams.map(param => {
|
||||
const [field, direction] = param.split(':');
|
||||
if (!validDirections.includes(direction.toUpperCase())) {
|
||||
throw new Error(`Invalid direction: ${direction}`);
|
||||
}
|
||||
return `${field} ${direction}`;
|
||||
});
|
||||
|
||||
// Gabungkan dengan koma untuk digunakan dalam query
|
||||
const orderByClause = orderConditions.join(', ');
|
||||
|
||||
return orderByClause
|
||||
}
|
||||
|
||||
module.exports = { setResponse, setResponsePaging, setPaging, convertId, formatToYYYYMMDD, orderByClauseQuery };
|
||||
Reference in New Issue
Block a user