54 lines
1.3 KiB
JavaScript
54 lines
1.3 KiB
JavaScript
export default function listingResponseTranslator(dbResp, respSchema) {
|
|
|
|
// -----------------------------
|
|
// Normalize DB response
|
|
// -----------------------------
|
|
const rows = Array.isArray(dbResp)
|
|
? dbResp
|
|
: dbResp
|
|
? [dbResp]
|
|
: [];
|
|
|
|
// -----------------------------
|
|
// Pick only fields defined in response schema
|
|
// -----------------------------
|
|
const allowedFields = respSchema
|
|
? Object.keys(respSchema)
|
|
: null;
|
|
|
|
const normalizeRow = (row) => {
|
|
if (!row || typeof row !== 'object') return null;
|
|
|
|
// If schema exists, filter fields
|
|
if (allowedFields) {
|
|
const filtered = {};
|
|
for (const key of allowedFields) {
|
|
if (row[key] !== undefined) {
|
|
filtered[key] = row[key];
|
|
}
|
|
}
|
|
return filtered;
|
|
}
|
|
|
|
// Fallback (should not happen normally)
|
|
return row;
|
|
};
|
|
|
|
// -----------------------------
|
|
// Map rows
|
|
// -----------------------------
|
|
const result = rows
|
|
.map(normalizeRow)
|
|
.filter(Boolean);
|
|
|
|
// -----------------------------
|
|
// Return shape
|
|
// -----------------------------
|
|
// If schema represents a single object, return object
|
|
if (!Array.isArray(respSchema)) {
|
|
return result.length === 1 ? result[0] : result;
|
|
}
|
|
|
|
return result;
|
|
}
|