buildResponse
functionBuilds the envelope for an HTTP body. The response is successful when no error is passed. Any error that is passed, even a falsy one, becomes { code, message, data }: an Exception keeps all three, and any other error keeps its string code, or gets UNKNOWN_ERROR, and its message. A failed response can carry data too.
buildResponse<T = undefined>(data?: T, error?: unknown): IApiResponse<T>Parameters
data?TThe data to send.
error?unknownThe error the request failed with, of any shape.
Returns
IApiResponse<T>The envelope, which JSON.stringify can always serialize when the data can.
import { buildResponse } from 'jg-api-response';
import { Exception } from 'jg-exception';
buildResponse({ id: 1 }); // => { success: true, data: { id: 1 }, error: null }
buildResponse(undefined, new Exception('Not found', { code: 'NOT_FOUND', data: { id: 1 } }));
// { success: false, data: undefined, error: { code: 'NOT_FOUND', message: 'Not found', data: { id: 1 } } }