feat: Create user model
This commit is contained in:
@@ -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');
|
||||
}
|
||||
|
@@ -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",
|
||||
|
40
packages/backend/src/models/user.ts
Normal file
40
packages/backend/src/models/user.ts
Normal 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;
|
Reference in New Issue
Block a user