@contract-kit/client
v0.1.1
Published
HTTP client for contract-kit
Maintainers
Readme
@contract-kit/client
HTTP client for Contract Kit
This package provides type-safe client adapters for making contract-based HTTP requests.
Installation
npm install @contract-kit/client @contract-kit/coreTypeScript Requirements
This package requires TypeScript 5.0 or higher for proper type inference.
HTTP Client
Creating a Client
import { createClient } from "@contract-kit/client";
export const apiClient = createClient({
baseUrl: "https://api.example.com",
headers: async () => ({
"x-app-version": "1.0",
Authorization: `Bearer ${getToken()}`,
}),
});Making Requests
import { apiClient } from "@/lib/api-client";
import { getTodo, createTodo, listTodos } from "@/contracts/todos";
// GET request with path params
const todo = await apiClient
.endpoint(getTodo)
.call({ path: { id: "123" } });
// POST request with body
const newTodo = await apiClient
.endpoint(createTodo)
.call({ body: { title: "Learn Contract Kit" } });
// GET request with query params
const todos = await apiClient
.endpoint(listTodos)
.call({ query: { completed: false, limit: 10 } });Error Handling
import { ContractError } from "@contract-kit/client";
try {
const todo = await apiClient
.endpoint(getTodo)
.call({ path: { id: "123" } });
} catch (error) {
if (error instanceof ContractError) {
console.log(error.status); // HTTP status code
console.log(error.details); // Error response body (validated when schema exists)
}
}Creating API Wrappers
// features/todos/api.ts
import { apiClient } from "@/lib/api-client";
import { getTodo, createTodo, deleteTodo } from "@/contracts/todos";
export const todosApi = {
get: (id: string) =>
apiClient.endpoint(getTodo).call({ path: { id } }),
create: (data: { title: string; completed?: boolean }) =>
apiClient.endpoint(createTodo).call({ body: data }),
delete: (id: string) =>
apiClient.endpoint(deleteTodo).call({ path: { id } }),
};API Reference
HTTP Client
createClient(config)
Creates an HTTP client instance.
const client = createClient({
baseUrl: string;
headers?: () => Promise<Record<string, string>> | Record<string, string>;
fetch?: typeof fetch;
});client.endpoint(contract)
Creates a typed endpoint for a contract.
const endpoint = client.endpoint(getTodo);
const result = await endpoint.call({ path: { id: "123" } });Type Exports
import { ContractError } from "@contract-kit/client";
import type {
CallArgs,
Client,
ClientConfig,
Endpoint,
EndpointCallArgs,
InferBody,
InferPathParams,
InferQuery,
InferSuccessResponse,
} from "@contract-kit/client";Related Packages
@contract-kit/core- Core contract definitions@contract-kit/react-query- TanStack Query integration@contract-kit/server- Hexagonal framework for application composition
License
MIT
