forked from getyourguide/vue-class-migrator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
66 lines (59 loc) · 1.93 KB
/
utils.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
import type {
ArrayLiteralExpression,
ObjectLiteralExpression,
ClassDeclaration,
PropertyDeclaration,
Node,
} from 'ts-morph';
import { SyntaxKind } from 'ts-morph';
export const addPropertyObject = (mainObject: ObjectLiteralExpression, propName: string, initializer = '{}'): ObjectLiteralExpression => mainObject
.addPropertyAssignment({
name: propName,
initializer,
})
.getFirstDescendantByKindOrThrow(SyntaxKind.ObjectLiteralExpression);
export const addPropertyArray = (mainObject: ObjectLiteralExpression, propName: string, initializer = '[]'): ArrayLiteralExpression => mainObject
.addPropertyAssignment({
name: propName,
initializer,
})
.getFirstDescendantByKindOrThrow(SyntaxKind.ArrayLiteralExpression);
export const getObjectProperty = (
mainObject: ObjectLiteralExpression,
property: string,
): ObjectLiteralExpression => {
const computedObject = mainObject
.getProperty(property)
?.getFirstDescendantByKind(SyntaxKind.ObjectLiteralExpression);
if (computedObject) {
return computedObject;
}
return addPropertyObject(mainObject, property);
};
export const getArrayProperty = (
mainObject: ObjectLiteralExpression,
property: string,
): ArrayLiteralExpression => {
const computedObject = mainObject
.getProperty(property)
?.getFirstDescendantByKind(SyntaxKind.ArrayLiteralExpression);
if (computedObject) {
return computedObject;
}
return addPropertyArray(mainObject, property);
};
export const extractPropertiesWithDecorator = (
clazz: ClassDeclaration,
decoratorName: string,
): PropertyDeclaration[] => clazz
.getProperties()
.filter((prop) => prop.getDecorator(decoratorName));
export const stringNodeToSTring = (node: Node): string => {
if (
node.isKind(SyntaxKind.StringLiteral)
|| node.isKind(SyntaxKind.NoSubstitutionTemplateLiteral)
) {
return node.getLiteralText();
}
throw new Error(`Node is not a string: ${node.getKindName()}`);
};