@jubo-health/node-grpc-microservice-kit
v0.1.0
Published
A grpc library for node
Readme
@jubo-health/node-grpc-microservice-kit
Node.js gRPC 微服務工具套件,提供簡化的 gRPC 客戶端與伺服器建立方式。
安裝
npm install @jubo-health/node-grpc-microservice-kit專案結構
proto-node/
├── index.js # 主程式入口
├── package.json
└── src/
├── familyServer/
│ └── familyServer.proto
├── lineBotServer/
│ └── lineBotServer.proto
├── NISMQTTService/
│ └── NISMQTTService.proto
├── NISServer/
│ └── NISServer.proto
└── ping/
└── ping.proto使用方式
建立 gRPC Client
const { getClient } = require('@jubo-health/node-grpc-microservice-kit');
// getClient(protoName, serviceName, serverURL)
const pingClient = getClient('ping', 'Ping', 'localhost:50051');
// 呼叫 RPC 方法 (Promise-based)
const response = await pingClient.Echo({
messageId: '123',
messageBody: 'Hello World'
});
// 帶 metadata
const responseWithMeta = await pingClient.Echo(
{ messageId: '123', messageBody: 'Hello World' },
{ 'x-request-id': 'abc-123', 'authorization': 'Bearer token' }
);建立 gRPC Server
const { startServer } = require('@jubo-health/node-grpc-microservice-kit');
// 定義 service implementation
const implementation = {
Echo: (call, callback) => {
const { messageId, messageBody } = call.request;
callback(null, {
messageId,
messageBody,
count: 1,
timestr: new Date().toISOString(),
timestamp: Date.now()
});
}
};
// startServer(protoName, serviceName, implementation, port)
startServer('ping', 'Ping', implementation, '0.0.0.0:50051');API
getClient(protoName, serviceName, serverURL)
建立 gRPC 客戶端。
| 參數 | 類型 | 說明 |
|------|------|------|
| protoName | string | Proto 檔案所在的資料夾名稱(如 ping、NISServer) |
| serviceName | string | Proto 檔案中定義的 service 名稱 |
| serverURL | string | gRPC 伺服器位址(如 localhost:50051) |
回傳一個物件,包含所有 RPC 方法的 Promise-based 版本。每個方法接受兩個參數:
request: 請求物件metadata: (可選) 要傳送的 metadata 物件
startServer(protoName, serviceName, implementation, port)
啟動 gRPC 伺服器。
| 參數 | 類型 | 說明 |
|------|------|------|
| protoName | string | Proto 檔案所在的資料夾名稱 |
| serviceName | string | Proto 檔案中定義的 service 名稱 |
| implementation | object | Service 實作,包含各 RPC 方法的處理函式 |
| port | string | 監聽的位址與 port(如 0.0.0.0:50051) |
新增 Proto 檔案
- 在
src/下建立新資料夾(資料夾名稱將作為protoName) - 在資料夾內新增同名的
.proto檔案
src/
└── myService/
└── myService.proto- 套件會自動載入所有 proto 定義
測試
npm test依賴套件
@grpc/grpc-js^1.14.3 - gRPC for Node.js@grpc/proto-loader^0.8.0 - Protocol Buffer loader
License
ISC
