forked from zcws/node-feign
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeign.service.ts
154 lines (134 loc) · 4.06 KB
/
feign.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import * as Nacos from "nacos";
import { getLogger } from "log4js";
import { FeignOptions, Mapping } from "./interface";
import { HttpModuleOptions, HttpService } from "@nestjs/axios";
import { Util } from "./util";
import { AxiosResponse } from "axios";
import { URL } from "url";
type Service = {
index: number;
hosts: string[]
};
interface Instance {
instanceId: string;
ip: string;
port: number;
weight: number;
healthy: boolean;
enabled: boolean;
ephemeral: boolean;
clusterName: string;
serviceName: string;
metadata: { [key: string]: string };
instanceHeartBeatInterval: number;
ipDeleteTimeout: number;
instanceIdGenerator: string;
instanceHeartBeatTimeOut: number;
}
type HttpOptions = Omit<HttpModuleOptions, "data" | "params" | "url" | "method" | "baseURL">
const { NacosNamingClient } = Nacos as any;
export class FeignService {
private client: typeof NacosNamingClient;
private services = new Map<string, Service>();
private logger = getLogger("FeignService");
#prefix;
constructor(private readonly options: FeignOptions, private readonly http: HttpService) {
if (options.httpOptions?.prefix) {
this.#prefix = options.httpOptions.prefix;
}
}
async request<R>(mapping: Mapping, data: { [key: string]: unknown } = {}, options: HttpOptions = {}): Promise<AxiosResponse<R>> {
const req: HttpModuleOptions = { ...options };
req.baseURL = await this.getHost(mapping.name);
if (mapping.method === "GET") {
req.params = data;
} else {
req.data = data;
}
if (this.options.secretKey) {
const nonce = Util.generateNonce();
const timestamp = Date.now().toString();
if (!req.headers) {
req.headers = {};
}
req.headers.nonce = nonce;
req.headers.timestamp = timestamp;
const data = mapping.method === "GET" ? req.params : req.data;
req.headers.signature = Util.signature({
...data,
nonce,
timestamp,
secretKey: this.options.secretKey
});
}
return this.http.axiosRef.request<unknown, AxiosResponse<R>>({
...req,
url: mapping.url,
method: mapping.method
});
}
async do<R>(mapping: Mapping, data: { [key: string]: unknown } = {}, options: HttpOptions = {}): Promise<R> {
const res = await this.request<R>(mapping, data, options);
return res?.data;
}
/**
* 初始化服务中心
* */
private async initNacos(): Promise<void> {
if (!this.client) {
if (!this.options.registry.logger) {
this.options.registry.logger = this.logger;
}
this.client = new NacosNamingClient(this.options.registry);
await this.client.ready();
}
}
/**
* 初始化服务
* */
private async initService(serviceName: string, groupName: string = "DEFAULT_GROUP"): Promise<void> {
await this.initNacos();
const instances: Instance[] = await this.client.getAllInstances(serviceName, groupName);
this.setService(serviceName, instances);
this.client.subscribe({ serviceName, groupName }, (info: Instance[]) => this.setService(serviceName, info));
}
/**
* 获取服务节点地址
* */
private async getHost(name: string): Promise<string> {
if (!this.services.has(name)) {
await this.initService(name);
}
const sv = this.services.get(name);
if (!sv?.hosts.length) {
throw new Error(`没有可用的服务[${name}]节点。`);
}
sv.index = (sv.index + 1) % sv.hosts.length;
return sv.hosts[sv.index];
}
/**
* 保存服务节点地址信息
* */
private setService(name: string, instances: Instance[]): void {
const hosts = instances.filter(x => x.enabled).map(x => {
const url = new URL(`http://${x.ip}:${x.port}`);
if (this.#prefix) {
url.pathname = this.#prefix;
}
return url.toString();
});
this.services.set(name, { index: 0, hosts });
}
/**
* 签名
* */
static signature(data: { [i: string]: unknown }): string {
return Util.signature(data);
}
/**
* 设置prefix
* */
setPrefix(prefix: string) {
this.#prefix = prefix;
}
}