/
typescript.ts
41 lines (33 loc) · 1.3 KB
/
typescript.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
import {
Generator,
GetMethodTypings,
GetMethodAliasName,
} from "./generator-interface";
import { ContentDescriptorObject, MethodObject } from "@open-rpc/meta-schema";
import { languageSafeName, ensureSchemaTitles } from "@etclabscore/json-schema-to-types/build/utils";
export const getMethodAliasName: GetMethodAliasName = (method) => {
return languageSafeName(method.name);
};
const getMethodTyping = (method: MethodObject): string => {
const result = method.result as ContentDescriptorObject;
const resultName = ensureSchemaTitles({ ...result.schema });
const resultTypeName = `Promise<${languageSafeName(resultName.title as string)}>`;
const methodAliasName = getMethodAliasName(method);
const params = (method.params as ContentDescriptorObject[]).map(
(param) => [
`${param.name}${param.required ? "" : "?"}: `,
`${languageSafeName(ensureSchemaTitles(param.schema).title as string)}`,
].join(""),
).join(", ");
return `export type ${methodAliasName} = (${params}) => ${resultTypeName};`;
};
export const getMethodTypings: GetMethodTypings = (openrpcDocument) => {
return openrpcDocument.methods
.map((method: MethodObject) => getMethodTyping(method))
.join("\n");
};
const generator: Generator = {
getMethodAliasName,
getMethodTypings,
};
export default generator;