Standard libraries that lift up your code.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

76 lines
1.7 KiB

/**
* Base type for an API response format.
*/
export interface APIResponse<T> {
success: boolean,
message?: string,
data?: T,
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<void> {
return {
success: true,
message: displayMessage,
}
}
/**
* Formats a single record as a successful API response.
* @param record
* @return APIResponse
*/
export function one<T>(record: T): APIResponse<T> {
return {
success: true,
data: record,
}
}
/**
* Formats an array of records as a successful API response.
* @param {array} records
* @return APIResponse
*/
export function many<T>(records: T[]): APIResponse<{records: T[], total: number}> {
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<void> {
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) : [],
},
}
}
}