JAVASCRIPT
Transform Raw API Response to a Client-Side Model
Transform raw, inconsistent API responses into a normalized, predictable client-side data model, simplifying handling and display in your application.
// Example raw API response structure
const rawApiData = {
meta: {
timestamp: "2023-10-27T10:30:00Z",
request_id: "xyz123",
status: "success"
},
payload: [
{
user_id: "usr_001",
first_name: "John",
last_name: "Doe",
email_address: "[email protected]",
last_login: 1678886400, // Unix timestamp
account_status: "active",
address_info: {
street: "123 Main St",
city: "Anytown",
zip_code: "12345"
},
roles: ["admin", "editor"]
},
{
user_id: "usr_002",
first_name: "Jane",
last_name: "Smith",
email_address: "[email protected]",
last_login: 1679059200,
account_status: "inactive",
address_info: {
street: "456 Oak Ave",
city: "Otherville",
zip_code: "67890"
},
roles: ["viewer"]
}
]
};
// Define the desired client-side model structure
class User {
constructor(id, fullName, email, lastLoginDate, isActive, fullAddress, permissions) {
this.id = id;
this.fullName = fullName;
this.email = email;
this.lastLoginDate = lastLoginDate; // Date object
this.isActive = isActive;
this.fullAddress = fullAddress;
this.permissions = permissions;
}
get greeting() {
return `Hello, ${this.fullName}!`;
}
}
/**
* Transforms a single raw user object from the API into our client-side User model.
* @param {object} rawUser - The raw user object from the API.
* @returns {User} The transformed User object.
*/
function transformUser(rawUser) {
if (!rawUser) return null;
const {
user_id,
first_name,
last_name,
email_address,
last_login,
account_status,
address_info,
roles
} = rawUser;
const fullName = `${first_name} ${last_name}`;
const email = email_address;
const lastLoginDate = last_login ? new Date(last_login * 1000) : null; // Convert Unix timestamp to Date
const isActive = account_status === 'active';
const fullAddress = address_info
? `${address_info.street}, ${address_info.city}, ${address_info.zip_code}`
: 'N/A';
const permissions = roles;
return new User(user_id, fullName, email, lastLoginDate, isActive, fullAddress, permissions);
}
/**
* Transforms the entire raw API response to an array of client-side User models.
* @param {object} apiResponse - The full API response object.
* @returns {User[]} An array of transformed User objects.
*/
function transformApiResponse(apiResponse) {
if (!apiResponse || !apiResponse.payload || !Array.isArray(apiResponse.payload)) {
console.warn('API response payload is missing or not an array.');
return [];
}
return apiResponse.payload.map(transformUser);
}
// Example usage:
// Assuming you fetched rawApiData from an API call
/*
const transformedUsers = transformApiResponse(rawApiData);
console.log('Transformed Users:', transformedUsers);
console.log('First user greeting:', transformedUsers[0].greeting);
*/
How it works: This snippet demonstrates how to transform a raw, potentially complex API response into a consistent and easier-to-use client-side data model. It defines a `User` class to represent the desired structure and a `transformUser` function to map individual raw user objects to instances of this class, handling data type conversions (e.g., Unix timestamp to `Date`), string formatting, and boolean mapping. The `transformApiResponse` function then applies this transformation across an array of items in the API payload, centralizing data normalization.