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 🙏

© 2025 – Pkg Stats / Ryan Hefner

electron-ipc-restful

v0.0.1

Published

Electron IPC 路由与注册器(HTTP 风格 REST 语义)

Downloads

9

Readme

@life-toolkit/electron-ipc-router

Electron IPC 路由与注册器,提供 HTTP 风格的 REST API 语义,支持装饰器语法和自动路由注册。

特性

  • 🎯 HTTP 风格语义: 使用标准的 HTTP 方法 (GET/POST/PUT/DELETE) 和路径语法
  • 🎨 装饰器语法: 基于 TypeScript 装饰器的声明式路由定义
  • 🔗 参数绑定: 支持路径参数、查询参数和请求体参数
  • 📦 自动注册: 自动从控制器类构建和注册路由
  • 🛡️ 响应包装: 统一的响应格式和错误处理
  • 高性能: 使用 find-my-way 作为路由匹配引擎

安装

pnpm add @life-toolkit/electron-ipc-router

快速开始

1. 定义控制器

import { Controller, Get, Post, Param, Body } from '@life-toolkit/electron-ipc-router';

@Controller('/users')
class UserController {
  @Get('/')
  async getUsers() {
    return await this.userService.findAll();
  }

  @Get('/:id')
  async getUser(@Param('id') id: string) {
    return await this.userService.findById(id);
  }

  @Post('/')
  async createUser(@Body() userData: CreateUserDto) {
    return await this.userService.create(userData);
  }

  @Put('/:id')
  async updateUser(@Param('id') id: string, @Body() userData: UpdateUserDto) {
    return await this.userService.update(id, userData);
  }

  @Delete('/:id')
  async deleteUser(@Param('id') id: string) {
    return await this.userService.delete(id);
    return { success: true };
  }
}

2. 注册 IPC 处理器

import { registerIpcHandlers } from '@life-toolkit/electron-ipc-router';

registerIpcHandlers({
  controllers: [UserController],
  channel: 'REST' // 可选,默认为 'REST'
});

3. 渲染进程调用

import { ipcRenderer } from 'electron';

// GET 请求
const users = await ipcRenderer.invoke('REST', {
  method: 'GET',
  path: '/users'
});

// POST 请求
const newUser = await ipcRenderer.invoke('REST', {
  method: 'POST',
  path: '/users',
  payload: { name: 'John', email: '[email protected]' }
});

// 带路径参数的请求
const user = await ipcRenderer.invoke('REST', {
  method: 'GET',
  path: '/users/123'
});

API 参考

装饰器

@Controller(prefix?: string)

定义控制器类和路由前缀。

@Controller('/api/v1/users') // 路由前缀为 /api/v1/users
class UserController {
  // ...
}

HTTP 方法装饰器

  • @Get(path?: string)
  • @Post(path?: string)
  • @Put(path?: string)
  • @Delete(path?: string)
@Get('/')           // GET /users/
@Get('/:id')        // GET /users/:id
@Post('/create')    // POST /users/create

参数装饰器

  • @Param(name?: string) - 路径参数
  • @Query(name?: string) - 查询参数
  • @Body(name?: string) - 请求体参数
@Get('/:id')
async getUser(@Param('id') id: string) {
  // id 来自路径参数 /users/123 中的 123
}

@Post('/search')
async searchUsers(@Query('keyword') keyword: string, @Query() query: any) {
  // keyword 来自查询参数 ?keyword=test
  // query 包含所有查询参数
}

@Post('/')
async createUser(@Body('name') name: string, @Body() userData: CreateUserDto) {
  // name 来自请求体中的 name 字段
  // userData 包含整个请求体
}

注册选项

type RegisterIpcHandlersOptions = {
  controllers?: Array<any>;      // 控制器类或实例列表
  routes?: RouteDef[];          // 直接提供的路由定义
  channel?: string;             // IPC channel 名称,默认为 'REST'
};

响应格式

所有响应都会被包装为标准格式:

interface StandardResponse<T = any> {
  data: T;        // 响应数据
  message: string; // 响应消息
  code: number;    // 响应状态码
}

成功响应:

{
  "data": { "id": 1, "name": "John" },
  "message": "success",
  "code": 200
}

错误响应:

{
  "data": null,
  "message": "User not found",
  "code": 404
}

自定义响应配置

import { registerIpcHandlers } from '@life-toolkit/electron-ipc-router';

registerIpcHandlers({
  controllers: [UserController],
  responseWrapperConfig: {
    successCode: 200,
    successMessage: '操作成功',
    defaultErrorCode: 500,
    defaultErrorMessage: '系统错误'
  }
});

高级用法

直接定义路由

除了使用装饰器,你也可以直接定义路由:

import { registerIpcHandlers } from '@life-toolkit/electron-ipc-router';

const customRoutes = [
  {
    method: 'GET',
    path: '/health',
    handler: async () => ({ status: 'ok', timestamp: Date.now() })
  }
];

registerIpcHandlers({
  routes: customRoutes
});

混合使用

控制器和自定义路由可以混合使用:

registerIpcHandlers({
  controllers: [UserController, ProductController],
  routes: customRoutes
});

路径兼容性

支持两种路径格式:

// REST 风格路径
'/users/:id'

// IPC 事件风格路径(会自动转换为 REST 风格)
// 'users:getById' -> '/users/getById'

类型定义

// 路由定义
type RouteDef = {
  method: 'GET' | 'POST' | 'PUT' | 'DELETE';
  path: string;
  handler: RestHandler;
};

// 请求处理器
type RestHandler = (ctx: RestHandlerCtx) => any | Promise<any>;

// 处理器上下文
type RestHandlerCtx = {
  params: Record<string, string>;  // 路径参数
  payload: any;                    // 请求负载
};

依赖

  • find-my-way: 高性能路由匹配
  • reflect-metadata: TypeScript 装饰器元数据支持
  • electron: IPC 通信(peerDependency)

许可证

MIT