-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
gen-clients.js
82 lines (69 loc) · 2.26 KB
/
gen-clients.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
import Handlebars from "handlebars";
import pbjs from "protobufjs";
// Load Protocol Buffer from specified .proto file
const pb = pbjs.loadSync("api/vendor/protocoltypes.proto");
// Function to decapitalize the first letter of a string
const uncap = (str) => str.charAt(0).toLowerCase() + str.slice(1);
const getInterface = (typ) => {
const parts = typ.split(".");
const ilast = `I${parts.pop()}`;
parts.push(ilast);
return parts.join(".");
};
// Define an array of services
const services = ["weshnet.protocol.v1.ProtocolService"];
// Prepare Handlebars templates
const serviceClientTemplate = Handlebars.compile(`
import api from './api/index.d'
import { Unary, ResponseStream, RequestStream } from './types'
export type ServiceClientType<S> = {{#each services}} {{this}} {{/each}}never;
`);
const ClientTemplate = Handlebars.compile(`
export interface {{name}}Client {
{{#each methods}}
{{this.name}}: {{this.type}}<api.{{this.svcName}}.{{this.request}}, api.{{this.svcName}}.{{this.reply}}>,
{{/each}}
}
`);
// Gather data for ServiceClientType
let serviceData = {
services: services.map((svcType) => {
const svc = pb.lookup(svcType);
return `S extends typeof api.${svc.parent.parent.name}.${svc.name} ? ${svc.name}Client :`;
}),
};
// Generate and output ServiceClientType
console.log(serviceClientTemplate(serviceData));
// Gather data for each Client and output
for (const svcType of services) {
const svc = pb.lookup(svcType);
const methodsData = Object.entries(svc.methods).map(([key, method]) => {
let rpcType = "";
if (!method.requestStream && !method.responseStream) {
// Unary
rpcType = "Unary";
} else if (method.requestStream && !method.responseStream) {
// Request Stream
rpcType = "RequestStream";
} else if (!method.requestStream && method.responseStream) {
// Response Stream
rpcType = "ResponseStream";
} else {
// Dubplex
rpcType = "never";
}
const name = uncap(key);
return {
name: name,
request: getInterface(method.requestType),
reply: method.responseType,
type: rpcType,
svcName: `${svc.parent.parent.name}`,
};
});
let ClientData = {
name: svc.name,
methods: methodsData,
};
console.log(ClientTemplate(ClientData));
}