### Install fetchdts Package Source: https://github.com/unjs/fetchdts/blob/main/README.md Installs the fetchdts package using npm or pnpm. This is the initial step to integrate fetchdts into your project for building typed APIs. ```sh # npm npm install fetchdts # pnpm pnpm install fetchdts ``` -------------------------------- ### fetchdts HTTP Methods Support Example (TypeScript) Source: https://github.com/unjs/fetchdts/blob/main/README.md Illustrates how to define API endpoints supporting various HTTP methods within a fetchdts schema. It covers standard methods like GET, POST, PUT, DELETE, PATCH, and less common ones like OPTIONS, HEAD, CONNECT, TRACE. ```ts interface RESTSchema { '/api/users': { [Endpoint]: { GET: { response: User[] } POST: { body: CreateUser, response: User } } [DynamicParam]: { [Endpoint]: { GET: { response: User } PUT: { body: UpdateUser, response: User } PATCH: { body: Partial, response: User } DELETE: { response: { success: boolean } } } } } } ``` -------------------------------- ### Handling Mixed Static and Dynamic Routes Source: https://github.com/unjs/fetchdts/blob/main/README.md Illustrates how FetchDTS supports complex API structures with both static and dynamic routes. The example defines a schema with nested static and dynamic paths, showcasing typed requests for various endpoints. ```typescript interface APISchema { '/api': { '/health': { [Endpoint]: { GET: { response: { status: 'ok' | 'error' } } } } '/users': { [Endpoint]: { GET: { response: User[] } POST: { body: CreateUser, response: User } } [DynamicParam]: { [Endpoint]: { GET: { response: User } PUT: { body: UpdateUser, response: User } DELETE: { response: { deleted: boolean } } } '/posts': { [Endpoint]: { GET: { response: Post[] } } [DynamicParam]: { [Endpoint]: { GET: { response: Post } } } } } } } } // All of these are now typed: await api('/api/health') // { status: 'ok' | 'error' } await api('/api/users') // User[] await api('/api/users/123') // User await api('/api/users/123/posts') // Post[] await api('/api/users/123/posts/456') // Post ``` -------------------------------- ### fetchdts Schema Definition Example (TypeScript) Source: https://github.com/unjs/fetchdts/blob/main/README.md Illustrates the basic structure for defining an API schema in fetchdts. It shows how to map paths to HTTP methods and specify query parameters, request bodies, headers, and response structures. ```ts interface Schema { '/path': { [Endpoint]: { [HTTPMethod]: { query?: { param: string } // Query parameters body?: { data: any } // Request body headers?: { auth: string } // Required headers response: { result: any } // Response data responseHeaders?: { 'x-rate-limit': string } // Response headers } } } } ``` -------------------------------- ### fetchdts Core Symbols and Schema Definition Source: https://context7.com/unjs/fetchdts/llms.txt Demonstrates the core symbols (`Endpoint`, `DynamicParam`, `WildcardParam`) used to define API route structures and an example API schema. ```APIDOC ## Core Symbols and Schema Definition ### Description This section explains the core symbols used in `fetchdts` to define API route structures and provides an example of an API schema definition. ### Symbols - `Endpoint`: Marks where HTTP methods are defined. - `DynamicParam`: Matches single path segments (e.g., `/users/:id`). - `WildcardParam`: Matches multiple path segments (e.g., `/api/**`). ### Request Example ```typescript import type { DynamicParam, Endpoint, WildcardParam } from 'fetchdts' interface APISchema { '/api': { '/users': { [Endpoint]: { GET: { response: User[] } POST: { body: { name: string }, response: User } } [DynamicParam]: { // Matches /api/users/:id [Endpoint]: { GET: { response: User } PUT: { body: Partial, response: User } DELETE: { response: { success: boolean } } } } } [WildcardParam]: { // Matches /api/** [Endpoint]: { GET: { response: unknown } } } } } ``` ### Response (No specific response defined for this conceptual example, focuses on schema definition.) ``` -------------------------------- ### Typed Headers and Query Parameters Usage Source: https://github.com/unjs/fetchdts/blob/main/README.md Example of using FetchDTS with typed query parameters, headers, and response headers. It defines an API schema and demonstrates making a request with required query parameters and headers, then accessing typed response headers. ```typescript interface APISchema { '/search': { [Endpoint]: { GET: { query: { q: string, limit?: number } headers: { 'x-api-key': string } response: { results: string[], total: number } responseHeaders: { 'x-rate-limit-remaining': string } } } } } // Usage with required query and headers const results = await api('/search', { query: { q: 'typescript', limit: 10 }, headers: { 'x-api-key': 'your-key' } }) // Access typed response headers const rateLimit = results.headers.get('x-rate-limit-remaining') // string | null ``` -------------------------------- ### TypeScript API Client with fetchdts Source: https://context7.com/unjs/fetchdts/llms.txt This example demonstrates how to combine fetchdts types to create a fully typed API client with error handling. It defines data models, an API schema, and a generic fetch wrapper function for type-safe API interactions. ```typescript import type { DynamicParam, Endpoint, TypedFetchInput, TypedFetchRequestInit, TypedFetchResponseBody, TypedResponse } from 'fetchdts' // Define your data models interface User { id: number name: string email: string } interface Post { id: number userId: number title: string body: string } // Define your API schema interface APISchema { '/api': { '/users': { [Endpoint]: { GET: { query?: { limit?: number, offset?: number } response: User[] responseHeaders: { 'x-total-count': string } } POST: { body: { name: string, email: string } headers: { authorization: string } response: User } } [DynamicParam]: { [Endpoint]: { GET: { response: User } PUT: { body: Partial> headers: { authorization: string } response: User } DELETE: { headers: { authorization: string } response: { success: boolean } } } '/posts': { [Endpoint]: { GET: { response: Post[] } } } } } } } // Create the typed API client async function api>( input: T, init?: TypedFetchRequestInit ): Promise>> { const response = await fetch(`https://api.example.com${input}`, init as RequestInit) if (!response.ok) { throw new Error(`API Error: ${response.status} ${response.statusText}`) } return response as TypedResponse> } // Usage examples with full type safety async function main() { // GET all users - response is User[] const usersResponse = await api('/api/users') const totalCount = usersResponse.headers.get('x-total-count') const users = await usersResponse.json() console.log(`Total users: ${totalCount}`, users) // POST create user - body and headers are required and typed const newUser = await api('/api/users', { method: 'POST', body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' }), headers: { authorization: 'Bearer token123' } }).then(r => r.json()) console.log('Created user:', newUser.id, newUser.name) // GET single user - response is User const user = await api('/api/users/1').then(r => r.json()) console.log('User:', user.name, user.email) // PUT update user - partial body allowed const updatedUser = await api('/api/users/1', { method: 'PUT', body: JSON.stringify({ name: 'Alice Smith' }), headers: { authorization: 'Bearer token123' } }).then(r => r.json()) console.log('Updated:', updatedUser.name) // GET user's posts - response is Post[] const posts = await api('/api/users/1/posts').then(r => r.json()) console.log('Posts:', posts.map(p => p.title)) // DELETE user - response is { success: boolean } const deleteResult = await api('/api/users/1', { method: 'DELETE', headers: { authorization: 'Bearer token123' } }).then(r => r.json()) console.log('Deleted:', deleteResult.success) } ``` -------------------------------- ### Error Handling Schema Design in TypeScript Source: https://github.com/unjs/fetchdts/blob/main/README.md Illustrates how to design an APISchema interface in TypeScript to handle potential errors from API responses. This example defines a structure for user data retrieval, including success and error states, enabling type-safe access to response data. ```typescript interface APISchema { '/api/users': { [DynamicParam]: { [Endpoint]: { GET: { response: | { success: true, data: User } | { success: false, error: string, code: number } } } } } } // Usage const result = await api('/api/users/123') if (result.success) { console.log(result.data.name) // ✅ Type-safe access } else { console.error(`Error ${result.code}: ${result.error}`) } ``` -------------------------------- ### TypedURLSearchParams Source: https://context7.com/unjs/fetchdts/llms.txt TypedURLSearchParams provides type-safe access to URL search parameters with typed get, set, append, has, and delete methods. ```APIDOC ## TypedURLSearchParams ### Description Provides type-safe access to URL search parameters with typed `get`, `set`, `append`, `has`, and `delete` methods. ### Usage Example ```typescript import type { TypedURLSearchParams } from 'fetchdts' interface SearchParams { q: string page: string limit: string sort: 'asc' | 'desc' } type SearchQueryParams = TypedURLSearchParams function buildSearchURL(params: SearchQueryParams): string { // get() returns typed value or null const query = params.get('q') // Type: string | null const sort = params.get('sort') // Type: 'asc' | 'desc' | null // set() accepts typed values params.set('page', '1') params.set('limit', '10') // has() checks for parameter existence if (!params.has('sort')) { params.append('sort', 'desc') } return params.toString() } ``` ``` -------------------------------- ### TypedHeaders: Type-Safe HTTP Header Access Source: https://context7.com/unjs/fetchdts/llms.txt TypedHeaders offers type-safe access to HTTP headers. It supports all standard header methods like get, set, append, has, delete, and forEach, with type inference for header names and values. ```typescript import type { TypedHeaders } from 'fetchdts' interface CustomHeaderMap { 'content-type': 'application/json' | 'text/plain' 'authorization': `Bearer ${string}` 'x-api-key': string } type CustomHeaders = TypedHeaders function processHeaders(headers: CustomHeaders) { // get() returns typed value or null const contentType = headers.get('content-type') // Type: 'application/json' | 'text/plain' | null const auth = headers.get('authorization') // Type: `Bearer ${string}` | null // has() checks for header existence if (headers.has('x-api-key')) { const apiKey = headers.get('x-api-key') // Type: string | null } // forEach with typed key/value pairs headers.forEach((value, key) => { // key: 'content-type' | 'authorization' | 'x-api-key' | string // value: typed based on header name console.log(`${key}: ${value}`) }) // Unknown headers fall back to string const unknown = headers.get('x-unknown') // Type: string | null } ``` -------------------------------- ### Path Types Source: https://github.com/unjs/fetchdts/blob/main/README.md Illustrates how to define static, dynamic, and wildcard paths within your API schema. ```APIDOC ## Path Types **Static Paths**: Exact string matches ```ts interface Schema { '/api/users': { [Endpoint]: { GET: { response: User[] } } } } ``` **Dynamic Parameters**: Single path segments ```ts interface Schema { '/api/users': { [DynamicParam]: { // matches /api/users/123, /api/users/abc, etc. [Endpoint]: { GET: { response: User } } } } } ``` **Wildcard Parameters**: Multiple path segments ```ts interface Schema { '/api': { [WildcardParam]: { // matches /api/anything/nested/deep [Endpoint]: { GET: { response: any } } } } } ``` ``` -------------------------------- ### fetchdts Path Types: Static, Dynamic, and Wildcard (TypeScript) Source: https://github.com/unjs/fetchdts/blob/main/README.md Explains and demonstrates the use of static, dynamic, and wildcard path types within fetchdts schemas. Static paths match exactly, DynamicParam matches single segments (like /users/:id), and WildcardParam matches multiple segments (like /api/*). ```ts interface Schema { '/api/users': { [Endpoint]: { GET: { response: User[] } } } } interface Schema { '/api/users': { [DynamicParam]: { // matches /api/users/123, /api/users/abc, etc. [Endpoint]: { GET: { response: User } } } } } interface Schema { '/api': { [WildcardParam]: { // matches /api/anything/nested/deep [Endpoint]: { GET: { response: any } } } } } ``` -------------------------------- ### Typed Fetch Request Initialization with TypeScript Source: https://context7.com/unjs/fetchdts/llms.txt Shows how `TypedFetchRequestInit` provides typed request options for specific API paths. It infers types for `method`, `body`, `headers`, and `query` parameters based on the defined schema, enhancing type safety for fetch requests. ```typescript import type { DynamicParam, Endpoint, TypedFetchInput, TypedFetchRequestInit } from 'fetchdts' interface APISchema { '/users': { [Endpoint]: { GET: { response: User[] } POST: { body: { name: string, email: string } headers: { authorization: string } response: User } } [DynamicParam]: { [Endpoint]: { PUT: { body: { name?: string, email?: string } response: User } } } } } async function api>(input: T, init?: TypedFetchRequestInit) { return fetch(input, init as RequestInit) } // GET request - method is optional since GET is the default await api('/users') // POST request - method is required, body and headers are typed await api('/users', { method: 'POST', body: JSON.stringify({ name: 'John', email: 'john@example.com' }), headers: { authorization: 'Bearer token123' } }) // PUT request on dynamic path await api('/users/123', { method: 'PUT', body: JSON.stringify({ name: 'Jane' }) }) ``` -------------------------------- ### fetchdts TypedFetchRequestInit Source: https://context7.com/unjs/fetchdts/llms.txt Illustrates how `TypedFetchRequestInit` provides typed request options (method, body, headers, query) for a specific API path based on the defined schema. ```APIDOC ## TypedFetchRequestInit ### Description `TypedFetchRequestInit` generates type-safe request options for a specific API endpoint path defined in your schema. It ensures that the `method`, `body`, `headers`, and `query` parameters conform to the schema's requirements for that particular path and HTTP method. ### Type Definition `TypedFetchRequestInit` ### Parameters - **Schema**: The API schema interface. - **Path**: The specific URL path for which to generate request options. ### Request Example ```typescript import type { DynamicParam, Endpoint, TypedFetchInput, TypedFetchRequestInit } from 'fetchdts' interface APISchema { '/users': { [Endpoint]: { GET: { response: User[] } POST: { body: { name: string, email: string } headers: { authorization: string } response: User } } [DynamicParam]: { [Endpoint]: { PUT: { body: { name?: string, email?: string } response: User } } } } } async function api>( input: T, init?: TypedFetchRequestInit ) { return fetch(input, init as RequestInit) } // GET request - method is optional since GET is the default await api('/users') // POST request - method is required, body and headers are typed await api('/users', { method: 'POST', body: JSON.stringify({ name: 'John', email: 'john@example.com' }), headers: { authorization: 'Bearer token123' } }) // PUT request on dynamic path await api('/users/123', { method: 'PUT', body: JSON.stringify({ name: 'Jane' }) }) ``` ### Response (This is a type utility, not an endpoint. The response is the inferred TypeScript `RequestInit` type for the specified path.) ``` -------------------------------- ### HTTP Methods Source: https://github.com/unjs/fetchdts/blob/main/README.md Lists the supported HTTP methods in fetchdts, including standard methods and less common ones. ```APIDOC ## HTTP Methods All standard HTTP methods are supported: - `GET`, `POST`, `PUT`, `DELETE`, `PATCH` - `OPTIONS`, `HEAD`, `CONNECT`, `TRACE` ```ts interface RESTSchema { '/api/users': { [Endpoint]: { GET: { response: User[] } POST: { body: CreateUser, response: User } } [DynamicParam]: { [Endpoint]: { GET: { response: User } PUT: { body: UpdateUser, response: User } PATCH: { body: Partial, response: User } DELETE: { response: { success: boolean } } } } } } ``` ``` -------------------------------- ### Core Types Source: https://github.com/unjs/fetchdts/blob/main/README.md Details the core utility types provided by fetchdts, such as `TypedFetchInput`, `TypedFetchRequestInit`, and `TypedFetchResponseBody`, and demonstrates their usage. ```APIDOC ## Core Types #### `TypedFetchInput` Extracts valid URL paths from your schema: ```ts type ValidPaths = TypedFetchInput // Result: '/users' | '/users/${string}' ``` #### `TypedFetchRequestInit` Provides typed request options for a specific path: ```ts // For paths requiring body/headers/query parameters await api('/users', { method: 'POST', body: { name: 'John' }, // ✅ Typed based on schema headers: { authorization: 'Bearer token' } }) ``` #### `TypedFetchResponseBody` Returns the typed response body for a given path: ```ts const response = await api('/users/123') // Type automatically inferred from schema ``` ``` -------------------------------- ### Symbols Reference Source: https://github.com/unjs/fetchdts/blob/main/README.md Explains the special symbols used in fetchdts for defining route matching behavior: `Endpoint`, `DynamicParam`, and `WildcardParam`. ```APIDOC ## Symbols Reference fetchdts uses special symbols to define different types of route matching: ```ts import { DynamicParam, Endpoint, WildcardParam } from 'fetchdts' interface Schema { // Endpoint: Marks where HTTP methods are defined [Endpoint]: { GET: { response: Data } POST: { body: Input, response: Data } } // DynamicParam: Matches single path segments (e.g., /users/:id) [DynamicParam]: { [Endpoint]: { GET: { response: User } } } // WildcardParam: Matches multiple path segments (e.g., /files/*) [WildcardParam]: { [Endpoint]: { GET: { response: File } } } } ``` ``` -------------------------------- ### TypeScript Configuration for Strictness Source: https://github.com/unjs/fetchdts/blob/main/README.md Provides essential TypeScript compiler options for enhanced type safety and development experience. Enabling 'strict', 'exactOptionalPropertyTypes', and 'noUncheckedIndexedAccess' helps catch potential errors during development. ```json { "compilerOptions": { "strict": true, "exactOptionalPropertyTypes": true, "noUncheckedIndexedAccess": true } } ``` -------------------------------- ### Cross-Domain API Support with FetchDTS Source: https://github.com/unjs/fetchdts/blob/main/README.md Demonstrates FetchDTS's capability to handle requests to external domains by defining schemas that include full URLs. This allows for type-safe interactions with third-party APIs. ```typescript interface Schema { 'https://api.github.com': { '/users': { [DynamicParam]: { [Endpoint]: { GET: { response: GitHubUser } } '/repos': { [Endpoint]: { GET: { response: Repository[] } } } } } } } // Works with full URLs const user = await api('https://api.github.com/users/octocat') const repos = await api('https://api.github.com/users/octocat/repos') ``` -------------------------------- ### serializeRoutes: Generate TypeScript API Schemas from Routes (TypeScript) Source: https://context7.com/unjs/fetchdts/llms.txt The serializeRoutes function generates TypeScript interface definitions from route configurations, enabling the creation of API schemas at build time. It takes a name for the interface, an array of route definitions, and optional configuration. The output is a string containing the generated TypeScript interfaces. Dependencies include the 'fetchdts' library. ```typescript import { serializeRoutes } from 'fetchdts' const schema = serializeRoutes('APISchema', [ { path: '/users', metadata: { GET: { responseType: '{ id: number, name: string }[]' }, POST: { bodyType: '{ name: string, email: string }', responseType: '{ id: number, name: string, email: string }' } } }, { path: '/users/:id', type: 'dynamic', metadata: { GET: { responseType: '{ id: number, name: string, email: string }' }, PUT: { bodyType: '{ name?: string, email?: string }', responseType: '{ id: number, name: string, email: string }' }, DELETE: { responseType: '{ success: boolean }' } } }, { path: '/files', type: 'wildcard', metadata: { GET: { responseType: 'ArrayBuffer' } } } ], { export: true }) console.log(schema) // Output: // import { DynamicParam, WildcardParam } from 'fetchdts' // export // interface APISchema { // "/users": { // "GET": { // "response": { id: number, name: string }[] // } // "POST": { // "body": { name: string, email: string } // "response": { id: number, name: string, email: string } // } // [DynamicParam]: { // "GET": { // "response": { id: number, name: string, email: string } // } // "PUT": { // "body": { name?: string, email?: string } // "response": { id: number, name: string, email: string } // } // "DELETE": { // "response": { success: boolean } // } // } // } // "/files": { // [WildcardParam]: { // "GET": { // "response": ArrayBuffer // } // } // } // } ``` -------------------------------- ### fetchdts Core Type: TypedFetchRequestInit (TypeScript) Source: https://github.com/unjs/fetchdts/blob/main/README.md Demonstrates the usage of `TypedFetchRequestInit` for providing type-safe request options. It allows specifying method, body, and headers that conform to the API schema for a particular path, enhancing request safety. ```ts await api('/users', { method: 'POST', body: { name: 'John' }, // ✅ Typed based on schema headers: { authorization: 'Bearer token' } }) ``` -------------------------------- ### serializeRoutes Source: https://context7.com/unjs/fetchdts/llms.txt serializeRoutes generates TypeScript interface definitions from route configurations, useful for generating API schemas at build time. ```APIDOC ## serializeRoutes(name, routes, options?) ### Description Generates TypeScript interface definitions from route configurations. This is useful for generating API schemas from route definitions at build time. ### Parameters - **name** (string) - The name of the generated interface. - **routes** (Array) - An array of route objects, each defining a path and its metadata (HTTP methods, request/response types). - **options** (object, optional) - Configuration options, such as `{ export: true }` to add the `export` keyword. ### Usage Example ```typescript import { serializeRoutes } from 'fetchdts' const schema = serializeRoutes('APISchema', [ { path: '/users', metadata: { GET: { responseType: '{ id: number, name: string }[]' }, POST: { bodyType: '{ name: string, email: string }', responseType: '{ id: number, name: string, email: string }' } } }, { path: '/users/:id', type: 'dynamic', metadata: { GET: { responseType: '{ id: number, name: string, email: string }' }, PUT: { bodyType: '{ name?: string, email?: string }', responseType: '{ id: number, name: string, email: string }' }, DELETE: { responseType: '{ success: boolean }' } } }, { path: '/files', type: 'wildcard', metadata: { GET: { responseType: 'ArrayBuffer' } } } ], { export: true }) console.log(schema) // Output: // import { DynamicParam, WildcardParam } from 'fetchdts' // export // interface APISchema { // "/users": { // "GET": { // "response": { id: number, name: string }[] // } // "POST": { // "body": { name: string, email: string } // "response": { id: number, name: string, email: string } // } // [DynamicParam]: { // "GET": { // "response": { id: number, name: string, email: string } // } // "PUT": { // "body": { name?: string, email?: string } // "response": { id: number, name: string, email: string } // } // "DELETE": { // "response": { success: boolean } // } // } // } // "/files": { // [WildcardParam]: { // "GET": { // "response": ArrayBuffer // } // } // } // } ``` ``` -------------------------------- ### Generate TypeScript Schema from Routes Source: https://github.com/unjs/fetchdts/blob/main/README.md Utility function to generate a TypeScript schema from route definitions. This function takes a schema name, an array of route objects, and optional configuration to produce a typed schema for API requests. ```typescript import { serializeRoutes } from 'fetchdts' const schema = serializeRoutes('APISchema', [ { path: '/users', metadata: { GET: { responseType: 'User[]' }, POST: { bodyType: '{ name: string }', responseType: 'User' } } }, { path: '/users/:id', type: 'dynamic', metadata: { GET: { responseType: 'User' } } } ]) console.log(schema) // Outputs TypeScript interface definition ``` -------------------------------- ### User Endpoints API Source: https://context7.com/unjs/fetchdts/llms.txt This section details the API endpoints for managing users, including operations like fetching, creating, updating, and deleting users. ```APIDOC ## GET /api/users ### Description Retrieves a list of users, with optional limit and offset for pagination. ### Method GET ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of users to return. - **offset** (number) - Optional - The number of users to skip before starting to collect the result set. ### Response #### Success Response (200) - **response** (User[]) - An array of user objects. - **responseHeaders** - Headers returned with the response. - **x-total-count** (string) - The total number of users available. #### Response Example ```json [ { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } ] ``` ## POST /api/users ### Description Creates a new user. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. #### Headers - **authorization** (string) - Required - Bearer token for authentication. ### Response #### Success Response (200) - **response** (User) - The newly created user object. #### Response Example ```json { "id": 2, "name": "Jane Smith", "email": "jane.smith@example.com" } ``` ## GET /api/users/{id} ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (number) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **response** (User) - The user object. #### Response Example ```json { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } ``` ## PUT /api/users/{id} ### Description Updates an existing user. ### Method PUT ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (number) - Required - The unique identifier of the user to update. #### Request Body - **name** (string) - Optional - The updated name of the user. - **email** (string) - Optional - The updated email address of the user. #### Headers - **authorization** (string) - Required - Bearer token for authentication. ### Response #### Success Response (200) - **response** (User) - The updated user object. #### Response Example ```json { "id": 1, "name": "John Doe Updated", "email": "john.doe.updated@example.com" } ``` ## DELETE /api/users/{id} ### Description Deletes a user by their ID. ### Method DELETE ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (number) - Required - The unique identifier of the user to delete. #### Headers - **authorization** (string) - Required - Bearer token for authentication. ### Response #### Success Response (200) - **response** ({ success: boolean }) - An object indicating the success of the deletion. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Typed Headers Access with FetchDTS Source: https://github.com/unjs/fetchdts/blob/main/README.md Demonstrates how to access response headers with type safety using FetchDTS. It shows retrieving standard and custom headers, with custom headers being typed based on a defined schema. ```typescript const contentType = response.headers.get('content-type') // string | null const customHeader = response.headers.get('x-custom') // Typed based on schema ``` -------------------------------- ### Schema Definition Source: https://github.com/unjs/fetchdts/blob/main/README.md Defines the structure of your API endpoints using TypeScript interfaces. It specifies paths, HTTP methods, and the shape of request bodies, query parameters, headers, and responses. ```APIDOC ## Schema Definition Your API schema describes the structure of your endpoints using TypeScript interfaces: ```ts interface Schema { '/path': { [Endpoint]: { [HTTPMethod]: { query?: { param: string } // Query parameters body?: { data: any } // Request body headers?: { auth: string } // Required headers response: { result: any } // Response data responseHeaders?: { 'x-rate-limit': string } // Response headers } } } } ``` ``` -------------------------------- ### Define API Schema and Create Typed Fetch Function (TypeScript) Source: https://github.com/unjs/fetchdts/blob/main/README.md Demonstrates how to define an API schema using TypeScript interfaces and create a generic typed fetch function. This function ensures type safety for request inputs, initializers, and response bodies based on the defined schema. ```ts import type { DynamicParam, Endpoint, TypedFetchInput, TypedFetchRequestInit, TypedFetchResponseBody, TypedResponse } from 'fetchdts' // Define your API schema interface APISchema { '/users': { [Endpoint]: { GET: { response: { id: number, name: string }[] } POST: { body: { name: string, email: string } response: { id: number, name: string, email: string } } } [DynamicParam]: { // /users/:id [Endpoint]: { GET: { response: { id: number, name: string, email: string } } DELETE: { response: { success: boolean } } } } } } // Create your typed fetch function async function api>( input: T, init?: TypedFetchRequestInit, ) { return fetch(input, init as RequestInit) as unknown as Promise>> } // Use with full type safety const users = await api('/users').then(r => r.json()) // Type: { id: number; name: string }[] const user = await api('/users/123').then(r => r.json()) // Type: { id: number; name: string; email: string } ``` -------------------------------- ### Extract Typed Fetch Input Paths with TypeScript Source: https://context7.com/unjs/fetchdts/llms.txt Illustrates the use of `TypedFetchInput` to extract valid URL paths from an API schema. This type utility can optionally filter paths by HTTP method, ensuring type safety for the `input` parameter of typed fetch functions. ```typescript import type { TypedFetchInput } from 'fetchdts' interface APISchema { '/users': { [Endpoint]: { GET: { response: User[] } POST: { body: CreateUser, response: User } } [DynamicParam]: { [Endpoint]: { GET: { response: User } } } } } // All valid paths type AllPaths = TypedFetchInput // Result: '/users' | '/users/${string}' // Only GET paths type GetPaths = TypedFetchInput // Result: '/users' | '/users/${string}' // Only POST paths type PostPaths = TypedFetchInput // Result: '/users' ``` -------------------------------- ### Runtime Validation with Zod in TypeScript Source: https://github.com/unjs/fetchdts/blob/main/README.md Demonstrates how to add runtime validation to fetch requests using Zod in TypeScript. This ensures that the data received from the API conforms to the expected schema, even after compile-time checks. It parses the JSON response and throws an error if the data does not match the UserSchema. ```typescript import { z } from 'zod' const UserSchema = z.object({ id: z.number(), name: z.string(), email: z.string().email() }) async function api>( input: T, init?: TypedFetchRequestInit ): Promise> { const response = await fetch(input, init as RequestInit) const data = await response.json() // Runtime validation for critical endpoints if (input.startsWith('/api/users/') && init?.method !== 'DELETE') { return UserSchema.parse(data) // Throws if invalid } return data } ``` -------------------------------- ### Define API Schema with Core Symbols in TypeScript Source: https://context7.com/unjs/fetchdts/llms.txt Demonstrates how to define an API schema using fetchdts' core symbols: `Endpoint`, `DynamicParam`, and `WildcardParam`. These symbols are used to structure route matching patterns for static paths, dynamic parameters, and wildcard segments. ```typescript import type { DynamicParam, Endpoint, WildcardParam } from 'fetchdts' interface APISchema { '/api': { '/users': { [Endpoint]: { GET: { response: User[] } POST: { body: { name: string }, response: User } } [DynamicParam]: { // Matches /api/users/:id [Endpoint]: { GET: { response: User } PUT: { body: Partial, response: User } DELETE: { response: { success: boolean } } } } } [WildcardParam]: { // Matches /api/** [Endpoint]: { GET: { response: unknown } } } } } ``` -------------------------------- ### Organizing FetchDTS Schemas into Modules Source: https://github.com/unjs/fetchdts/blob/main/README.md Provides a best practice for managing large API schemas by organizing them into separate modules and then combining them using TypeScript's intersection types. This improves code maintainability and readability. ```typescript // types/api.ts interface UserAPI { '/api/users': { [Endpoint]: { GET: { response: User[] } POST: { body: CreateUser, response: User } } [DynamicParam]: { [Endpoint]: { GET: { response: User } PUT: { body: UpdateUser, response: User } DELETE: { response: { success: boolean } } } } } } interface PostAPI { '/api/posts': { [Endpoint]: { GET: { query?: { limit?: number }, response: Post[] } POST: { body: CreatePost, response: Post } } [DynamicParam]: { [Endpoint]: { GET: { response: Post } PUT: { body: UpdatePost, response: Post } DELETE: { response: { success: boolean } } } } } } // Combine them type APISchema = UserAPI & PostAPI ``` -------------------------------- ### fetchdts Core Type: TypedFetchInput (TypeScript) Source: https://github.com/unjs/fetchdts/blob/main/README.md Shows how to use the `TypedFetchInput` utility type to extract all valid URL paths from a defined API schema. This helps in ensuring that only defined API routes can be used with the typed fetch function. ```ts type ValidPaths = TypedFetchInput // Result: '/users' | '/users/${string}' ``` -------------------------------- ### fetchdts TypedFetchInput Source: https://context7.com/unjs/fetchdts/llms.txt Explains how `TypedFetchInput` extracts valid URL paths from an API schema, optionally filtered by HTTP method, for use with typed fetch functions. ```APIDOC ## TypedFetchInput ### Description `TypedFetchInput` is a type utility that extracts all valid URL paths from a given API schema. It can optionally filter these paths based on a specified HTTP method, ensuring type safety for the `input` parameter of your fetch requests. ### Type Definition `TypedFetchInput` ### Parameters - **Schema**: The API schema interface. - **Method** (Optional): The HTTP method ('GET', 'POST', 'PUT', 'DELETE', etc.) to filter paths by. ### Request Example ```typescript import type { TypedFetchInput } from 'fetchdts' interface APISchema { '/users': { [Endpoint]: { GET: { response: User[] } POST: { body: CreateUser, response: User } } [DynamicParam]: { [Endpoint]: { GET: { response: User } } } } } // All valid paths type AllPaths = TypedFetchInput // Result: '/users' | '/users/${string}' // Only GET paths type GetPaths = TypedFetchInput // Result: '/users' | '/users/${string}' // Only POST paths type PostPaths = TypedFetchInput // Result: '/users' ``` ### Response (This is a type utility, not an endpoint. The response is the inferred TypeScript type.) ``` -------------------------------- ### Post Endpoints API Source: https://context7.com/unjs/fetchdts/llms.txt This section details the API endpoints for retrieving posts associated with a user. ```APIDOC ## GET /api/users/{userId}/posts ### Description Retrieves all posts for a specific user. ### Method GET ### Endpoint /api/users/{userId}/posts ### Parameters #### Path Parameters - **userId** (number) - Required - The ID of the user whose posts are to be retrieved. ### Response #### Success Response (200) - **response** (Post[]) - An array of post objects. #### Response Example ```json [ { "id": 101, "userId": 1, "title": "First Post", "body": "This is the content of the first post." } ] ``` ``` -------------------------------- ### Typed Error Handling with FetchDTS Source: https://github.com/unjs/fetchdts/blob/main/README.md Shows how to define and handle API responses that can be either a successful data type or an error object with specific properties. This enhances robustness by allowing explicit checks for error conditions. ```typescript interface APISchema { '/api/users': { [DynamicParam]: { [Endpoint]: { GET: { response: User | { error: string, code: number } } } } } } const result = await api('/api/users/123') // result is typed as: User | { error: string; code: number } if ('error' in result) { console.error(`Error ${result.code}: ${result.error}`) } else { console.log(`User: ${result.name}`) } ``` -------------------------------- ### fetchdts Symbols Reference: Endpoint, DynamicParam, WildcardParam (TypeScript) Source: https://github.com/unjs/fetchdts/blob/main/README.md Details the special symbols used by fetchdts to define API route structures. `Endpoint` marks where HTTP methods are defined, `DynamicParam` matches single path segments, and `WildcardParam` matches multiple path segments. ```ts import { DynamicParam, Endpoint, WildcardParam } from 'fetchdts' interface Schema { // Endpoint: Marks where HTTP methods are defined [Endpoint]: { GET: { response: Data } POST: { body: Input, response: Data } } // DynamicParam: Matches single path segments (e.g., /users/:id) [DynamicParam]: { [Endpoint]: { GET: { response: User } } } // WildcardParam: Matches multiple path segments (e.g., /files/*) [WildcardParam]: { [Endpoint]: { GET: { response: File } } } } ``` -------------------------------- ### TypedURLSearchParams: Type-Safe URL Query Parameters (TypeScript) Source: https://context7.com/unjs/fetchdts/llms.txt TypedURLSearchParams provides type-safe methods for interacting with URL search parameters. It ensures that values retrieved or set match the expected types defined in a QueryMap interface, offering compile-time safety and reducing runtime errors. Dependencies include the 'fetchdts' library. ```typescript import type { TypedURLSearchParams } from 'fetchdts' interface SearchParams { q: string page: string limit: string sort: 'asc' | 'desc' } type SearchQueryParams = TypedURLSearchParams function buildSearchURL(params: SearchQueryParams): string { // get() returns typed value or null const query = params.get('q') // Type: string | null const sort = params.get('sort') // Type: 'asc' | 'desc' | null // set() accepts typed values params.set('page', '1') params.set('limit', '10') // has() checks for parameter existence if (!params.has('sort')) { params.append('sort', 'desc') } return params.toString() } ``` -------------------------------- ### TypedRequest: Typed Wrapper for Fetch Request Source: https://context7.com/unjs/fetchdts/llms.txt TypedRequest provides a typed wrapper for the native Request object. It enables strongly-typed access to request bodies and headers, particularly useful in API handler contexts. ```typescript import type { TypedRequest, TypedHeaders } from 'fetchdts' interface CreateUserBody { name: string email: string } interface AuthHeaders { 'authorization': `Bearer ${string}` 'content-type': 'application/json' } type CreateUserRequest = TypedRequest // In an API handler function handleRequest(request: CreateUserRequest) { const authHeader = request.headers.get('authorization') // Type: `Bearer ${string}` | null const contentType = request.headers.get('content-type') // Type: 'application/json' | null return request.json().then(body => { // body: CreateUserBody console.log(body.name, body.email) }) } ```