npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jintianxiayu/http-client-decorator

v0.1.3

Published

Decorator-based HTTP client framework providing RPC-like calling experience

Downloads

309

Readme

@jintianxiayu/http-client-decorator

基于装饰器的 HTTP 客户端框架,提供 RPC-like 调用体验。

特性

  • 基于装饰器的声明式 HTTP 客户端定义
  • 支持 @Get@Post@Put@Delete@Patch 方法装饰器
  • 支持 @Path@Query@Body@Header 参数装饰器
  • Koa 风格洋葱模型中间件机制
  • HTTP 4xx/5xx 错误自动抛出 HttpError 异常
  • 底层使用 axios,支持所有 axios 特性

安装

npm install @jintianxiayu/http-client-decorator

快速开始

定义 HTTP 客户端

import { HttpClient, Get, Post, Path, Query, Body, Header } from '@jintianxiayu/http-client-decorator';

@HttpClient({
    baseURL: 'https://api.example.com',
})
class UserService {
    @Get('/users/:id')
    getUser(@Path('id') id: string, @Header('Authorization') token: string): Promise<User> {
        // 实际不会调用,仅用于类型标注
        return Promise.resolve({} as User);
    }

    @Post('/users')
    createUser(@Body() dto: CreateUserDto): Promise<User> {
        return Promise.resolve({} as User);
    }

    @Get('/users')
    listUsers(@Query('page') page: string, @Query('size') size: string): Promise<User[]> {
        return Promise.resolve([] as User[]);
    }
}

使用客户端

const userService = new UserService();

// GET https://api.example.com/users/123
const user = await userService.getUser('123', 'Bearer xxx');

// POST https://api.example.com/users
const newUser = await userService.createUser({ name: 'John' });

// GET https://api.example.com/users?page=1&size=10
const users = await userService.listUsers('1', '10');

中间件

定义中间件

import type { Middleware, HttpContext } from '@jintianxiayu/http-client-decorator';

const authMiddleware: Middleware = async (ctx: HttpContext, next) => {
    // 请求前处理
    ctx.request.headers['Authorization'] = `Bearer ${getToken()}`;

    await next(); // 调用下一个中间件

    // 响应后处理
    console.log(`Response status: ${ctx.response?.status}`);
};

洋葱模型执行顺序

请求前: middlewareA.before → middlewareB.before
       ↓
    [HTTP 请求]
       ↓
响应后: middlewareB.after → middlewareA.after

使用中间件

@HttpClient({
    baseURL: 'https://api.example.com',
    middlewares: [authMiddleware, logMiddleware],
})
class UserService {}

错误处理

HTTP 4xx/5xx 响应会抛出 HttpError 异常:

import { HttpError } from '@jintianxiayu/http-client-decorator';

try {
    await userService.getUser('not-found');
} catch (e) {
    if (e instanceof HttpError) {
        console.error(`HTTP ${e.status}: ${e.message}`);
        console.error('Response data:', e.data);
    }
}

API 参考

装饰器

类装饰器

  • @HttpClient(config: HttpClientConfig) - 标记并配置 HTTP 客户端类

方法装饰器

  • @Get(path: string) - GET 请求
  • @Post(path: string) - POST 请求
  • @Put(path: string) - PUT 请求
  • @Delete(path: string) - DELETE 请求
  • @Patch(path: string) - PATCH 请求

参数装饰器

  • @Path(name: string) - URL 路径参数
  • @Query(name: string) - URL 查询参数
  • @Body() - 请求体
  • @Header(name: string) - 请求头

类型

interface HttpClientConfig {
    baseURL: string;
    middlewares?: Middleware[];
    timeout?: number;
    headers?: Record<string, string>;
}

interface HttpContext {
    request: {
        method: string;
        url: string;
        headers: Record<string, string>;
        body?: unknown;
    };
    response?: {
        status: number;
        headers: Record<string, string>;
        data: unknown;
    };
    state: Record<string, unknown>;
    error?: Error;
}

type Middleware = (ctx: HttpContext, next: () => Promise<void>) => Promise<void>;

class HttpError extends Error {
    constructor(
        public status: number,
        public data: unknown,
        message: string
    ) {
        super(message);
        this.name = 'HttpError';
    }
}

License

MIT