electron-nest-core
v1.0.8
Published
Electron-nest IPC 装饰器,HTTP 服务支持,数据库支持
Maintainers
Readme
Electron Nest Core
一个用于 Electron 应用的装饰器和 HTTP 服务支持库,让你能像 Nest.js 一样使用装饰器来处理 IPC 通信和 HTTP 请求。
特性
- 支持 IPC 通信的装饰器
- 支持 HTTP 服务
- 支持 DTO 验证
- 支持 CORS 跨域
- TypeScript 支持
安装
npm install electron-nest-core --save依赖
本库需要以下依赖:
npm install class-transformer class-validator reflect-metadata --save基本使用
初始化 HTTP 服务
import { app } from 'electron';
import { initializeHttpServer } from 'electron-nest-core';
app.whenReady().then(() => {
// 初始化 HTTP 服务
initializeHttpServer({
enable: true,
port: 3000,
baseRoutePrefix: '/api'
});
});创建 IPC 控制器
import { IpcController, IpcHandler } from 'electron-nest-core';
import { IsString, IsNotEmpty } from 'class-validator';
// 定义 DTO
class UserDTO {
@IsString()
@IsNotEmpty()
name: string;
}
// 定义控制器
@IpcController({
prefix: 'user',
enableHttp: true
})
class UserController {
@IpcHandler('create', UserDTO)
async createUser(event, userData: UserDTO) {
return {
success: true,
message: '用户创建成功',
data: userData
};
}
}
// 实例化控制器
const userController = new UserController();客户端调用方式
通过 IPC 调用
// 在渲染进程中
const result = await window.electron.ipcRenderer.invoke('user/create', {
name: '张三'
});通过 HTTP 调用
// 使用 fetch API
const response = await fetch('http://localhost:3000/api/user/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: '张三'
})
});
const result = await response.json();高级用法
配置 CORS
import { initializeHttpServer, getHttpServer } from 'electron-nest-core';
// 方法 1: 初始化时配置
initializeHttpServer({
cors: {
enable: true,
options: {
origin: ['http://localhost:8080'],
methods: ['GET', 'POST'],
credentials: true
}
}
});
// 方法 2: 获取实例后配置
const httpServer = getHttpServer();
httpServer.setCorsOptions({
origin: '*',
methods: ['GET', 'POST']
});
// 方法 3: 禁用 CORS
httpServer.enableCors(false);添加自定义中间件
import { getHttpServer } from 'electron-nest-core';
const httpServer = getHttpServer();
httpServer.use((req, res, next) => {
console.log(`[${req.method}] ${req.url}`);
next();
});API 参考
IpcController 装饰器
@IpcController(options: string | IpcControllerOptions)参数:
options: 字符串前缀或控制器选项对象prefix: 路由前缀enableHttp: 是否启用 HTTP 支持
IpcHandler 装饰器
@IpcHandler(path: string, dtoClass?: any)参数:
path: 处理器路径dtoClass: 可选的 DTO 类用于验证
HTTP 服务
initializeHttpServer(options?: Partial<HttpServerOptions>)参数:
options: HTTP 服务配置选项enable: 是否启用 HTTP 服务port: 端口号baseRoutePrefix: 路由前缀cors: CORS 配置
getHttpServer(): HttpServerService返回 HTTP 服务实例,可用于添加自定义中间件或路由。
许可证
MIT
