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.
lib/src/http/response/api.ts

77 lines
1.6 KiB

/**
* 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} message
* @return APIResponse
*/
export function message(message: string): APIResponse {
return {
success: true,
message,
}
}
/**
* Formats a single record as a successful API response.
* @param record
* @return APIResponse
*/
export function one(record: any): 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.
* @param {string|Error} error
* @return APIResponse
*/
export function error(error: string | Error): APIResponse {
if ( typeof error === 'string' ) {
return {
success: false,
message: error,
}
} else {
return {
success: false,
message: error.message,
error: {
name: error.name,
message: error.message,
stack: error.stack ? error.stack.split(/\s+at\s+/).slice(1) : [],
},
}
}
}