-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathtypescript.ts
More file actions
67 lines (58 loc) · 2.17 KB
/
Copy pathtypescript.ts
File metadata and controls
67 lines (58 loc) · 2.17 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
/**
* Generate typescript interface from table schema
* Created by xiamx on 2016-08-10.
*/
import { TableDefinition } from './schemaInterfaces'
import Options from './options'
function nameIsReservedKeyword (name: string): boolean {
const reservedKeywords = [
'string',
'number',
'package'
]
return reservedKeywords.indexOf(name) !== -1
}
function normalizeName (name: string, options: Options): string {
if (nameIsReservedKeyword(name)) {
return name + '_'
} else {
return name
}
}
export function generateTableInterface (tableNameRaw: string, tableDefinition: TableDefinition, options: Options) {
const tableName = options.transformTypeName(tableNameRaw)
const members = options.getKeys(tableDefinition).map((columnNameRaw) => {
const columnName = options.transformColumnName(columnNameRaw)
return `${columnName}: ${tableName}Fields.${normalizeName(columnName, options)};`
})
return `
export interface ${normalizeName(tableName, options)} {
${members.join('\n')}
}
`
}
export function generateEnumType (enumObject: any, options: Options) {
const enumNamespace = options.getKeys(enumObject).map((enumNameRaw) => {
const enumName = options.transformTypeName(enumNameRaw)
return `export type ${enumName} = '${options.getMaybeSorted(enumObject[enumNameRaw]).join(`' | '`)}';`
})
return `
export namespace customTypes {
${enumNamespace.join('\n')}
}
`
}
export function generateTableTypes (tableNameRaw: string, tableDefinition: TableDefinition, options: Options) {
const tableName = options.transformTypeName(tableNameRaw)
const tableNamespace = options.getKeys(tableDefinition).map((columnNameRaw) => {
let type = tableDefinition[columnNameRaw].tsType
let nullable = tableDefinition[columnNameRaw].nullable ? '| null' : ''
const columnName = options.transformColumnName(columnNameRaw)
return `export type ${normalizeName(columnName, options)} = ${type}${nullable};`
})
return `
export namespace ${tableName}Fields {
${tableNamespace.join('\n')}
}
`
}