UNPKG

@izzyjs/route

Version:

Use your AdonisJs routes in your Inertia.js application

90 lines (89 loc) 2.98 kB
import { HttpClient } from './http_client.js'; import { Route } from './route.js'; // Create default client instance const client = new HttpClient(); class RequestBuilder { constructor(route, data, config, httpClient = client) { this.route = route; this.data = data; this.config = config; this.httpClient = httpClient; } successType() { return new RequestBuilder(this.route, this.data, this.config, this.httpClient); } failedType() { return new RequestBuilder(this.route, this.data, this.config, this.httpClient); } withData(data) { return new RequestBuilder(this.route, data, this.config, this.httpClient); } async run() { try { let response; switch (this.route.method) { case 'get': response = await this.httpClient.get(this.route.url, this.config); break; case 'post': response = await this.httpClient.post(this.route.url, this.data, this.config); break; case 'put': response = await this.httpClient.put(this.route.url, this.data, this.config); break; case 'delete': response = await this.httpClient.delete(this.route.url, this.config); break; case 'patch': response = await this.httpClient.patch(this.route.url, this.data, this.config); break; default: throw new Error(`Unsupported HTTP method: ${this.route.method}`); } const { data, status } = response; if (status < 200 || status >= 300) { return { data: null, error: data }; } return { data, error: null }; } catch (error) { return { data: null, error: error }; } } } class ApiBuilder { constructor(nameRoute, params, httpClient = client) { this.nameRoute = nameRoute; this.params = params; this.httpClient = httpClient; } withQs(qs) { this.qs = qs; return this; } withHash(hash) { this.hash = hash; return this; } withPrefix(prefix) { this.prefix = prefix; return this; } route() { return Route.new(this.nameRoute, this.params, this.qs, this.prefix, this.hash); } request(config) { return new RequestBuilder(this.route(), undefined, config, this.httpClient); } } function builder(nameRoute, params) { return new ApiBuilder(nameRoute, params); } // Factory function to create builder with custom client export function createApiBuilder(customClient) { function customBuilder(nameRoute, params) { return new ApiBuilder(nameRoute, params, customClient); } return customBuilder; } export default builder;