-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
73 lines (60 loc) · 2.06 KB
/
Copy pathapi.ts
File metadata and controls
73 lines (60 loc) · 2.06 KB
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
import { resolve } from "node:path";
import { Case } from "change-case-all";
import type { OpenAPIV3_1 } from "openapi-types";
import { getSortedSchemas } from "./base";
import { fileWriter } from "./io";
import { schemaNameToTypeName } from "./schema";
/**
* Generates the main index.ts file with the primary API client class.
* Creates a client class that instantiates all resource classes as properties.
*/
export async function generateIndex(
spec: OpenAPIV3_1.Document,
destDir: string,
) {
const apiName = "SumUp";
if (!spec.components) return;
const outFile = resolve(destDir, "index.ts");
const writer = fileWriter(outFile);
writer.w(`
// Code generated by @sumup/sumup-ts-codegen. DO NOT EDIT.
import { HTTPClient } from './client'
export type { APIConfig } from './client'
export { APIError, SumUpError } from './core'
export type { RequestOptions } from './core'
export * from './webhooks'
export * from './types'
`);
const schemaTypeNames = new Set(
getSortedSchemas(spec).map((schemaName) =>
schemaNameToTypeName(schemaName),
),
);
const tags = spec.tags || [];
tags.sort((a, b) => (a.name > b.name ? 1 : -1));
const resourceClassByTag = new Map<string, string>();
for (const tag of tags) {
const resourceName = Case.pascal(tag.name);
const resourceClassName = schemaTypeNames.has(resourceName)
? `${resourceName}Resource`
: resourceName;
resourceClassByTag.set(tag.name, resourceClassName);
writer.w(`export * from './resources/${Case.kebab(tag.name)}'`);
writer.w(
`import { ${resourceClassName} } from './resources/${Case.kebab(tag.name)}'`,
);
}
writer.w("");
writer.w(`export class ${apiName} extends HTTPClient {`);
for (const tag of tags) {
const resourceClassName = resourceClassByTag.get(tag.name)!;
writer.w(
` /** Access the ${tag.name} API endpoints. */
${Case.camel(tag.name)}: ${resourceClassName} = new ${resourceClassName}(this);`,
);
}
writer.w("}");
writer.w("");
writer.w(`export default ${apiName};`);
await writer.flush();
}