54 lines
1.6 KiB
JavaScript
54 lines
1.6 KiB
JavaScript
/**
|
|
* Check if an object is not empty.
|
|
* @param {Object} obj - The object to check.
|
|
* @returns {boolean} - Returns true if the object is not empty, false otherwise.
|
|
*/
|
|
export const isObjectNotEmpty = (obj) => {
|
|
if (!obj) {
|
|
return false
|
|
}
|
|
return Object.keys(obj).length > 0
|
|
}
|
|
|
|
/**
|
|
* ex) const params = {page:10, searchDvsnCd: 20}
|
|
* @param {*} params
|
|
* @returns page=10&searchDvsnCd=20
|
|
*/
|
|
export const queryStringFormatter = (params = {}) => {
|
|
const queries = []
|
|
Object.keys(params).forEach((parameterKey) => {
|
|
const parameterValue = params[parameterKey]
|
|
|
|
if (parameterValue === undefined || parameterValue === null) {
|
|
return
|
|
}
|
|
|
|
// string trim
|
|
if (typeof parameterValue === 'string' && !parameterValue.trim()) {
|
|
return
|
|
}
|
|
|
|
// array to query string
|
|
if (Array.isArray(parameterValue)) {
|
|
// primitive type
|
|
if (parameterValue.every((v) => typeof v === 'number' || typeof v === 'string')) {
|
|
queries.push(`${encodeURIComponent(parameterKey)}=${parameterValue.map((v) => encodeURIComponent(v)).join(',')}`)
|
|
return
|
|
}
|
|
// reference type
|
|
if (parameterValue.every((v) => typeof v === 'object' && v !== null)) {
|
|
parameterValue.map((pv, i) => {
|
|
return Object.keys(pv).forEach((valueKey) => {
|
|
queries.push(`${encodeURIComponent(`${parameterKey}[${i}].${valueKey}`)}=${encodeURIComponent(pv[valueKey])}`)
|
|
})
|
|
})
|
|
return
|
|
}
|
|
}
|
|
// 나머지
|
|
queries.push(`${encodeURIComponent(parameterKey)}=${encodeURIComponent(parameterValue)}`)
|
|
})
|
|
return queries.join('&')
|
|
}
|