-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
97 lines (87 loc) · 2.76 KB
/
app.js
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
const serviceTypeHTTP = "http"
const serviceTypeHTTPS = "https"
const serviceTypeGRPC = "grpc"
const serviceTypeWebSocket = "ws"
module.exports.templateTags = [{
name: 'consulServiceResolver',
displayName: 'Consul Service Resolver',
liveDisplayName: function(args) {
return "Consul: " + buildURL(args[1].value, args[2].value, args[3].value)
},
description: 'Helper to resolve consul service IP.',
args: [
{
displayName: 'Consul Server',
description: 'Consul server address',
type: 'string',
},
{
displayName: 'Protocol ',
description: 'Service protocol type (HTTP/GRPC/Websocket)',
type: 'enum',
defaultValue: serviceTypeHTTP,
options: [
{
displayName: 'HTTP',
value: serviceTypeHTTP
},
{
displayName: 'HTTPS',
value: serviceTypeHTTPS
},
{
displayName: 'gRPC',
value: serviceTypeGRPC
},
{
displayName: 'WebSocket',
value: serviceTypeWebSocket
},
]
},
{
displayName: 'Service Name',
description: 'service name',
type: 'string'
},
{
displayName: 'Port',
description: 'Service port',
type: 'number',
defaultValue: 80
},
{
displayName: 'Override',
description: 'If this is not empty, the server URL will use this value instead.',
type: 'string',
defaultValue: ''
}
],
async run (ctx, consulServer, protocol, service, port, override) {
const useServerIP = async function() {
const ip = await getIP(ctx, consulServer, service)
return buildURL(protocol, ip, port)
}
if (override) {
console.log(override)
}
return override ? override : useServerIP()
}
}];
function buildURL(protocol, service, port) {
if (protocol == serviceTypeHTTP && port == 80) {
return protocol + "://" + service
}
if (protocol == serviceTypeHTTPS && port == 443) {
return protocol + "://" + service
}
return protocol + "://" + service + ":" + port
}
async function getIP(context, consulServer, serviceName) {
const response = await fetch(`https://${consulServer}/v1/health/service/${serviceName}?passing=true`)
const items = await response.json()
if (items.size < 1) {
throw new Error(`no ${serviceName} service healthy`)
}
return items[0].Service.Address
}