forked from asyncapi/modelina
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractRenderer.ts
83 lines (75 loc) · 2.32 KB
/
AbstractRenderer.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
77
78
79
80
81
82
83
import { AbstractGenerator, CommonGeneratorOptions } from './AbstractGenerator';
import { CommonModel, CommonInputModel, Preset } from '../models';
import { FormatHelpers, IndentationTypes } from '../helpers';
/**
* Abstract renderer with common helper methods
*/
export abstract class AbstractRenderer<
O extends CommonGeneratorOptions = CommonGeneratorOptions,
G extends AbstractGenerator = AbstractGenerator
> {
constructor(
protected readonly options: O,
readonly generator: G,
protected readonly presets: Array<[Preset, unknown]>,
protected readonly model: CommonModel,
protected readonly inputModel: CommonInputModel,
public dependencies: string[] = []
) {}
/**
* Adds a dependency while ensuring that only one dependency is preset at a time.
*
* @param dependency complete dependency string so it can be rendered as is.
*/
addDependency(dependency: string): void {
if (!this.dependencies.includes(dependency)) {
this.dependencies.push(dependency);
}
}
renderLine(line: string): string {
return `${line}\n`;
}
renderBlock(lines: string[], newLines = 1): string {
const n = Array(newLines).fill('\n').join('');
return lines.filter(Boolean).join(n);
}
indent(
content: string,
size?: number,
type?: IndentationTypes,
): string {
size = size || this.options.indentation?.size;
type = type || this.options.indentation?.type;
return FormatHelpers.indent(content, size, type);
}
runSelfPreset(): Promise<string> {
return this.runPreset('self');
}
runAdditionalContentPreset(): Promise<string> {
return this.runPreset('additionalContent');
}
async runPreset(
functionName: string,
params: Record<string, unknown> = {},
): Promise<string> {
let content = '';
for (const [preset, options] of this.presets) {
if (typeof preset[String(functionName)] === 'function') {
const presetRenderedContent: any = await preset[String(functionName)]({
...params,
renderer: this,
content,
options,
model: this.model,
inputModel: this.inputModel
});
if (typeof presetRenderedContent === 'string') {
content = presetRenderedContent;
} else {
content = '';
}
}
}
return content;
}
}