-
Notifications
You must be signed in to change notification settings - Fork 1
/
services.ts
76 lines (57 loc) · 2.08 KB
/
services.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
import { Method, Service, Type } from 'protobufjs';
import { getCommentBlock, getImport, Import, toLowerCaseFirstLetter } from './utils';
export function getServiceInfo(service: Service) {
let typeString = `export interface ${service.name} {\n`;
let imports: Array<Import> = [];
Object.values(service.methods).forEach((method) => {
const { code, typeImports } = getMethodCode(method);
imports = imports.concat(typeImports);
typeString += code;
});
typeString = `${typeString}\n}`;
return { imports, typeString };
}
function getMethodCode(method: Method) {
const typeImports: Array<Import> = [];
method.resolve();
if (!method.resolvedRequestType || !method.resolvedResponseType) {
throw new Error(`Could not resolve type for ${method.name}`);
}
const { code: requestCode, import: requestImport } = getServiceTypeInfo(
method,
method.resolvedRequestType
);
const { code: responseCode, import: responseImport } = getServiceTypeInfo(
method,
method.resolvedResponseType
);
if (requestImport) {
typeImports.push(requestImport);
}
if (responseImport) {
typeImports.push(responseImport);
}
return {
typeImports,
code: `${getCommentBlock(method)}${toLowerCaseFirstLetter(
method.name
)}(request: ${requestCode}): Promise<${responseCode}>,\n\n`,
};
}
function getServiceTypeInfo(method: Method, type: Type): { code: string; import: Import | null } {
switch (type.fullName) {
case '.google.protobuf.Value':
return { code: 'any', import: null };
case '.google.protobuf.ListValue':
return { code: 'any[]', import: null };
case '.google.protobuf.Struct':
return { code: 'Record<string, any>', import: null };
case '.google.protobuf.Empty':
return { code: 'Record<string, never>', import: null };
default:
return {
code: type.name,
import: getImport(method, type),
};
}
}