Skip to content

Commit

Permalink
Merge 567d849 into 896a5a7
Browse files Browse the repository at this point in the history
  • Loading branch information
mmkal committed Jan 26, 2020
2 parents 896a5a7 + 567d849 commit b194dc5
Show file tree
Hide file tree
Showing 5 changed files with 236 additions and 192 deletions.
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
**/generated/**
**/dist/**
42 changes: 23 additions & 19 deletions packages/demo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,39 +10,43 @@ export const getApp = () => {
res.status(500).send(`${err}`)
}

app.post('/api/messages', (req, res) => slonik
.connect(async conn => {
const content = req.query.content
const id = await conn.oneFirst(sql.MessageId`
app.post('/api/messages', (req, res) =>
slonik
.connect(async conn => {
const content = req.query.content
const id = await conn.oneFirst(sql.MessageId`
insert into messages(content)
values (${content})
returning id
`)
res.status(201).send({id})
})
.catch(handleError(res))
res.status(201).send({id})
})
.catch(handleError(res)),
)

app.get('/api/messages', (req, res) => slonik
.connect(async conn => {
let {before} = req.query
const messages = await conn.any(sql.Message`
app.get('/api/messages', (req, res) =>
slonik
.connect(async conn => {
let {before} = req.query
const messages = await conn.any(sql.Message`
select * from messages
where id < ${before || 9999999}
order by created_at desc
limit 10
`)
res.status(200).send(messages.map(m => ({
id: m.id,
text: m.content,
secondsAgo: Math.floor((Date.now() - m.created_at.getTime()) / 1000),
})))
})
.catch(handleError(res))
res.status(200).send(
messages.map(m => ({
id: m.id,
text: m.content,
secondsAgo: Math.floor((Date.now() - m.created_at.getTime()) / 1000),
})),
)
})
.catch(handleError(res)),
)

app.get('/', (_req, res) => res.sendFile(resolve(__dirname + '/../index.html')))

return app
}

Expand Down
10 changes: 6 additions & 4 deletions packages/demo/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ process.env.POSTGRES_CONNECTION_STRING = 'postgresql://postgres:postgres@localho

import {getApp} from '../src'
import * as supertest from 'supertest'
import { slonik, sql } from '../src/db';
import {slonik, sql} from '../src/db'

describe('demo app', () => {
const testApp = supertest(getApp())
Expand All @@ -11,11 +11,13 @@ describe('demo app', () => {

it('gets and posts messages', async () => {
const {body: empty} = await testApp.get('/api/messages')

expect(empty).toEqual([])

const {body: {id: newMessageId}} = await testApp.post('/api/messages?content=abc')

const {
body: {id: newMessageId},
} = await testApp.post('/api/messages?content=abc')

expect(newMessageId).toBeGreaterThanOrEqual(0)

const {body: nonEmpty} = await testApp.get('/api/messages')
Expand Down
70 changes: 42 additions & 28 deletions packages/migrator/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import {map, pick} from 'lodash/fp'
import {basename, dirname, join} from 'path'
import * as Umzug from 'umzug'
import {sql, DatabasePoolType} from 'slonik'
import { raw } from 'slonik-sql-tag-raw'
import { inspect } from 'util';
import {raw} from 'slonik-sql-tag-raw'
import {inspect} from 'util'

export interface SlonikMigratorOptions {
slonik: DatabasePoolType
Expand Down Expand Up @@ -43,18 +43,23 @@ export const setupSlonikMigrator = ({
return _log(...args)
}, JSON.stringify)
const createMigrationTable = once(async () => {
void await slonik.query(sql`
void (await slonik.query(sql`
create table if not exists ${sql.identifier([migrationTableName])}(
name text primary key,
hash text not null,
date timestamptz not null default now()
)
`)
`))
})
const hash = (migrationName: string) => createHash('md5')
.update(readFileSync(join(migrationsPath, migrationName), 'utf8').trim().replace(/\s+/g, ' '))
.digest('hex')
.slice(0, 10)
const hash = (migrationName: string) =>
createHash('md5')
.update(
readFileSync(join(migrationsPath, migrationName), 'utf8')
.trim()
.replace(/\s+/g, ' '),
)
.digest('hex')
.slice(0, 10)
const umzug = new Umzug({
logging: log,
migrations: {
Expand All @@ -77,44 +82,47 @@ export const setupSlonikMigrator = ({
log('migrations in database:', migrations)
return migrations
})
.then(migrations => migrations.map(r => {
const name = r.name as string
/* istanbul ignore if */
if (r.hash !== hash(name)) {
log(
`warning:`,
`hash in '${migrationTableName}' table didn't match content on disk.`,
`did you try to change a migration file after it had been run?`,
{migration: r.name, dbHash: r.hash, diskHash: hash(name)}
)
}
return name
}))
.then(migrations =>
migrations.map(r => {
const name = r.name as string
/* istanbul ignore if */
if (r.hash !== hash(name)) {
log(
`warning:`,
`hash in '${migrationTableName}' table didn't match content on disk.`,
`did you try to change a migration file after it had been run?`,
{migration: r.name, dbHash: r.hash, diskHash: hash(name)},
)
}
return name
}),
)
},
async logMigration(name: string) {
await createMigrationTable()
await slonik
.query(sql`
await slonik.query(sql`
insert into ${sql.identifier([migrationTableName])}(name, hash)
values (${name}, ${hash(name)})
`)
},
async unlogMigration(name: string) {
await createMigrationTable()
await slonik
.query(sql`
await slonik.query(sql`
delete from ${sql.identifier([migrationTableName])}
where name = ${name}
`)
}
},
},
})

const migrator: SlonikMigrator = {
up: (name?: string) => umzug.up(name).then(map(pick(['file', 'path']))),
down: (name?: string) => umzug.down(name).then(map(pick(['file', 'path']))),
create: (name: string) => {
const timestamp = new Date().toISOString().replace(/\W/g, '-').replace(/-\d\d-\d\d\dZ/, '')
const timestamp = new Date()
.toISOString()
.replace(/\W/g, '-')
.replace(/-\d\d-\d\d\dZ/, '')
const sqlFileName = `${timestamp}.${name}.sql`
const downDir = join(migrationsPath, 'down')
mkdirSync(downDir, {recursive: true})
Expand All @@ -127,7 +135,13 @@ export const setupSlonikMigrator = ({
const [command, name] = process.argv.slice(2)
command in migrator
? (migrator as any)[command](name)
: console.warn('command not found. ' + inspect({'commands available': Object.keys(migrator), 'command from cli args': command}, {breakLength: Infinity}))
: console.warn(
'command not found. ' +
inspect(
{'commands available': Object.keys(migrator), 'command from cli args': command},
{breakLength: Infinity},
),
)
}

return migrator
Expand Down
Loading

0 comments on commit b194dc5

Please sign in to comment.