### Basic Route Call Example Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/klaim.md Demonstrates registering a simple GET route and calling it via the Klaim runtime to fetch a single resource. ```typescript Api.create("todos", "https://jsonplaceholder.typicode.com", () => { Route.get("getOne", "/todos/[id]"); }); const todo = await Klaim.todos.getOne({ id: 1 }); ``` -------------------------------- ### Define a Basic API with Multiple Routes Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Api.md This example demonstrates creating a GitHub API client with routes for listing, getting, creating, and deleting repositories. It also shows how to use the defined API and routes. ```typescript Api.create("github", "https://api.github.com", () => { Route.get("listRepos", "/user/repos"); Route.get("getRepo", "/repos/[owner]/[repo]"); Route.post("createRepo", "/user/repos"); Route.delete("deleteRepo", "/repos/[owner]/[repo]"); }); // Usage const repos = await Klaim.github.listRepos(); const repo = await Klaim.github.getRepo({owner: "antharuu", repo: "klaim"}); ``` -------------------------------- ### Complete Example with Runtime Patterns Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/guides/advanced-runtime-patterns.md A comprehensive example integrating API defaults, route-specific middleware, hooks, and detailed error handling for production clients. ```typescript import { Api, Hook, Klaim, RateLimitError, Registry, RetryExhaustedError, Route, TimeoutError, } from "klaim"; Api.create("inventory", "https://dummyjson.com", () => { Route.get("listProducts", "/products"); Route.get("getProduct", "/products/[id]").withTimeout(1.5, "Product lookup timed out"); }).withRetry(2).withRate({ limit: 8, duration: 30 }); Registry.i.getRoute("inventory", "listProducts")?.after(({ route, api, response, data }) => { const payload = data as { products: Array<{ id: number; title: string }> }; return { route, api, response, data: payload.products.map((item) => ({ id: item.id, title: item.title, })), }; }); Hook.subscribe("inventory.listProducts", () => { console.log("products loaded"); }); async function main() { try { const products = await Klaim.inventory.listProducts>(); console.log(products.slice(0, 3)); } catch (error) { if (error instanceof TimeoutError) { console.error(error.message); return; } if (error instanceof RateLimitError) { console.error(`wait ${error.retryAfterMs}ms`); return; } if (error instanceof RetryExhaustedError) { console.error(`failed after ${error.attempts} attempts`); return; } throw error; } } main(); ``` -------------------------------- ### Install Klaim with bun Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/index.md Installs the Klaim library using bun. This is a prerequisite for using Klaim in your project. ```bash bun add klaim ``` -------------------------------- ### Route.get() Examples Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Creates GET routes for listing users or retrieving a specific user by ID. ```typescript Route.get("listUsers", "/users"); Route.get("getUser", "/users/[id]"); ``` -------------------------------- ### Install Klaim via npm, bun, or deno Source: https://github.com/antharuu/klaim/blob/main/README.md Install the Klaim library using your preferred package manager. This is the first step to using Klaim in your project. ```sh npm install klaim ``` ```sh bun add klaim ``` ```sh deno add @antharuu/klaim ``` -------------------------------- ### Klaim API Testing Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/README.md Demonstrates how to set up and use the Klaim API for testing purposes. It includes clearing the registry before each test and creating a sample API with a GET route. ```typescript import { Registry, Api, Route } from 'klaim'; beforeEach(() => { Registry.i.reset(); // Clear all APIs }); Api.create("test", "https://test.com", () => { Route.get("data", "/data"); }); const result = await Klaim.test.data(); ``` -------------------------------- ### Install Klaim with yarn Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/index.md Installs the Klaim library using yarn. This is a prerequisite for using Klaim in your project. ```bash yarn add klaim ``` -------------------------------- ### Install Klaim with pnpm Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/index.md Installs the Klaim library using pnpm. This is a prerequisite for using Klaim in your project. ```bash pnpm add klaim ``` -------------------------------- ### Complete Klaim Client Example with Types and Options Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/guides/defining-a-client.md A comprehensive example demonstrating API definition with route-specific options like timeouts and retries, type safety for responses, and concurrent API calls. This showcases advanced usage patterns. ```typescript import { Api, Group, Klaim, Route } from "klaim"; type Post = { id: number; title: string; body: string; userId: number; }; type User = { id: number; name: string; email: string; }; Api.create( "blog", "https://jsonplaceholder.typicode.com", () => { Group.create("posts", () => { Route.get("list", "/posts").withTimeout(2); Route.get("getOne", "/posts/[id]"); Route.post("create", "/posts"); }).withRetry(1); Group.create("users", () => { Route.get("list", "/users"); Route.get("getOne", "/users/[id]"); }); }, { Authorization: "Bearer example-token", } ); async function run() { const [posts, user] = await Promise.all([ Klaim.blog.posts.list(), Klaim.blog.users.getOne({ id: 1 }), ]); const created = await Klaim.blog.posts.create( {}, { title: "Guide post", body: "Example body", userId: 1 } ); console.log(posts.length, user.email, created.id); } run(); ``` -------------------------------- ### Install Klaim with npm Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/index.md Installs the Klaim library using npm. This is a prerequisite for using Klaim in your project. ```bash npm install klaim ``` -------------------------------- ### Basic Route Call Example Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/klaim.md Demonstrates a basic route call for a non-paginated GET request. ```APIDOC ## Basic Route Call Example ### Description Demonstrates a basic route call for a non-paginated GET request. ### Method Not applicable (SDK method call) ### Endpoint Not applicable (SDK method call) ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the todo item. #### Query Parameters None #### Request Body None ### Request Example ```typescript const todo = await Klaim.todos.getOne({ id: 1 }); ``` ### Response #### Success Response - **todo** - The retrieved todo item. #### Response Example None provided in source. ``` -------------------------------- ### Route Constructor Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Demonstrates how to create a new Route instance with a name, URL, headers, and HTTP method. ```typescript const route = new Route("getUser", "/users/[id]", {}, RouteMethod.GET); ``` -------------------------------- ### Basic Routes Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Demonstrates the creation of basic HTTP routes using `Route.get`, `Route.post`, `Route.put`, and `Route.delete`. ```APIDOC ### Basic Routes ```typescript Api.create("api", "https://api.example.com", () => { Route.get("list", "/items"); Route.get("getOne", "/items/[id]"); Route.post("create", "/items"); Route.put("update", "/items/[id]"); Route.delete("delete", "/items/[id]"); }); ``` ``` -------------------------------- ### Complete Klaim Configuration Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/configuration.md This example demonstrates a comprehensive configuration for a protected API group, including route-specific caching, rate limiting, timeouts, retries, and global group-level settings. It also shows how to use before and after hooks for request authorization and response normalization. ```typescript import { Api, Route, Group } from 'klaim'; Group.create("services", () => { Api.create("protected", "https://api.example.com", () => { Group.create("users", () => { Route.get("list", "/users") .withCache(300) // 5 min cache .withRate({limit: 10, duration: 60}) // 10/min .withTimeout(15, "Users list slow"); Route.get("getOne", "/users/[id]") .withCache(600) // 10 min cache .withRetry(3) // 3 retries .withTimeout(10); Route.post("create", "/users") .withRetry(5) // More retries for writes .withTimeout(20); // Longer timeout }) .withPagination({limit: 20}); Route.delete("deleteUser", "/users/[id]") .withRate({limit: 1, duration: 60}); // 1 per minute }) .before(({config}) => { config.headers.Authorization = `Bearer ${getToken()}`; return {config}; }) .after(({data}) => { return {data: normalizeResponse(data)}; }); }) .withRetry(2) // Group-level retry fallback .withTimeout(30); // 30 second group timeout ``` -------------------------------- ### Route.post() Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Creates a POST route for creating a new user. ```typescript Route.post("createUser", "/users"); ``` -------------------------------- ### Complete Example: Paginated Route with Validation and Hooks Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/guides/pagination-validation-and-observability.md A comprehensive example integrating route definition with pagination and validation, hook subscription for observing completion, and client-side calls to fetch multiple pages. It includes type definitions and demonstrates logging the fetched data. ```typescript import { Api, Hook, Klaim, Route } from "klaim"; import * as yup from "yup"; type PokemonList = { results: Array<{ name: string }>; }; const pokemonListSchema = yup.object({ results: yup.array( yup.object({ name: yup.string().required(), }) ).required(), }); Api.create("pokemon", "https://pokeapi.co/api/v2", () => { Route.get("list", "/pokemon") .withPagination({ pageParam: "offset", limitParam: "limit", limit: 5 }) .withTimeout(2) .validate(pokemonListSchema); }); Hook.subscribe("pokemon.list", () => { console.log("pokemon.list finished"); }); async function run() { const pageOne = await Klaim.pokemon.list(0); const pageTwo = await Klaim.pokemon.list(5); console.log(pageOne.results.map((item) => item.name)); console.log(pageTwo.results.map((item) => item.name)); } run(); ``` -------------------------------- ### Route Validation Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Demonstrates setting up response validation for a GET route using a Yup schema. ```typescript import * as yup from 'yup'; const userSchema = yup.object().shape({ id: yup.number().required(), name: yup.string().required(), email: yup.string().email().required() }); Route.get("getUser", "/users/[id]") .validate(userSchema); ``` -------------------------------- ### Paginated Route Call Example Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/klaim.md Illustrates registering a paginated GET route and calling it to retrieve different pages of results. ```typescript Api.create("pokemon", "https://pokeapi.co/api/v2", () => { Route.get("list", "/pokemon").withPagination({ pageParam: "offset", limitParam: "limit", limit: 5, }); }); const firstPage = await Klaim.pokemon.list(0); const secondPage = await Klaim.pokemon.list(5); ``` -------------------------------- ### Routes with Pagination Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Demonstrates configuring pagination for routes using the `withPagination` method, specifying parameters for page and limit. ```APIDOC ### Routes with Pagination ```typescript Api.create("api", "https://api.example.com", () => { Route.get("listItems", "/items").withPagination({ limit: 20, page: 1, pageParam: "page", limitParam: "limit" }); }); // Usage const page1 = await Klaim.api.listItems(); const page2 = await Klaim.api.listItems(2); const page3 = await Klaim.api.listItems(3, {category: "electronics"}); ``` ``` -------------------------------- ### Registration Flow Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Registry.md Demonstrates the registration process when Api.create() is called, showing how the current parent context is managed during callback execution. ```typescript Api.create("users", "https://api.users.com", () => { // During this callback, currentParent = "users" Route.get("list", "/users"); Route.get("getOne", "/users/[id]"); // After callback, previousParent is restored }); ``` -------------------------------- ### Route.get() Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Creates a GET route. This is a static shortcut for defining GET requests. ```APIDOC ## Route.get() ### Description Creates a GET route. This is a static shortcut for defining GET requests. ### Method `public static get(name: string, url: string, headers?: IHeaders): Element` ### Parameters #### Path Parameters - **name** (string) - Required - Route name - **url** (string) - Required - Route URL path - **headers** (IHeaders) - Optional - Route-specific headers ### Returns `Element` - The created GET route ### Request Example ```typescript Route.get("listUsers", "/users"); Route.get("getUser", "/users/[id]"); ``` ``` -------------------------------- ### Route.options() Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Creates an OPTIONS route for retrieving user-related options. ```typescript Route.options("userOptions", "/users"); ``` -------------------------------- ### Example Usage of IHeaders Source: https://github.com/antharuu/klaim/blob/main/_autodocs/types.md Demonstrates creating an IHeaders object with an Authorization token and an API version. ```typescript const headers: IHeaders = { "Authorization": "Bearer token", "X-API-Version": "2" }; ``` -------------------------------- ### Basic Event Monitoring Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Hook.md Demonstrates subscribing to route events for user list and creation, and then triggering these routes to observe the logged messages. ```typescript import { Api, Route, Hook } from 'klaim'; Api.create("users", "https://api.example.com", () => { Route.get("list", "/users"); Route.get("getOne", "/users/[id]"); Route.post("create", "/users"); }); // Subscribe to hooks Hook.subscribe("users.list", () => { console.log("Fetched user list"); }); Hook.subscribe("users.create", () => { console.log("User created"); }); // Usage await Klaim.users.list(); // Logs: "Fetched user list" await Klaim.users.create({}, {name: "John"}); // Logs: "User created" ``` -------------------------------- ### Example Usage of IRouteReference Source: https://github.com/antharuu/klaim/blob/main/_autodocs/types.md Shows a basic example of creating an IRouteReference object to manually define a set of route functions. ```typescript const routes: IRouteReference = { list: async () => {}, getOne: async () => {}, create: async () => {} }; ``` -------------------------------- ### Route Call with Body Example Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/klaim.md Shows how to register a POST route and call it with a request body using the Klaim runtime. ```typescript Api.create("posts", "https://jsonplaceholder.typicode.com", () => { Route.post("create", "/posts"); }); const created = await Klaim.posts.create( {}, { title: "Hello", body: "From Klaim", userId: 1 } ); ``` -------------------------------- ### Routes with Caching Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Illustrates how to enable caching for routes using the `withCache` method, specifying cache duration in seconds. ```APIDOC ### Routes with Caching ```typescript Api.create("api", "https://api.example.com", () => { // Cache for 5 minutes Route.get("listProducts", "/products").withCache(300); // Cache for 1 hour Route.get("getProduct", "/products/[id]").withCache(3600); // No cache (POST) Route.post("createProduct", "/products"); }); ``` ``` -------------------------------- ### Static Route Helpers Example Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/route.md Demonstrates how to use static helper methods like Route.get and Route.post to define API routes within an Api.create context. ```typescript Api.create("users", "https://example.com", () => { Route.get("list", "/users"); Route.get("getOne", "/users/[id]"); Route.post("create", "/users", { Authorization: "Bearer token" }); }); ``` -------------------------------- ### Configuration Type Composition Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/types.md Demonstrates composing multiple configuration types like rate limiting, timeout, and pagination for route definitions. ```typescript // Create strongly-typed configuration const rateLimitConfig: IRateLimitConfig = { limit: 10, duration: 60 }; const timeoutConfig: ITimeoutConfig = { duration: 30, message: "Request exceeded 30 seconds" }; const paginationConfig: IPaginationConfig = { page: 1, pageParam: "page_number", limit: 50, limitParam: "per_page" }; Route.get("items", "/items") .withRate(rateLimitConfig) .withTimeout(timeoutConfig.duration, timeoutConfig.message) .withPagination(paginationConfig); ``` -------------------------------- ### Timeout Usage Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/types.md Demonstrates how to apply timeout configurations to routes and APIs using the withTimeout method. ```typescript Route.get("slow", "/slow") .withTimeout(10, "API took too long"); Api.create("api", "https://api.example.com", () => { Route.get("endpoint", "/endpoint"); }).withTimeout(15); ``` -------------------------------- ### Configuration Levels Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/configuration.md Demonstrates how API, Group, and Route level configurations are applied and inherited. More specific levels override less specific ones. ```typescript Api.create("api", "https://api.example.com", () => { Group.create("users", () => { Route.get("list", "/users"); // Inherits from group Route.get("getOne", "/users/[id]") // Can override group config .withCache(600); // Route-level override }).withCache(120); // Group-level cache }).withCache(60); // API-level cache (fallback) ``` -------------------------------- ### Routes with Middleware Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Illustrates adding middleware to routes using `before` and `after` callbacks to intercept and modify requests or responses. ```APIDOC ### Routes with Middleware ```typescript Api.create("api", "https://api.example.com", () => { Route.get("data", "/data") .before(({url, config}) => { config.headers["Authorization"] = `Bearer ${getToken()}`; return {url, config}; }) .after(({data}) => { return {data: {processed: true, ...data}}; }); }); ``` ``` -------------------------------- ### Route Call with Body Example Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/klaim.md Demonstrates calling a route that requires a request body, such as a POST request. ```APIDOC ## Route Call with Body Example ### Description Demonstrates calling a route that requires a request body, such as a POST request. ### Method Not applicable (SDK method call) ### Endpoint Not applicable (SDK method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The title of the post. - **body** (string) - Required - The content of the post. - **userId** (number) - Required - The ID of the user creating the post. ### Request Example ```typescript const created = await Klaim.posts.create( {}, { title: "Hello", body: "From Klaim", userId: 1 } ); ``` ### Response #### Success Response - **created** - The created post object. #### Response Example None provided in source. ``` -------------------------------- ### Before Hook Example Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/route.md Illustrates using the .before() hook to modify request configuration, such as adding an Authorization header. ```typescript Route.get("profile", "/me").before(({ route, api, url, config }) => { return { route, api, url, config: { ...config, headers: { ...(config.headers as Record), Authorization: `Bearer ${token}`, }, }, }; }); ``` -------------------------------- ### Define and Call a Basic Route Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Klaim.md Sets up a simple GET route for fetching a list of users and demonstrates how to call it. Requires importing Klaim, Api, and Route. ```typescript import { Klaim, Api, Route } from 'klaim'; // Setup Api.create("users", "https://api.example.com", () => { Route.get("list", "/users"); }); // Usage const users = await Klaim.users.list(); ``` -------------------------------- ### Example Usage of IBody Source: https://github.com/antharuu/klaim/blob/main/_autodocs/types.md Shows how to create and use an IBody object for sending data in an API request. ```typescript const body: IBody = {name: 'John', email: 'john@example.com'}; await Klaim.api.createUser({}, body); ``` -------------------------------- ### Example Usage of IPaginationConfig Source: https://github.com/antharuu/klaim/blob/main/_autodocs/types.md Shows how to configure custom pagination settings like 'offset' for page and 'per_page' for limit, and apply it to a route definition. ```typescript const config: IPaginationConfig = { page: 1, pageParam: "offset", limit: 20, limitParam: "per_page" }; Route.get("items", "/items").withPagination(config); ``` -------------------------------- ### Callback Examples Source: https://github.com/antharuu/klaim/blob/main/_autodocs/types.md Illustrates how to define before and after callbacks for modifying request configurations or transforming response data. Ensure the correct argument types are used. ```typescript const beforeCallback: ICallback = ({config}) => { config.headers.Authorization = getToken(); return {config}; }; const afterCallback: ICallback = ({data}) => { return {data: transformData(data)}; }; ``` -------------------------------- ### Routes with Rate Limiting Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Demonstrates how to implement rate limiting for routes using the `withRate` method, specifying the request limit and duration. ```APIDOC ### Routes with Rate Limiting ```typescript Api.create("api", "https://api.example.com", () => { // 2 requests per 60 seconds Route.get("expensive", "/expensive-endpoint") .withRate({limit: 2, duration: 60}); }); ``` ``` -------------------------------- ### Routes with Retry and Timeout Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Shows how to configure automatic retries and request timeouts for routes using `withRetry` and `withTimeout` methods. ```APIDOC ### Routes with Retry and Timeout ```typescript Api.create("api", "https://api.example.com", () => { Route.get("unreliable", "/unreliable") .withRetry(5) .withTimeout(10); }); ``` ``` -------------------------------- ### Cache Eviction Policy Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Cache.md Demonstrates how items are added and accessed, affecting their position in the LRU cache and potential eviction. ```typescript Cache.i.set("A", 1); Cache.i.set("B", 2); Cache.i.set("C", 3); // Access A (moves to end) Cache.i.get("A"); // Order now: B, C, A // Add D, if cache is full, B would be evicted Cache.i.set("D", 4); // Order now: C, A, D ``` -------------------------------- ### Chained Configuration Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Illustrates the use of method chaining to apply multiple configurations (caching, retry, timeout, rate limiting, middleware) to a single route. ```APIDOC ### Chained Configuration ```typescript Route.post("createItem", "/items") .withCache(300) .withRetry(3) .withTimeout(10) .withRate({limit: 5, duration: 10}) .before(({config}) => { config.headers["X-Custom"] = "value"; return {config}; }); ``` ``` -------------------------------- ### Rate Limiting Examples Source: https://github.com/antharuu/klaim/blob/main/_autodocs/types.md Demonstrates how to apply rate limiting to routes and APIs. Custom limits can be set, or default values can be used. ```typescript // 2 requests per 60 seconds Route.get("expensive", "/expensive") .withRate({limit: 2, duration: 60}); // 5 requests per 10 seconds (default) Api.create("api", "https://api.example.com", () => { Route.get("endpoint", "/endpoint"); }).withRate(); ``` -------------------------------- ### Cache with TTL Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Cache.md Shows how to set a Time-To-Live (TTL) for cache entries, causing them to expire after a specified duration. ```typescript // Cache for 1 minute (60000ms) Cache.i.set("token", authToken, 60000); // After 60 seconds, this will return null const expired = Cache.i.get("token"); ``` -------------------------------- ### Example Usage of Klaim Types Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/types.md Demonstrates how to import and use common Klaim types like IArgs, IRateLimitConfig, and ITimeoutConfig in a TypeScript project. ```typescript import type { IArgs, IRateLimitConfig, ITimeoutConfig } from "klaim"; const routeArgs: IArgs = { id: 1 }; const rate: IRateLimitConfig = { limit: 5, duration: 10 }; const timeout: ITimeoutConfig = { duration: 2, message: "Too slow" }; ``` -------------------------------- ### Creating Basic Routes Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Define standard HTTP routes (GET, POST, PUT, DELETE) with their respective paths within an API instance. ```typescript Api.create("api", "https://api.example.com", () => { Route.get("list", "/items"); Route.get("getOne", "/items/[id]"); Route.post("create", "/items"); Route.put("update", "/items/[id]"); Route.delete("delete", "/items/[id]"); }); ``` -------------------------------- ### Paginated Route Call Example Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/klaim.md Demonstrates calling a paginated route, specifying the offset for retrieving data pages. ```APIDOC ## Paginated Route Call Example ### Description Demonstrates calling a paginated route, specifying the offset for retrieving data pages. ### Method Not applicable (SDK method call) ### Endpoint Not applicable (SDK method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **offset** (number) - Required - The offset for pagination (e.g., 0 for the first page, 5 for the second page if limit is 5). ### Request Example ```typescript const firstPage = await Klaim.pokemon.list(0); const secondPage = await Klaim.pokemon.list(5); ``` ### Response #### Success Response - **firstPage** - The data for the first page of results. - **secondPage** - The data for the second page of results. #### Response Example None provided in source. ``` -------------------------------- ### Klaim API with Cache Example Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/cache.md Demonstrates configuring a Klaim API with a cache and making a cached request. It also shows how to check the cache size after the request. ```typescript Api.create("catalog", "https://dummyjson.com", () => { Route.get("listProducts", "/products"); }).withCache(60); await Klaim.catalog.listProducts(); console.log(Cache.i.size); ``` -------------------------------- ### Routes with Validation Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Shows how to apply validation schemas to routes using the `validate` method, ensuring request data conforms to expected structures. ```APIDOC ### Routes with Validation ```typescript import * as yup from 'yup'; const todoSchema = yup.object().shape({ id: yup.number().required(), title: yup.string().required(), completed: yup.boolean().required() }); Api.create("api", "https://api.example.com", () => { Route.get("getTodo", "/todos/[id]").validate(todoSchema); }); ``` ``` -------------------------------- ### Route with URL Parameters Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Klaim.md Defines a GET route to fetch a single user by ID, demonstrating the use of URL parameters. ```APIDOC ## GET /users/[id] ### Description Fetches a single user by their ID. ### Method GET ### Endpoint /users/[id] ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the user to retrieve. ### Request Example ```json { "id": 123 } ``` ### Response #### Success Response (200) - **data** (object) - The user object. ### Response Example ```json { "id": 123, "name": "Jane Doe" } ``` ``` -------------------------------- ### Registering APIs and Routes in Tests Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Registry.md Demonstrates how to use the Registry to register APIs and routes within a testing environment. It includes setup and cleanup for each test case. ```typescript import { Registry, Api, Route } from 'klaim'; describe("API Registry", () => { beforeEach(() => { // Clear registry before each test Registry.i.reset(); }); it("registers APIs and routes", () => { Api.create("test", "https://test.com", () => { Route.get("endpoint", "/endpoint"); }); const route = Registry.i.getRoute("test", "endpoint"); expect(route).toBeDefined(); expect(route?.url).toBe("endpoint"); }); it("maintains hierarchy", () => { Api.create("api", "https://api.com", () => { Route.get("route1", "/route1"); Route.get("route2", "/route2"); }); const children = Registry.i.getChildren("api"); expect(children.length).toBe(2); }); afterEach(() => { // Clean up after test Registry.i.reset(); }); }); ``` -------------------------------- ### Runtime Controls Example Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/route.md Combines multiple runtime control methods like .withRate(), .withRetry(), .withTimeout(), and .withCache() for a single route. ```typescript Route.get("expensive", "/reports/[id]") .withRate({ limit: 2, duration: 60 }) .withRetry(1) .withTimeout(5) .withCache(120); ``` -------------------------------- ### RouteMethod Enum Usage Examples Source: https://github.com/antharuu/klaim/blob/main/_autodocs/types.md Illustrates direct usage of the RouteMethod enum and preferred static shortcut methods for route creation. ```typescript // Using enum directly const route = new Route("name", "/path", {}, RouteMethod.GET); // Using static shortcuts (preferred) Route.get("name", "/path"); Route.post("name", "/path"); Route.put("name", "/path"); Route.delete("name", "/path"); Route.patch("name", "/path"); Route.options("name", "/path"); ``` -------------------------------- ### Cache Key Generation Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Cache.md Illustrates how cache keys are generated by hashing the URL and request configuration. This ensures unique keys for identical requests. ```typescript const cacheKey = hashStr(`${url}${JSON.stringify(config)}`); ``` -------------------------------- ### Define Route with Pagination and Validation Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/guides/pagination-validation-and-observability.md Defines a GET route for fetching a list of items, enabling pagination with specified parameters and validating the response against a defined schema using Yup. This setup ensures that paginated requests adhere to a consistent structure and data format. ```typescript import { Api, Route } from "klaim"; import * as yup from "yup"; const pokemonListSchema = yup.object({ results: yup.array( yup.object({ name: yup.string().required(), }) ).required(), }); Api.create("pokemon", "https://pokeapi.co/api/v2", () => { Route.get("list", "/pokemon") .withPagination({ pageParam: "offset", limitParam: "limit", limit: 5 }) .validate(pokemonListSchema); }); ``` -------------------------------- ### Create API Declaration Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/api.md Example of creating and registering an API declaration with a basic route. The callback is used to register routes or nested groups. ```typescript import { Api, Route } from "klaim"; Api.create("billing-api", "https://api.example.com", () => { Route.get("listInvoices", "/invoices"); }); ``` -------------------------------- ### Basic API Configuration with Routes Source: https://github.com/antharuu/klaim/blob/main/README.md Configure a new API named 'hello' with a base URL and define its routes using Route.get and Route.post. This sets up the fundamental structure for interacting with an API. ```typescript import {Api, Route} from 'klaim'; // For deno: import { Api, Route } from "@antharuu/klaim"; // Your simple Todo type type Todo = { userId: number; id: number; title: string; completed: boolean; }; // Create a new API with the name "hello" and the base URL "https://jsonplaceholder.typicode.com/" Api.create("hello", "https://jsonplaceholder.typicode.com/", () => { // Define routes for the API Route.get("listTodos", "todos"); Route.get("getTodo", "todos/[id]"); Route.post("addTodo", "todos"); }); ``` -------------------------------- ### Example Usage with Klaim API and Hook Subscription Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/hook.md Demonstrates setting up an API with routes and subscribing to a hook for a specific route. The hook executes after the API call is completed. ```typescript Api.create("inventory", "https://dummyjson.com", () => { Route.get("listProducts", "/products"); }); Hook.subscribe("inventory.listProducts", () => { console.log("request completed"); }); await Klaim.inventory.listProducts(); ``` -------------------------------- ### Define API and Routes Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-and-routes.md Define a base API URL and then declare GET routes for listing and retrieving users. This sets up a structured way to interact with a RESTful API. ```typescript import { Api, Klaim, Route } from "klaim"; type User = { id: number; name: string; }; Api.create("usersApi", "https://jsonplaceholder.typicode.com", () => { Route.get("listUsers", "/users"); Route.get("getUser", "/users/[id]"); }); const users = await Klaim.usersApi.listUsers(); const one = await Klaim.usersApi.getUser({ id: 1 }); ``` -------------------------------- ### Define API and Fetch Todos Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/index.md Defines a 'todos' API with a base URL and registers GET routes for listing all todos and getting a single todo by ID. It then demonstrates fetching data using the defined API. ```typescript import { Api, Klaim, Route } from "klaim"; type Todo = { userId: number; id: number; title: string; completed: boolean; }; Api.create("todos", "https://jsonplaceholder.typicode.com", () => { Route.get("list", "/todos"); Route.get("getOne", "/todos/[id]"); }); const items = await Klaim.todos.list(); const first = await Klaim.todos.getOne({ id: 1 }); ``` -------------------------------- ### Quick Start: Fetch Single Todo Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/index.md Sets up a minimal Klaim client to fetch a single todo item by its ID from the JSONPlaceholder API. Demonstrates defining an API, a route with a path parameter, and making a request. ```typescript import { Api, Klaim, Route } from "klaim"; type Todo = { id: number; title: string; completed: boolean; }; Api.create("jsonPlaceholder", "https://jsonplaceholder.typicode.com", () => { Route.get("getTodo", "/todos/[id]"); }); const todo = await Klaim.jsonPlaceholder.getTodo({ id: 1 }); console.log(todo.id, todo.title, todo.completed); ``` -------------------------------- ### Route.delete() Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Creates a DELETE route for removing a user by ID. ```typescript Route.delete("deleteUser", "/users/[id]"); ``` -------------------------------- ### Route.put() Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Creates a PUT route for updating a user by ID. ```typescript Route.put("updateUser", "/users/[id]"); ``` -------------------------------- ### getChildren Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Registry.md Gets all child elements associated with a given parent path in the registry. ```APIDOC ## getChildren(elementPath) ### Description Gets all child elements for a given parent path. ### Method `getChildren(elementPath: string): IElement[]` ### Parameters #### Path Parameters - **elementPath** (string) - Required - Full path to the parent element ### Returns Array of child elements ### Example ```typescript const children = registry.getChildren("api"); // Returns all routes and groups directly under "api" ``` ``` -------------------------------- ### Get Current Cache Size Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Cache.md Retrieve the number of entries currently stored in the cache. ```typescript console.log(`Cache size: ${Cache.i.size}`); ``` -------------------------------- ### Route.patch() Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Creates a PATCH route for updating a user's status by ID. ```typescript Route.patch("updateUserStatus", "/users/[id]/status"); ``` -------------------------------- ### Basic API Setup with Klaim Source: https://github.com/antharuu/klaim/blob/main/_autodocs/README.md Define API endpoints and their routes using the Api and Route classes. This sets up the structure for making requests to a specific base URL. ```typescript import { Api, Route } from 'klaim'; Api.create("users", "https://api.example.com", () => { Route.get("list", "/users"); Route.get("getOne", "/users/[id]"); Route.post("create", "/users"); }); ``` -------------------------------- ### Get Registry Singleton Instance Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/registry.md Access the singleton instance of the Registry using the static `i` getter. ```typescript const registry = Registry.i; ``` -------------------------------- ### Create a Simple API with Routes Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Api.md Use Api.create to define a new API with a name, base URL, and a callback function to configure its routes. This example shows a basic API for user management. ```typescript import { Api, Route } from 'klaim'; // Simple API with routes Api.create("users", "https://api.users.com", () => { Route.get("list", "/users"); Route.get("getOne", "/users/[id]"); Route.post("create", "/users"); }); ``` -------------------------------- ### get() Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Cache.md Retrieves a value from the cache if it exists and has not expired. Accessing an item moves it to the most recently used position. ```APIDOC ## get() Retrieves a value from the cache if it exists and hasn't expired. ```typescript public get(key: string): unknown | null ``` **Parameters**: | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | key | string | Yes | The key of the cached item to retrieve | **Returns**: The cached value if valid, `null` otherwise **Details**: - Returns null for non-existent entries - Returns null for expired entries (and removes them) - Moves the accessed entry to the most recent position (LRU optimization) - Used internally by `fetchWithCache` to implement response caching **Example**: ```typescript const userData = Cache.i.get("userProfile"); if (userData) { // Use cached data console.log(userData); } else { // Handle cache miss console.log("Not in cache"); } ``` ``` -------------------------------- ### Access Singleton Cache Instance Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Cache.md Get the singleton instance of the Cache. The instance is created if it doesn't exist. ```typescript const cache = Cache.i; cache.set("key", "value", 60000); const value = cache.get("key"); ``` -------------------------------- ### Testing Cache Functionality Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Cache.md Provides an example of how to test cache behavior, including clearing the cache before and after each test. ```typescript import { Cache } from 'klaim'; describe("API Caching", () => { beforeEach(() => { // Clear cache before each test Cache.i.clear(); }); it("caches responses", async () => { const key = "test_response"; const data = {id: 1, name: "Test"}; Cache.i.set(key, data, 60000); const cached = Cache.i.get(key); expect(cached).toEqual(data); }); afterEach(() => { // Clean up after test Cache.i.clear(); }); }); ``` -------------------------------- ### Register API and Route Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/registry.md Demonstrates registering an API with a route using `Api.create` and `Route.get`, then retrieving the registered route using the registry. This shows the typical flow of defining and accessing routes. ```typescript Api.create("service", "https://example.com", () => { Route.get("health", "/health"); }); console.log(Registry.i.getRoute("service", "health")); ``` -------------------------------- ### Access Singleton Registry Instance Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Registry.md Get the singleton instance of the Registry. This is typically used internally for API management. ```typescript const registry = Registry.i; registry.registerElement(apiElement); ``` -------------------------------- ### Method Chaining Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Element.md Demonstrates how to chain multiple configuration methods together for complex Element configurations. ```APIDOC ## Method Chaining All configuration methods return `this`, allowing you to chain multiple configurations: ```typescript Route.get("complex", "/complex/[id]") .withCache(300) .withRetry(3) .withTimeout(10) .withRate({limit: 5, duration: 10}) .withPagination({limit: 20}) .before(({config}) => { config.headers["Authorization"] = "Bearer token"; return {config}; }) .after(({data}) => { return {data: transformData(data)}; }); ``` ``` -------------------------------- ### Basic Caching Operations Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Cache.md Illustrates storing data in the cache with a TTL and retrieving it using 'has' and 'get' methods. ```typescript const data = "Some data"; const key = "myKey"; // Store in cache for 5 minutes Cache.i.set(key, data, 300000); // Check if in cache if (Cache.i.has(key)) { const cached = Cache.i.get(key); console.log("From cache:", cached); } ``` -------------------------------- ### Basic Route Call Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Klaim.md Defines a simple GET route for listing users and shows how to call it to fetch data. ```APIDOC ## GET /users ### Description Fetches a list of users. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **data** (array) - A list of user objects. ### Response Example ```json { "data": [ { "id": 1, "name": "John Doe" } ] } ``` ``` -------------------------------- ### Route.options() Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Creates an OPTIONS route. This is a static shortcut for defining OPTIONS requests. ```APIDOC ## Route.options() ### Description Creates an OPTIONS route. This is a static shortcut for defining OPTIONS requests. ### Method `public static options(name: string, url: string, headers?: IHeaders): Element` ### Parameters #### Path Parameters - **name** (string) - Required - Route name - **url** (string) - Required - Route URL path - **headers** (IHeaders) - Optional - Route-specific headers ### Request Example ```typescript Route.options("userOptions", "/users"); ``` ``` -------------------------------- ### Pagination Configuration Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/route.md Demonstrates configuring a route for pagination using .withPagination(), specifying parameter names and default limit. ```typescript Route.get("list", "/pokemon").withPagination({ pageParam: "offset", limitParam: "limit", limit: 20, }); ``` -------------------------------- ### Example Usage of IArgs Source: https://github.com/antharuu/klaim/blob/main/_autodocs/types.md Demonstrates how to create and use an IArgs object for making an API call with dynamic parameters. ```typescript const args: IArgs = {id: 123, status: 'active'}; await Klaim.api.searchUsers(args); ``` -------------------------------- ### Calling Klaim API Routes Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Demonstrates various ways to call Klaim API routes. Use these examples for routes without parameters, with URL parameters, with request bodies, for pagination, and for combined scenarios. ```typescript // Without parameters const items = await Klaim.api.listItems(); // With URL parameters const item = await Klaim.api.getItem({id: 1}); // With body (POST/PUT/PATCH) const newItem = await Klaim.api.createItem( {}, // args (empty if no URL params) {name: "New Item", description: "..."} // body ); // Paginated const page2 = await Klaim.api.listItems(2); // Combined const page2Items = await Klaim.api.searchItems( 2, // page {query: "search term"}, // args {} // body (empty if not needed) ); ``` -------------------------------- ### Cache Invalidation Example Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Cache.md Demonstrates how to invalidate a cache entry by updating its value, effectively refreshing the cached data. ```typescript // After updating data, clear the cache Cache.i.set("userData", originalData, 600000); // Update the data updateUserData(newData); // Invalidate cache by setting new value Cache.i.set("userData", newData, 600000); ``` -------------------------------- ### Configuring Route Caching Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Route.md Enable caching for GET routes by specifying a duration in seconds. POST requests do not support caching. ```typescript // Cache for 5 minutes Route.get("listProducts", "/products").withCache(300); // Cache for 1 hour Route.get("getProduct", "/products/[id]").withCache(3600); // No cache (POST) Route.post("createProduct", "/products"); ``` -------------------------------- ### Handling Expired Cache Items Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Cache.md Illustrates how the cache behaves when an item has expired, returning false for 'has' and null for 'get'. ```typescript // Cache for 1 second Cache.i.set("shortLived", "data", 1000); // Immediately available console.log(Cache.i.has("shortLived")); // true console.log(Cache.i.get("shortLived")); // "data" // After 1.1 seconds setTimeout(() => { console.log(Cache.i.has("shortLived")); // false console.log(Cache.i.get("shortLived")); // null }, 1100); ``` -------------------------------- ### Chaining Multiple Configurations Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Element.md Demonstrates chaining multiple configuration methods (`withCache`, `withRetry`, `withTimeout`, `withRate`, `withPagination`, `before`, `after`) on a single route element. ```typescript Route.get("complex", "/complex/[id]") .withCache(300) .withRetry(3) .withTimeout(10) .withRate({limit: 5, duration: 10}) .withPagination({limit: 20}) .before(({config}) => { config.headers["Authorization"] = "Bearer token"; return {config}; }) .after(({data}) => { return {data: transformData(data)}; }); ``` -------------------------------- ### Get Child Elements Source: https://github.com/antharuu/klaim/blob/main/_autodocs/api-reference/Registry.md Retrieves all direct child elements of a specified parent element path. Useful for exploring the registry structure. ```typescript public getChildren(elementPath: string): IElement[] ``` ```typescript const children = registry.getChildren("api"); // Returns all routes and groups directly under "api" ``` -------------------------------- ### Import Registry Singleton Source: https://github.com/antharuu/klaim/blob/main/docs/codedocs/api-reference/registry.md Import the Registry singleton from the 'klaim' package. ```typescript import { Registry } from "klaim"; ```