Created
April 11, 2020 03:17
-
-
Save promaty/4b043dade8ab4fddc60818ada9abf7db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*************** Migrations ***************/ | |
exports.up = function(knex) { | |
return knex.schema.withSchema('ObjectionTest') | |
.createTable('Users', function (table) { | |
table.increments('id') | |
table.integer('user_email_id') | |
table.string('address') | |
table.verified('boolean') | |
table.timestamp('created_at').defaultTo(knex.fn.now()) | |
table.timestamp('updated_at').defaultTo(knex.fn.now()) | |
}) | |
.createTable('UserSessions', function (table) { | |
table.increments('id') | |
table.integer('user_id') | |
table.enum('user_type', ['admin', 'peasant']) | |
table.string('session_id') | |
table.timestamp('expires_at') | |
table.timestamp('created_at').defaultTo(knex.fn.now()) | |
table.timestamp('updated_at').defaultTo(knex.fn.now()) | |
}); | |
}; | |
exports.down = function(knex) { | |
return knex.schema.withSchema('ObjectionTest') | |
.dropTable("Users") | |
.dropTable("UserSessions"); | |
}; | |
/*************** Relational models ***************/ | |
const SESSION_EXPIRES = 30 * DAYS | |
class UserSession extends Model { | |
static get tableName() { | |
return 'UserSessions'; | |
} | |
} | |
class User extends Model { | |
static get tableName() { | |
return 'Users'; | |
} | |
static get relationMappings() { | |
return { | |
sessions: { | |
relation: Model.HasManyRelation, | |
modelClass: UserSession, | |
// polymorphic relation for returns | |
filter(builder) { | |
builder.where('user_type', 'peasant') | |
}, | |
// polymorphic relation for inserts | |
beforeInsert(model) { | |
model.user_type = 'peasant'; | |
model.expires_at = knex.fn.now() + SESSION_EXPIRES | |
model.updated_at = knex.fn.now() | |
}, | |
join: { | |
from: 'Users.id', | |
to: 'UserSessions.user_id' | |
} | |
} | |
}; | |
} | |
} | |
/*************** Query examples ***************/ | |
// new user | |
const user = await Person.query().insert({address}) | |
// get user | |
const user = await User.query().where({address}) | |
// verify user | |
const user = await Person.query().update({verified}) | |
// Log in | |
user.$relatedQuery('sessions').insert({session_id: session.id}) | |
// Log out | |
user.$relatedQuery('sessions').delete().where({session_id: session.id}) | |
// Log out all devices | |
user.$relatedQuery('sessions').delete() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment