### Installing Dependencies with Bun Source: https://github.com/edgefirst-dev/api-client/blob/main/CONTRIBUTING.md Installs all project dependencies using the Bun package manager. This command should be run initially after cloning the repository or when dependencies change. ```Bun Shell bun install ``` -------------------------------- ### Installing @edgefirst-dev/api-client with Bun Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This snippet demonstrates how to install the `@edgefirst-dev/api-client` package using the Bun package manager. This is the first step to integrate the API client into your project. ```sh bun add @edgefirst-dev/api-client ``` -------------------------------- ### Initializing APIClient and Making a GET Request (TypeScript) Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This snippet shows the basic usage of the `APIClient` class. It imports the class, creates a new instance with a base URL, and then performs a simple GET request to retrieve user data. ```ts import { APIClient } from "@edgefirst-dev/api-client"; let client = new APIClient("https://api.example.com"); let response = await client.get("/users/1"); ``` -------------------------------- ### Running Tests with Bun Source: https://github.com/edgefirst-dev/api-client/blob/main/CONTRIBUTING.md Executes the project's test suite using Bun. This command verifies the correctness and functionality of the codebase. ```Bun Shell bun test ``` -------------------------------- ### Checking Exports with Bun Source: https://github.com/edgefirst-dev/api-client/blob/main/CONTRIBUTING.md Verifies the project's exports using Bun. This command ensures that the module's public API is correctly defined and accessible. ```Bun Shell bun run exports ``` -------------------------------- ### Checking Code Quality with Bun Source: https://github.com/edgefirst-dev/api-client/blob/main/CONTRIBUTING.md Runs the code quality checker defined in the project's scripts using Bun. This helps maintain consistent coding standards and identify potential issues. ```Bun Shell bun run quality ``` -------------------------------- ### Running Type Checker with Bun Source: https://github.com/edgefirst-dev/api-client/blob/main/CONTRIBUTING.md Executes the type checker defined in the project's scripts using Bun. This ensures type safety and helps catch type-related errors during development. ```Bun Shell bun run typecheck ``` -------------------------------- ### Extending APIClient for Custom Request/Response Handling (TypeScript) Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This example demonstrates how to extend the `APIClient` class to customize request and response handling. It overrides the `before` method to add a custom header and the `after` method to handle unauthorized (401) responses, providing a centralized way to modify behavior. ```ts class CustomAPIClient extends APIClient { async before(request: Request) { // Add a custom header to the request request.headers.set("X-Custom-Header", "value"); return request; } async after(request: Request, response: Response) { if (response.status === 401) { // Handle unauthorized error throw new Error("Unauthorized"); } return response; } } let client = new CustomAPIClient("https://api.example.com"); let response = await client.get("/users/1"); ``` -------------------------------- ### Testing APIClient Calls with MSW for Mocking Responses (TypeScript) Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This example shows how to integrate `APIClient` with `msw` (Mock Service Worker) for effective API testing. It sets up a mock server to intercept and respond to specific HTTP requests, allowing for isolated and reliable testing of API client interactions without hitting a real backend. ```ts import { http, HttpResponse } from "msw"; import { setupServer } from "msw/native"; // or "msw/node" or "msw/browser" let server = setupServer( http.get("https://api.example.com/users/1", (req, res, ctx) => { return res(ctx.json({ id: 1, name: "John Doe" })); }) ); server.listen(); let client = new APIClient("https://api.example.com"); let response = await client.get("/users/1"); let data = await response.json(); // { id: 1, name: "John Doe" } ``` -------------------------------- ### Setting Default Base URL by Overriding APIClient Constructor (TypeScript) Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This example shows how to override the constructor of the `APIClient` subclass to provide a default base URL. This eliminates the need to specify the base URL every time a new client instance is created, simplifying initialization. ```ts class CustomAPIClient extends APIClient { constructor() { super("https://api.example.com"); } } let client = new CustomAPIClient(); ``` -------------------------------- ### Setting Request Timeout with AbortSignal in TypeScript Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This code demonstrates how to set a timeout for an API request using the signal option with AbortSignal.timeout(). It ensures that the get request to /users/1 will automatically be aborted if it does not complete within 5000 milliseconds, preventing indefinite waiting. ```TypeScript let client = new APIClient("https://api.example.com"); await client.get("/users/1", { signal: AbortSignal.timeout(5000) }); ``` -------------------------------- ### Removing Specific Interceptors from APIClient Instance (TypeScript) Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This example illustrates how to remove a previously added interceptor from an `APIClient` instance using the `off` method. This is useful for managing interceptor lifecycle, ensuring that specific behaviors are applied only when needed. ```ts async function beforeInterceptor(request) { // Add a custom header to the request request.headers.set("X-Custom-Header", "value"); return request; } let client = new APIClient("https://api.example.com"); client.interceptors.before.on(beforeInterceptor); // Add the interceptor client.interceptors.before.off(beforeInterceptor); // Remove the interceptor ``` -------------------------------- ### Handling Common API Errors with Custom Interceptor in TypeScript Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This example illustrates handling common API errors by extending the APIClient class and overriding the after interceptor method. It centralizes the logic for checking and responding to specific HTTP status codes, such as a 401 Unauthorized error, before the response is returned. ```TypeScript class CustomAPIClient extends APIClient { async after(request: Request, response: Response) { if (response.status === 401) { // Handle unauthorized error throw new Error("Unauthorized"); } return response; } } ``` -------------------------------- ### Adding Request and Response Interceptors to APIClient Instance (TypeScript) Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This snippet demonstrates how to add `before` and `after` interceptors directly to an `APIClient` instance. These interceptors allow for dynamic modification of requests (e.g., adding headers) and handling of responses (e.g., error handling) without subclassing. ```ts let client = new APIClient("https://api.example.com"); client.interceptors.before.on(async (request) => { // Add a custom header to the request request.headers.set("X-Custom-Header", "value"); return request; }); client.interceptors.after.on(async (request, response) => { if (response.status === 401) { // Handle unauthorized error throw new Error("Unauthorized"); } return response; }); ``` -------------------------------- ### Handling API Errors with Try-Catch in TypeScript Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This snippet demonstrates how to handle API errors by directly checking the response status code within a try-catch block. It specifically shows how to identify and throw an error for a 401 Unauthorized status, while the catch block handles network-related errors. ```TypeScript let client = new APIClient("https://api.example.com"); try { let response = await client.get("/users/1"); if (response.status === 401) { // Handle unauthorized error throw new Error("Unauthorized"); } // Handle other errors or success } catch (error) { // Handle network error console.error(error); } ``` -------------------------------- ### Adding Custom API Call Methods to APIClient Subclass (TypeScript) Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This snippet illustrates how to define custom methods within an `APIClient` subclass to encapsulate specific API calls. The `fetchUserData` method simplifies fetching and parsing user data, making API interactions more organized and reusable. ```ts import { ObjectParser } from "@edgefirst-dev/data/parser"; class CustomAPIClient extends APIClient { async fetchUserData(id: number) { let response = await this.get(`/users/${id}`); let data = await response.json(); return new ObjectParser(data); } } let client = new CustomAPIClient("https://api.example.com"); let user = await client.fetchUserData(1); let userName = user.string("name"); ``` -------------------------------- ### Understanding Interceptor Execution Order: Subclass vs. Instance (TypeScript) Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This snippet demonstrates the execution order of interceptors: subclass interceptors run before instance interceptors. In this specific case, the instance interceptor's header modification will override the one set by the subclass interceptor, resulting in 'X-Custom-Header' being '2'. ```ts class CustomAPIClient extends APIClient { async before(request: Request) { // Add a custom header to the request request.headers.set("X-Custom-Header", "1"); return request; } } let client = new CustomAPIClient("https://api.example.com"); client.interceptors.before.on(async (request) => { // Add a custom header to the request request.headers.set("X-Custom-Header", "2"); return request; }); ``` -------------------------------- ### Adding After Interceptor for API Error Handling in TypeScript Source: https://github.com/edgefirst-dev/api-client/blob/main/README.md This snippet demonstrates how to add an after interceptor to an existing APIClient instance using the on method. This approach allows for dynamically attaching error handling logic, such as checking for a 401 Unauthorized status, to the response processing pipeline without subclassing. ```TypeScript let client = new APIClient("https://api.example.com"); client.interceptors.after.on(async (_, response) => { if (response.status === 401) { // Handle unauthorized error throw new Error("Unauthorized"); } return response; }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.