2021-03-08 16:07:10 +00:00
|
|
|
/**
|
|
|
|
* Base type for an API response format.
|
|
|
|
*/
|
2021-10-19 18:00:14 +00:00
|
|
|
export interface APIResponse<T> {
|
2021-03-08 16:07:10 +00:00
|
|
|
success: boolean,
|
|
|
|
message?: string,
|
2021-10-19 18:00:14 +00:00
|
|
|
data?: T,
|
2021-03-08 16:07:10 +00:00
|
|
|
error?: {
|
|
|
|
name: string,
|
|
|
|
message: string,
|
|
|
|
stack?: string[],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Formats a mesage as a successful API response.
|
2021-06-03 03:36:25 +00:00
|
|
|
* @param {string} displayMessage
|
2021-03-08 16:07:10 +00:00
|
|
|
* @return APIResponse
|
|
|
|
*/
|
2021-10-19 18:00:14 +00:00
|
|
|
export function message(displayMessage: string): APIResponse<void> {
|
2021-03-08 16:07:10 +00:00
|
|
|
return {
|
|
|
|
success: true,
|
2021-06-03 03:36:25 +00:00
|
|
|
message: displayMessage,
|
2021-03-08 16:07:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Formats a single record as a successful API response.
|
|
|
|
* @param record
|
|
|
|
* @return APIResponse
|
|
|
|
*/
|
2021-10-19 18:00:14 +00:00
|
|
|
export function one<T>(record: T): APIResponse<T> {
|
2021-03-08 16:07:10 +00:00
|
|
|
return {
|
|
|
|
success: true,
|
|
|
|
data: record,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Formats an array of records as a successful API response.
|
|
|
|
* @param {array} records
|
|
|
|
* @return APIResponse
|
|
|
|
*/
|
2021-10-19 18:00:14 +00:00
|
|
|
export function many<T>(records: T[]): APIResponse<{records: T[], total: number}> {
|
2021-03-08 16:07:10 +00:00
|
|
|
return {
|
|
|
|
success: true,
|
|
|
|
data: {
|
|
|
|
records,
|
|
|
|
total: records.length,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Formats an error message or Error instance as an API response.
|
|
|
|
* @return APIResponse
|
2021-06-03 03:36:25 +00:00
|
|
|
* @param thrownError
|
2021-03-08 16:07:10 +00:00
|
|
|
*/
|
2021-10-19 18:00:14 +00:00
|
|
|
export function error(thrownError: string | Error): APIResponse<void> {
|
2021-06-03 03:36:25 +00:00
|
|
|
if ( typeof thrownError === 'string' ) {
|
2021-03-08 16:07:10 +00:00
|
|
|
return {
|
|
|
|
success: false,
|
2021-06-03 03:36:25 +00:00
|
|
|
message: thrownError,
|
2021-03-08 16:07:10 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return {
|
|
|
|
success: false,
|
2021-06-03 03:36:25 +00:00
|
|
|
message: thrownError.message,
|
2021-03-08 16:07:10 +00:00
|
|
|
error: {
|
2021-06-03 03:36:25 +00:00
|
|
|
name: thrownError.name,
|
|
|
|
message: thrownError.message,
|
|
|
|
stack: thrownError.stack ? thrownError.stack.split(/\s+at\s+/).slice(1) : [],
|
2021-03-08 16:07:10 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|