Skip to content

Commit

Permalink
[#6] add relationship between models.
Browse files Browse the repository at this point in the history
  • Loading branch information
b051 committed Mar 21, 2017
1 parent 976b748 commit cf268d3
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
import Koa from 'koa'
import body from 'koa-body'
import person from './person/router'
import { errors } from './middleware'
import { errors, track } from './middleware'

export default () => {
const app = new Koa()
app.name = 'techtalk(20170322)'
app.use(body({ multipart: true }))
app.use(track())
app.use(errors())
for (const router of [person]) {
app.use(router.routes()).use(router.allowedMethods())
Expand Down
42 changes: 42 additions & 0 deletions src/history/model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//@flow

import Sequelize from 'sequelize'
import Database from '../database'
import Person from '../person/model'

const History = Database.getInstance().define('history', {
path: Sequelize.STRING,
body: Sequelize.TEXT,
host: Sequelize.STRING,
user_agent: Sequelize.STRING,
time: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
}, {
underscored: true,
timestamps: false,
scopes: {
last(action: string) {
return {
where: { action },
limit: 1,
order: [['time', 'DESC']],
attributes: ['time', 'action'],
include: [{
model: Person,
attributes: ['first_name', 'last_name']
}]
}
}
}
})

Person.hasMany(History, {
onDelete: 'cascade'
})
History.belongsTo(Person, {
constraints: false
})

export default History
1 change: 1 addition & 0 deletions src/middleware/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@

export {default as errors} from './errors'
export {default as auth} from './auth'
export {default as track} from './track'
22 changes: 22 additions & 0 deletions src/middleware/track.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//@flow

import History from '../history/model'

export default () => {
return async (ctx: any, next: Function) => {
await next()
if (ctx.status != 200) {
return
}
const { state: { person } } = ctx
if (person) {
console.log(person.Model.associations.histories.accessors);
await person.createHistory({
path: `${ctx.method} ${ctx.path}`,
body: JSON.stringify(ctx.request.body),
host: ctx.header['host'],
user_agent: ctx.header['user-agent']
})
}
}
}

0 comments on commit cf268d3

Please sign in to comment.