Skip to content

Instantly share code, notes, and snippets.

@statico
Last active February 7, 2019 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save statico/f2c5df1a2fae73e3492bc9346170a622 to your computer and use it in GitHub Desktop.
Save statico/f2c5df1a2fae73e3492bc9346170a622 to your computer and use it in GitHub Desktop.
Knex & TypeScript

Goals

  • Make all parts of Knex TypeScript-safe
import * as Knex from 'knex'
import { log } from './logging'
export const config = {
client: 'pg',
connection: {
host: process.env.POSTGRES_HOST
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB
},
migrations: {
// This is missing from the TypeScript types currently.
stub: 'migration.stub'
}
}
const instance: Knex = Knex(config as Knex.Config)
log.info(
`Will connect to postgres://${config.connection.user}@${
config.connection.host
}/${config.connection.database}`
)
instance
.raw('select 1')
.then(() => {
log.info(`Connected to database - OK`)
})
.catch(err => {
log.error(`Failed to connect to database: ${err}`)
process.exit(1)
})
export const db = () => instance
// Returns a timestamp suitable for inserting into Postgres
export const timestamp = (): string => new Date().toUTCString()
import { config } from './db'
module.exports = config
import * as Knex from 'knex'
exports.up = (knex: Knex) => knex.schema
exports.down = (knex: Knex) => knex.schema
{
...
"scripts": {
"db:migrate": "knex migrate:latest",
"db:rollback": "knex migrate:rollback",
"db:createMigration": "knex migrate:make"
},
"dependencies": {
"knex": "^0.15.2",
"pg": "^7.5.0",
},
"devDependencies": {
"@types/knex": "^0.14.26",
}
}
// Optional - Mostly provided here for reference
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"jsx": "react",
"strict": true,
"resolveJsonModule": true
},
"exclude": ["node_modules"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment