A Simple Utility to Create Unified Response Objects for APIs. Allowing for Easy Handling of API Responses Across Your Application.
- Unified response format for all API calls.
- Flexible to include additional custom fields.
- Automatically includes a timestamp for - logging and tracking.
- Supports both successful and error responses.
npm install uni-response
import { unifiedResponse } from 'uni-response';
const response = unifiedResponse(true, 'Request was successful', { id: 1 });
console.log(response);
/*
{
success: true,
message: "Request was successful",
data: { id: 1 },
timestamp: "..."
}
*/
// Example with CustomResponseFields
interface CustomResponseFields {
customField1: string;
customField2: number;
customField3: boolean;
}
// Creating a response with custom fields
const responseWithCustomFields =
unifiedResponse <
CustomResponseFields >
(true,
'Request was successful',
{ user: 'Jane Doe' },
null,
null,
{
customField1: 'Custom Data 1',
customField2: 42,
customField3: true,
});
// Output
console.log(responseWithCustomFields);
/*
{
success: true,
message: "Request was successful",
data: { user: 'Jane Doe' },
timestamp: "..."
extraFields: {
customField1: 'Custom Data 1',
customField2: 42,
customField3: true,
}
}
*/
interface Response<T = Record<string, unknown>> {
success: boolean;
message: string;
data?: object | null;
error?: object | null;
metadata?: object | null;
timestamp: string;
extraFields?: T; // Generic type for extra fields
}
MIT License