@bytekit/autofetch
Version:
A TypeScript-first, decorator-based HTTP client for building elegant and modular API clients with fetch under the hood. Inspired by Spring's `@RestClient` and OpenFeign.
124 lines (98 loc) โข 3.05 kB
Markdown
# /autofetch
A TypeScript-first, decorator-based HTTP client for building elegant and modular API clients with fetch under the hood. Inspired by Spring's `` and OpenFeign.
## Features
- ๐งฉ Class-based HTTP client with decorators
- ๐ฏ Supports `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, and more
- โ๏ธ Middleware support via interceptors
- ๐ Caching support and hooks for before/after execution
- ๐งต Works with native `fetch` and streams/blobs
- ๐งช Fully typed and extensible
## Installation
```bash
npm install /autofetch
```
or
```bash
yarn add /autofetch
```
## Quick Example
```ts
import {
Client,
GetMapping,
PostMapping,
BodyParam,
PathParam,
QueryParam,
} from "@bytekit/autofetch";
interface User {
id: string;
name: string;
email: string;
}
({
baseUrl: () => "https://api.example.com",
before: (self, url, init, id) => {
console.log(`[${id}] Requesting ${init.method} ${url} ${init.body}`);
},
after: (self, response, id) => {
console.log(`[${id}] Got response`, response);
},
})
class UserService {
({ value: "/users" })
async getUsers(): Promise<User[]> {
return [];
}
({ value: "/users/:id" })
async getUser(("id") id: string): Promise<User> {
return {} as User;
}
({ value: "/users" })
async createUser( user: Omit<User, "id">): Promise<User> {
return {} as User;
}
({ value: "/users/search" })
async searchUsers(
("q") query: string,
({ name: "limit", required: false }) limit?: number
): Promise<User[]> {
return [];
}
}
// Usage
const service = new UserService();
const run = async () => {
const newUser = await service.createUser({
name: "Alice",
email: "alice@example.com",
});
const user = await service.getUser(newUser.id);
const users = await service.getUsers();
const searchResults = await service.searchUsers("ali", 10);
};
```
## Decorators
### Class Decorators
`(options)`
Marks a class as an API client.
### Method Decorators
- `({ value })`
- `({ value })`
- `({ value })`
- `({ value })`
- `({ value })`
### Parameter Decorators
- `` โ binds the request body
- `(name)` โ binds a URL path parameter
- `(name | { name, required })` โ binds query parameters
- `(name)` โ binds a header
- `(name)` โ binds form fields (for multipart/form-data)
- `(name)` โ binds form fields (for application/x-www-form-urlencoded)
- `` โ accesses the `RequestInit` object for dynamic tweaking
## Advanced Options
- Interceptors: inject `RequestInit` at the client or method level
- Hooks: `before` and `after` functions for logging, auth, etc.
- Streaming: `stream: true` on `` returns the raw response stream
- Blobs: `blob: true` for binary payloads
- Custom Fetch: swap in your own fetch implementation