Skip to content

Instantly share code, notes, and snippets.

@eugenehp
Forked from statico/...README.md
Created February 7, 2019 07:31
Show Gist options
  • Save eugenehp/6c0d1097fa7a8dde7c85f3d335157156 to your computer and use it in GitHub Desktop.
Save eugenehp/6c0d1097fa7a8dde7c85f3d335157156 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"]
}
@nischalshakya95
Copy link

This doesn't work with me. These are my dependencies.
"dependencies": {
"dotenv": "^8.2.0",
"knex": "^0.20.4",
"mysql": "^2.17.1",
"ts-node": "^8.5.4",
"typescript": "^3.7.3"
},
"devDependencies": {
"@types/knex": "^0.16.1",
"@types/node": "^12.12.16"
}
While generating migration file it's saying unexpected token export

@FreedomBen
Copy link

FreedomBen commented May 14, 2020

Line 7 of db.ts needs a trailing comma. Can you fork and send PRs to gists?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment