|
|
|
/**
|
|
|
|
* Base type for an API response format.
|
|
|
|
*/
|
|
|
|
export interface APIResponse {
|
|
|
|
success: boolean,
|
|
|
|
message?: string,
|
|
|
|
data?: any,
|
|
|
|
error?: {
|
|
|
|
name: string,
|
|
|
|
message: string,
|
|
|
|
stack?: string[],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Formats a mesage as a successful API response.
|
|
|
|
* @param {string} displayMessage
|
|
|
|
* @return APIResponse
|
|
|
|
*/
|
|
|
|
export function message(displayMessage: string): APIResponse {
|
|
|
|
return {
|
|
|
|
success: true,
|
|
|
|
message: displayMessage,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Formats a single record as a successful API response.
|
|
|
|
* @param record
|
|
|
|
* @return APIResponse
|
|
|
|
*/
|
|
|
|
export function one(record: unknown): APIResponse {
|
|
|
|
return {
|
|
|
|
success: true,
|
|
|
|
data: record,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Formats an array of records as a successful API response.
|
|
|
|
* @param {array} records
|
|
|
|
* @return APIResponse
|
|
|
|
*/
|
|
|
|
export function many(records: any[]): APIResponse {
|
|
|
|
return {
|
|
|
|
success: true,
|
|
|
|
data: {
|
|
|
|
records,
|
|
|
|
total: records.length,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Formats an error message or Error instance as an API response.
|
|
|
|
* @return APIResponse
|
|
|
|
* @param thrownError
|
|
|
|
*/
|
|
|
|
export function error(thrownError: string | Error): APIResponse {
|
|
|
|
if ( typeof thrownError === 'string' ) {
|
|
|
|
return {
|
|
|
|
success: false,
|
|
|
|
message: thrownError,
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return {
|
|
|
|
success: false,
|
|
|
|
message: thrownError.message,
|
|
|
|
error: {
|
|
|
|
name: thrownError.name,
|
|
|
|
message: thrownError.message,
|
|
|
|
stack: thrownError.stack ? thrownError.stack.split(/\s+at\s+/).slice(1) : [],
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|