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

spike: Add TypeScriptTypes dumper #109

Closed
wants to merge 17 commits into from
Closed
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
128 changes: 126 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,14 @@
"start": "ts-node-dev src/server/app.ts | pino-pretty --colorize",
"dev": "run-s clean format start",
"pkg": "run-s clean format build:server && pkg --out-path bin .pkg.config.json",
"test": "run-s build:server && node -r esm ./node_modules/.bin/mocha 'test/**/*.js' --recursive"
"test": "run-s build:server && node -r esm ./node_modules/.bin/mocha 'test/**/*.js' --recursive",
"unit-test": "run-s build:server && node -r esm ./node_modules/.bin/mocha 'test/lib/*.js' --recursive"
},
"dependencies": {
"@types/prettier": "^2.2.3",
"pg": "^7.0.0",
"pg-format": "^1.0.4"
"pg-format": "^1.0.4",
"prettier": "^2.0.5"
},
"devDependencies": {
"@types/crypto-js": "^3.1.47",
Expand All @@ -43,8 +46,8 @@
"npm-run-all": "^4.1.5",
"pino-pretty": "^4.7.1",
"pkg": "^4.4.8",
"prettier": "^2.0.5",
"rimraf": "^3.0.2",
"sinon": "^10.0.0",
"ts-node-dev": "^1.1.6",
"typescript": "^3.9.3"
}
Expand Down
93 changes: 93 additions & 0 deletions src/lib/TypeScriptInterfaces.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import prettier from "prettier"
import parserTypescript from "prettier/parser-typescript"

import { PostgresMeta } from "."
import { PostgresColumn } from "./types"

const parseColumns = (columns: PostgresColumn[]) => {
const tableGroupings = columns.reduce((prev, current) => {
if (current.table in prev) {
prev[current.table].push(current)
} else {
prev[current.table] = [current]
}

return prev
}, {} as { [key: string]: PostgresColumn[] })

return Object
.entries(tableGroupings)
.map(([table, columns]: [string, PostgresColumn[]]) => {
return `${table}: { ${columns.map(parseColumn).join(';')} };`
}).join('')
}

const parseColumn = (column: PostgresColumn) => {
const dataType = postgresToTypescriptType(column.format)
const nullableSuffix = column.is_nullable ? '?' : ''

return `${column.name}${nullableSuffix}: ${dataType}`
}

const postgresToTypescriptType = (format: string) => {
switch (format) {
// adapted from https://github.com/jawj/zapatos/blob/master/src/generate/pgTypes.ts
case 'int8':
case 'int2':
case 'int4':
case 'float4':
case 'float8':
case 'numeric':
case 'money':
case 'oid':
return 'number'
case 'date':
case 'timestamp':
case 'timestamptz':
return 'Date'
case 'bpchar':
case 'char':
case 'varchar':
case 'text':
case 'citext':
case 'uuid':
case 'bytea':
case 'inet':
case 'time':
case 'timetz':
case 'interval':
case 'name':
case 'json':
case 'jsonb':
return 'string'
case 'bool':
return 'boolean'
default:
return 'any'
}
}

export default class TypeScriptInterfaces {
pgMeta: PostgresMeta

constructor({ pgMeta }: { pgMeta: PostgresMeta }) {
this.pgMeta = pgMeta
}

async dump(): Promise<any> {
const { data, error } = await this.pgMeta.columns.list()
// TODO: handle error

if (data) {
const tableDefString = parseColumns(data)
let output = `export interface definitions { ${tableDefString} };`

// Prettify output
let prettierOptions: prettier.Options = {
parser: "typescript",
plugins: [parserTypescript],
};
return prettier.format(output, prettierOptions);
}
}
}
72 changes: 72 additions & 0 deletions test/lib/TypeScriptInterfaces.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
var assert = require('assert')
var sinon = require('sinon')

import TypeScriptInterfaces from '../../bin/src/lib/TypeScriptInterfaces'
import { PostgresMeta } from '../../bin/src/lib'


describe('.dump()', () => {
it('handles nullable columns', async () => {
const pgMeta = new PostgresMeta({ connectionString: '', max: 1 })
const columnsData = [
{
table: 'todos',
name: 'name',
format: 'text',
is_nullable: true
}
]
sinon
.stub(pgMeta.columns, "list")
.returns(Promise.resolve({ data: columnsData }))

const example = new TypeScriptInterfaces({ pgMeta: pgMeta });

const expected = `export interface definitions {
todos: { name?: string };
}
`

assert.equal(await example.dump(), expected)
})

it('returns a string of TypeScript types', async () => {
const pgMeta = new PostgresMeta({ connectionString: '', max: 1 })
const columnsData = [
{
table: 'todos',
name: 'id',
format: 'int8'
},
{
table: 'todos',
name: 'done',
format: 'bool'
},
{
table: 'todos',
name: 'done_at',
is_nullable: true,
format: 'date',
},
{
table: 'memes',
name: 'example',
format: 'some-invalid-format',
}
]
sinon
.stub(pgMeta.columns, "list")
.returns(Promise.resolve({ data: columnsData }))

const example = new TypeScriptInterfaces({ pgMeta: pgMeta });

const expected = `export interface definitions {
todos: { id: number; done: boolean; done_at?: Date };
memes: { example: any };
}
`

assert.equal(await example.dump(), expected)
})
})