feat: Create user model

This commit is contained in:
Faruk AYDIN
2021-10-06 23:37:45 +02:00
committed by Ali BARIN
parent 3f56da5efb
commit d03e34e9cc
4 changed files with 102 additions and 2 deletions

View File

@@ -0,0 +1,17 @@
import { Knex } from "knex";
export async function up(knex: Knex): Promise<void> {
return knex.schema.createTable('users', (table) => {
table.increments('id');
table.string('email').unique().notNullable();
table.string('password').notNullable();
table.timestamps(true, true);
});
}
export async function down(knex: Knex): Promise<void> {
return knex.schema.dropTable('users');
}

View File

@@ -8,10 +8,12 @@
"start": "node dist/index.js",
"test": "echo \"Error: run tests from root\" && exit 1",
"db:create": "ts-node ./bin/database/create.ts",
"db:drop": "ts-node ./bin/database/drop.ts",
"db:migration:create": "knex migrate:make",
"db:drop": "ts-node ./bin/database/drop.ts"
"db:migrate": "knex migrate:latest"
},
"dependencies": {
"bcrypt": "^5.0.1",
"cors": "^2.8.5",
"debug": "~2.6.9",
"dotenv": "^10.0.0",
@@ -47,6 +49,7 @@
"url": "https://github.com/automatisch/automatisch/issues"
},
"devDependencies": {
"@types/bcrypt": "^5.0.0",
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/http-errors": "^1.8.1",

View File

@@ -0,0 +1,40 @@
import { Model, QueryContext, ModelOptions } from 'objection';
import bcrypt from 'bcrypt';
class User extends Model {
id!: number
email!: string
password!: string
static tableName = 'users';
static jsonSchema = {
type: 'object',
required: ['email', 'password'],
properties: {
id: { type: 'integer' },
email: { type: 'email', minLength: 1, maxLength: 255 },
password: { type: 'string', minLength: 1, maxLength: 255 },
}
}
async generateHash() {
this.password = await bcrypt.hash(this.password, 10);
}
async $beforeInsert(queryContext: QueryContext) {
await super.$beforeInsert(queryContext);
await this.generateHash()
}
async $beforeUpdate(opt: ModelOptions, queryContext: QueryContext) {
await super.$beforeUpdate(opt, queryContext);
if(this.password) {
await this.generateHash()
}
}
}
export default User;