UNPKG

@platform/cell.client

Version:

A strongly typed HTTP client for operating with a CellOS service end-point.

63 lines (62 loc) 2.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isOK(status) { if (status === void 0) { status = 200; } return status.toString().startsWith('2'); } exports.isOK = isOK; function isObservable(input) { var _a; return typeof ((_a = input) === null || _a === void 0 ? void 0 : _a.subscribe) === 'function'; } exports.isObservable = isObservable; function fromHttpResponse(res) { return { toClientResponse: function (options) { if (options === void 0) { options = {}; } var _a = options.bodyType, bodyType = _a === void 0 ? 'JSON' : _a; var status = res.status; var body = {}; body = bodyType === 'JSON' ? res.json : body; body = bodyType === 'BINARY' ? res.body : body; body = bodyType === 'TEXT' ? res.text : body; return toClientResponse(status, body); }, }; } exports.fromHttpResponse = fromHttpResponse; function toClientResponse(status, body, options) { if (options === void 0) { options = {}; } var _a = options.bodyType, bodyType = _a === void 0 ? 'JSON' : _a, error = options.error; var ok = isOK(status); var res = { ok: ok, status: status, body: body, bodyType: bodyType, error: error }; if (ok) { return res; } else { if (isError(body)) { var error_1 = body; return toError(error_1.status, error_1.type, error_1.message, {}); } else { return res; } } } exports.toClientResponse = toClientResponse; function toError(status, type, message, body) { var error = { status: status, type: type, message: message }; status = isOK(status) ? 500 : status; body = body || {}; var res = { ok: false, status: status, body: body, bodyType: 'JSON', error: error }; return res; } exports.toError = toError; function isError(data) { return (data && typeof data.status === 'number' && typeof data.message === 'string' && typeof data.type === 'string' && !isOK(data.status)); } exports.isError = isError;