@platform/cell.client
Version:
A strongly typed HTTP client for operating with a CellOS service end-point.
51 lines (50 loc) • 1.59 kB
JavaScript
export function isOK(status = 200) {
return status.toString().startsWith('2');
}
export function isObservable(input) {
return typeof (input === null || input === void 0 ? void 0 : input.subscribe) === 'function';
}
export function fromHttpResponse(res) {
return {
toClientResponse(options = {}) {
const { bodyType = 'JSON' } = options;
const { status } = res;
let body = {};
body = bodyType === 'JSON' ? res.json : body;
body = bodyType === 'BINARY' ? res.body : body;
body = bodyType === 'TEXT' ? res.text : body;
return toClientResponse(status, body);
},
};
}
export function toClientResponse(status, body, options = {}) {
const { bodyType = 'JSON', error } = options;
const ok = isOK(status);
const res = { ok, status, body, bodyType, error };
if (ok) {
return res;
}
else {
if (isError(body)) {
const error = body;
return toError(error.status, error.type, error.message, {});
}
else {
return res;
}
}
}
export function toError(status, type, message, body) {
const error = { status, type, message };
status = isOK(status) ? 500 : status;
body = body || {};
const res = { ok: false, status, body, bodyType: 'JSON', error };
return res;
}
export function isError(data) {
return (data &&
typeof data.status === 'number' &&
typeof data.message === 'string' &&
typeof data.type === 'string' &&
!isOK(data.status));
}