bananas-commerce
Version:
A client for bananas-commerce with support for TypeScript
24 lines (23 loc) • 938 B
JavaScript
/**
* Formats a {@link VariableResult} for an {@link ApiResponse} using a {@link matcher}.
* If the data is not an object or an array, i.e. a primitive value, an object with the matched type
* is returned. The type is defined as the `_type` property.
*
* @remarks
* If `undefined` or `null` is returned from the {@link matcher}, `console.error` is used to print an error
* detailing that no response type could be resolved, and the response data is returned without a type.
*/
export function formatVariableResult(response, matcher) {
const type = matcher(response);
if (type == null) {
console.error("No API response type could be resolved for the response from " +
response.url +
":", response);
}
let data = response.data;
if (data === null || typeof data !== "object") {
data = {};
}
Object.defineProperty(data, "_type", { value: type });
return data;
}