-
Notifications
You must be signed in to change notification settings - Fork 3
/
Typescript POCO to file.groovy
98 lines (79 loc) · 3.25 KB
/
Typescript POCO to file.groovy
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
typeMapping = [
(~/(?i)^bit$|boolean|tinyint\(1\)/) : "boolean",
(~/(?i)^tinyint$/) : "string",
(~/(?i)^uniqueidentifier|uuid$/) : "string",
(~/(?i)^int|integer$/) : "number",
(~/(?i)^bigint$/) : "number",
(~/(?i)^varbinary|image$/) : "string[]",
(~/(?i)^double|float|real$/) : "number",
(~/(?i)^decimal|money|numeric|smallmoney$/) : "number",
(~/(?i)^datetimeoffset$/) : "string",
(~/(?i)^datetime|datetime2|timestamp|date|time$/) : "string",
(~/(?i)^char$/) : "string",
]
notNullableTypes = [ "string", "byte[]" ]
tempString = '';
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}
def generate(table, dir) {
def className = pascalCase(table.getName())
def fields = calcFields(table)
new File(dir, className + ".ts").withPrintWriter { out -> generate(out, className, fields, table) }
}
def generate(out, className, fields, table) {
out.println "export default interface $className {"
fields.each() {
if (it.comment != "")
{
out.println "";
out.println " //${it.comment}";
}
def line = " ${it.name}: ${it.type}"
if (it.comment != "")
{
line += " // ${it.comment}"
}
out.println "${line}"
}
out.println "}"
}
def calcFields(table) {
DasUtil.getColumns(table).reduce([]) { fields, col ->
def spec = Case.LOWER.apply(col.getDataType().getSpecification())
def isArray = spec.contains('[]')
def typeStr = typeMapping.find { p, t -> p.matcher(spec.replace("[]", "")).find() }?.value ?: "string"
if (isArray)
{
typeStr = "${typeStr}[]"
}
def nullable = col.isNotNull() || typeStr in notNullableTypes ? "" : "?"
def pk = DasUtil.getPrimaryKey(table).toString();
fields += [[
primarykey : pk != null && pk != "" && pk.contains("(${col.getName()})") ? true : false,
colname : col.getName(),
spec : spec,
name : camelCase(col.getName()) + nullable,
type : typeStr,
comment : col.comment ? col.comment : ""]]
}
}
def camelCase(str) {
def dict = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str).collect()
def result = '';
dict.forEach{ value ->
if (result == '')
result += value;
else result += value.capitalize()
}
return result;
}
def pascalCase(str) {
com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
}