guardz-axios
Version:
Type-safe HTTP client built on top of Axios with runtime validation using guardz. Part of the guardz ecosystem for comprehensive TypeScript type safety.
76 lines • 2.23 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SafeRequestBuilder = void 0;
const executeRequest_1 = require("../internal/executeRequest");
/**
* Pattern 3: Fluent API Builder
* Usage: const result = await safe().get('/users/1').guard(isUser).tolerance(false).execute();
*/
class SafeRequestBuilder {
constructor() {
this.config = {};
this.axiosConfig = {};
}
get(url) {
this.axiosConfig = { ...this.axiosConfig, method: "GET", url };
return this;
}
post(url, data) {
this.axiosConfig = { ...this.axiosConfig, method: "POST", url, data };
return this;
}
put(url, data) {
this.axiosConfig = { ...this.axiosConfig, method: "PUT", url, data };
return this;
}
patch(url, data) {
this.axiosConfig = { ...this.axiosConfig, method: "PATCH", url, data };
return this;
}
delete(url) {
this.axiosConfig = { ...this.axiosConfig, method: "DELETE", url };
return this;
}
guard(guardFn) {
const newBuilder = this;
newBuilder.config.guard = guardFn;
return newBuilder;
}
tolerance(enabled = true) {
this.config.tolerance = enabled;
return this;
}
identifier(id) {
this.config.identifier = id;
return this;
}
onTypeMismatch(callback) {
this.config.onTypeMismatch = callback;
return this;
}
timeout(ms) {
this.config.timeout = ms;
this.axiosConfig.timeout = ms;
return this;
}
retry(config) {
this.config.retry = config;
return this;
}
headers(headers) {
this.axiosConfig.headers = { ...this.axiosConfig.headers, ...headers };
return this;
}
baseURL(url) {
this.axiosConfig.baseURL = url;
return this;
}
async execute() {
if (!this.config.guard) {
throw new Error("Type guard is required. Call .guard(typeGuardFn) before .execute()");
}
return (0, executeRequest_1.executeRequest)(this.axiosConfig, this.config);
}
}
exports.SafeRequestBuilder = SafeRequestBuilder;
//# sourceMappingURL=SafeRequestBuilder.js.map