Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option for consistently sorting generated output #102

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions bin/schemats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
import * as yargs from 'yargs'
import * as fs from 'fs'
import { typescriptOfSchema, getDatabase } from '../src/index'
import Options from '../src/options'

interface SchematsConfig {
conn: string,
table: string[] | string,
schema: string,
output: string,
order: boolean,
camelCase: boolean,
noHeader: boolean,
}
Expand Down Expand Up @@ -41,6 +41,7 @@ let argv: SchematsConfig = yargs
.alias('C', 'camelCase')
.describe('C', 'Camel-case columns')
.describe('noHeader', 'Do not write header')
.describe('order', 'Sort type and interface properties')
.demand('o')
.nargs('o', 1)
.alias('o', 'output')
Expand All @@ -61,7 +62,7 @@ let argv: SchematsConfig = yargs
}

let formattedOutput = await typescriptOfSchema(
argv.conn, argv.table, argv.schema, { camelCase: argv.camelCase, writeHeader: !argv.noHeader })
argv.conn, argv.table, argv.schema, { camelCase: argv.camelCase, order: argv.order, writeHeader: !argv.noHeader })
fs.writeFileSync(argv.output, formattedOutput)

} catch (e) {
Expand Down
22 changes: 16 additions & 6 deletions src/options.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,32 @@
import { camelCase, upperFirst } from 'lodash'
import { camelCase, upperFirst, sortBy, keys } from 'lodash'

const DEFAULT_OPTIONS: OptionValues = {
writeHeader: true,
camelCase: false
const DEFAULT_OPTIONS: Required<OptionValues> = {
camelCase: false,
order: false,
writeHeader: true
}

export type OptionValues = {
camelCase?: boolean
order?: boolean
writeHeader?: boolean // write schemats description header
}

export default class Options {
public options: OptionValues
public options: Required<OptionValues>

constructor (options: OptionValues = {}) {
constructor (options?: OptionValues) {
this.options = {...DEFAULT_OPTIONS, ...options}
}

getKeys (obj: any): string[] {
return this.getMaybeSorted(keys(obj))
}

getMaybeSorted (arr: string[]): string[] {
return this.options.order ? sortBy(arr) : arr
}

transformTypeName (typename: string) {
return this.options.camelCase ? upperFirst(camelCase(typename)) : typename
}
Expand Down
7 changes: 3 additions & 4 deletions src/schemaPostgres.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as PgPromise from 'pg-promise'
import { mapValues } from 'lodash'
import { keys } from 'lodash'
import { mapValues, keys } from 'lodash'
import Options from './options'

import { TableDefinition, Database } from './schemaInterfaces'
Expand Down Expand Up @@ -67,7 +66,7 @@ export class PostgresDatabase implements Database {
return column
case '_varchar':
case '_text':
case '_citext':
case '_citext':
case '_uuid':
case '_bytea':
column.tsType = 'Array<string>'
Expand All @@ -81,7 +80,7 @@ export class PostgresDatabase implements Database {
return column
default:
if (customTypes.indexOf(column.udtName) !== -1) {
column.tsType = options.transformTypeName(column.udtName)
column.tsType = `customTypes.${options.transformTypeName(column.udtName)}`
return column
} else {
console.log(`Type [${column.udtName} has been mapped to [any] because no specific type has been found.`)
Expand Down
33 changes: 16 additions & 17 deletions src/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
* Created by xiamx on 2016-08-10.
*/

import * as _ from 'lodash'

import { TableDefinition } from './schemaInterfaces'
import Options from './options'

Expand All @@ -27,42 +25,43 @@ function normalizeName (name: string, options: Options): string {

export function generateTableInterface (tableNameRaw: string, tableDefinition: TableDefinition, options: Options) {
const tableName = options.transformTypeName(tableNameRaw)
let members = ''
Object.keys(tableDefinition).map(c => options.transformColumnName(c)).forEach((columnName) => {
members += `${columnName}: ${tableName}Fields.${normalizeName(columnName, options)};\n`
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}
${members.join('\n')}
}
`
}

export function generateEnumType (enumObject: any, options: Options) {
let enumString = ''
for (let enumNameRaw in enumObject) {
const enumNamespace = options.getKeys(enumObject).map((enumNameRaw) => {
const enumName = options.transformTypeName(enumNameRaw)
enumString += `export type ${enumName} = `
enumString += enumObject[enumNameRaw].map((v: string) => `'${v}'`).join(' | ')
enumString += ';\n'
}
return enumString
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)
let fields = ''
Object.keys(tableDefinition).forEach((columnNameRaw) => {
const tableNamespace = options.getKeys(tableDefinition).map((columnNameRaw) => {
let type = tableDefinition[columnNameRaw].tsType
let nullable = tableDefinition[columnNameRaw].nullable ? '| null' : ''
const columnName = options.transformColumnName(columnNameRaw)
fields += `export type ${normalizeName(columnName, options)} = ${type}${nullable};\n`
return `export type ${normalizeName(columnName, options)} = ${type}${nullable};`
})

return `
export namespace ${tableName}Fields {
${fields}
${tableNamespace.join('\n')}
}
`
}
4 changes: 2 additions & 2 deletions test/integration/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ describe('schemats cli tool integration testing', () => {
it('should run without error', () => {
let {status, stdout, stderr} = spawnSync('node', [
'bin/schemats', 'generate',
'-c', process.env.POSTGRES_URL,
'-c', process.env.POSTGRES_URL as string,
'-o', '/tmp/schemats_cli_postgres.ts'
], { encoding: 'utf-8' })
console.log('opopopopop', stdout, stderr)
Expand All @@ -27,7 +27,7 @@ describe('schemats cli tool integration testing', () => {
it('should run without error', () => {
let {status} = spawnSync('node', [
'bin/schemats', 'generate',
'-c', process.env.MYSQL_URL,
'-c', process.env.MYSQL_URL as string,
'-s', 'test',
'-o', '/tmp/schemats_cli_postgres.ts'
])
Expand Down
17 changes: 10 additions & 7 deletions test/testUtility.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as assert from 'assert'
import * as fs from 'mz/fs'
import { typescriptOfSchema, Database } from '../src/index'
import Options from '../src/options'
import * as ts from 'typescript';
import * as ts from 'typescript'

const diff = require('diff')
interface IDiffResult {
Expand All @@ -11,13 +11,13 @@ interface IDiffResult {
removed?: boolean
}

export function compile(fileNames: string[], options: ts.CompilerOptions): boolean {
export function compile (fileNames: string[], options: ts.CompilerOptions): boolean {
let program = ts.createProgram(fileNames, options)
let emitResult = program.emit()
let exitCode = emitResult.emitSkipped ? 1 : 0
return exitCode === 0
}
export async function compare(goldStandardFile: string, outputFile: string): Promise<boolean> {
export async function compare (goldStandardFile: string, outputFile: string): Promise<boolean> {

let gold = await fs.readFile(goldStandardFile, {encoding: 'utf8'})
let actual = await fs.readFile(outputFile, {encoding: 'utf8'})
Expand All @@ -38,15 +38,14 @@ export async function compare(goldStandardFile: string, outputFile: string): Pro
}
}


export async function loadSchema(db: Database, file: string) {
export async function loadSchema (db: Database, file: string) {
let query = await fs.readFile(file, {
encoding: 'utf8'
})
return await db.query(query)
}

export async function writeTsFile(inputSQLFile: string, inputConfigFile: string, outputFile: string, db: Database) {
export async function writeTsFile (inputSQLFile: string, inputConfigFile: string, outputFile: string, db: Database) {
await loadSchema(db, inputSQLFile)
const config: any = require(inputConfigFile)
let formattedOutput = await typescriptOfSchema(
Expand All @@ -57,3 +56,7 @@ export async function writeTsFile(inputSQLFile: string, inputConfigFile: string,
)
await fs.writeFile(outputFile, formattedOutput)
}

export function assertEqualCode (expected: string, actual: string, message?: string) {
return assert.equal(actual.replace(/\s+/g, ' ').trim(), expected.replace(/\s+/g, ' ').trim(), message)
}
2 changes: 1 addition & 1 deletion test/unit/schemaPostgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@ describe('PostgresDatabase', () => {
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td, ['CustomType'], options).column.tsType, 'CustomType')
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td, ['CustomType'], options).column.tsType, 'customTypes.CustomType')
})
})
describe('maps to any', () => {
Expand Down
Loading