refactor: Refactor queries by using related query from objectionjs

This commit is contained in:
Faruk AYDIN
2022-01-28 21:08:49 +03:00
committed by Ali BARIN
parent 5b392f3f87
commit 2416ce13a7
9 changed files with 106 additions and 83 deletions

View File

@@ -1,12 +1,15 @@
import { QueryContext, ModelOptions } from 'objection';
import Base from './base';
import Connection from './connection';
import Flow from './flow';
import bcrypt from 'bcrypt';
class User extends Base {
id!: number
email!: string
password!: string
id!: number;
email!: string;
password!: string;
connections?: [Connection];
flows?: [Flow];
static tableName = 'users';
@@ -18,8 +21,8 @@ class User extends Base {
id: { type: 'integer' },
email: { type: 'string', format: 'email', minLength: 1, maxLength: 255 },
password: { type: 'string', minLength: 1, maxLength: 255 },
}
}
},
};
static relationMappings = () => ({
connections: {
@@ -29,8 +32,16 @@ class User extends Base {
from: 'users.id',
to: 'connections.user_id',
},
}
})
},
flows: {
relation: Base.HasManyRelation,
modelClass: Flow,
join: {
from: 'users.id',
to: 'flows.user_id',
},
},
});
login(password: string) {
return bcrypt.compare(password, this.password);
@@ -42,14 +53,14 @@ class User extends Base {
async $beforeInsert(queryContext: QueryContext) {
await super.$beforeInsert(queryContext);
await this.generateHash()
await this.generateHash();
}
async $beforeUpdate(opt: ModelOptions, queryContext: QueryContext) {
await super.$beforeUpdate(opt, queryContext);
if(this.password) {
await this.generateHash()
if (this.password) {
await this.generateHash();
}
}
}