@clickup/rest-client
Version:
A syntax sugar tool around Node fetch() API, tailored to work with TypeScript and response validators
57 lines • 2.72 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fast_typescript_memoize_1 = require("fast-typescript-memoize");
/**
* RestResponse is intentionally not aware of the data structure it carries, and
* it doesn't do any assertions/validations which is the responsibility of
* RestRequest helper methods.
*
* We also use a concept of "body preloading". Sometimes, e.g. on non-successful
* HTTP status codes, we also need to know the body content (at least its
* beginning), do double check whether should we retry, throw through or through
* a user-friendly error. To do this, we need to preload the beginning of the
* body and make it a part of RestResponse abstraction.
*/
class RestResponse {
constructor(req, agent, status, headers, text, textIsPartial) {
this.req = req;
this.agent = agent;
this.status = status;
this.headers = headers;
this.text = text;
this.textIsPartial = textIsPartial;
}
/**
* A safe way to treat the response as JSON.
* - Never throws, i.e. we imply that the caller will verify the structure of
* the response and do its own errors processing.
* - It's a getter, so we can use typescript-is'es is<xyz>() type guard, e.g.:
* `if (is<{ errors: any[] }>(res.json) && res.json.errors.length) { ... }`
*
* Notice that there is NO `assert()` abstraction inside RestResponse class.
* This is because RestClient sometimes substitutes the response with some
* sub-field (e.g. see writeGraphQLX() method), and we still need to run the
* assertion in such cases. By not having strong typing here, we intentionally
* make the use of this method harder, so people will prefer using
* RestRequest.json() instead.
*/
get json() {
try {
return this.text ? JSON.parse(this.text) : undefined;
}
catch (e) {
return undefined;
}
}
}
exports.default = RestResponse;
__decorate([
(0, fast_typescript_memoize_1.Memoize)()
], RestResponse.prototype, "json", null);
//# sourceMappingURL=RestResponse.js.map
;