1.0.4 • Published 4 years ago
crunch-sequelize v1.0.4
Описание
Модуль предоставляет несколько декораторов для более быстрого объявления моделей и функцию, которая инициализирует модели
Установка
npm i crunch-sequelize
Использование
user.ts
import { Association, Column, Table } from 'crunch-sequelize';
import { DateTime } from 'luxon';
import { DataTypes, Model } from 'sequelize';
import { LocalUser } from './local-user';
@Table()
export class User extends Model {
@Column({
type: DataTypes.DATE,
})
public bornAt?: Date;
@Column({
allowNull: false,
type: DataTypes.STRING(256),
})
public fullName: string;
@Column({
type: DataTypes.VIRTUAL,
})
public get age(): number {
if (this.bornAt == null) return undefined;
const bornAt = DateTime.fromJSDate(this.bornAt);
const now = DateTime.local();
const diffInYears = now.diff(bornAt, 'years');
return Math.floor(diffInYears.as('years'));
};
@Association('hasOne', {
foreignKey: 'userId',
target: () => LocalUser,
})
public localUser?: LocalUser;
}
local-user.ts
import { Association, Column, Table, Hook } from 'crunch-sequelize';
import { createHash } from 'crypto';
import { DataTypes, Model } from 'sequelize';
import { Role } from './role';
import { User } from './user';
const hashPassword = (password: string): string => {
return createHash('sha1')
.update(`${password}`)
.digest('hex');
};
@Table({
defaultScope: {
attributes: {
exclude: ['password'],
},
},
timestamps: false,
})
export class LocalUser extends Model {
@Hook('beforeCreate', 'beforeUpdate')
public static beforeUpsert(instance: LocalUser) {
if (instance.password != null) {
instance.password = hashPassword(instance.password);
}
}
@Column({
allowNull: false,
type: DataTypes.STRING(64),
})
public password: string;
@Column({
allowNull: false,
type: DataTypes.STRING(64),
unique: true,
})
public username: string;
@Column({
allowNull: false,
type: DataTypes.INTEGER,
})
public userId: number;
@Association('belongsToMany', {
foreignKey: 'localUserId',
target: () => Role,
through: 'LocalUserRoles',
otherKey: 'roleId',
})
public roles?: Role[];
@Association('belongsTo', {
foreignKey: 'userId',
target: () => User,
})
public user: User;
public checkPassword(password: string): boolean {
return hashPassword(password) === this.password;
}
}
role.ts
import { Association, Column, Table } from 'crunch-sequelize';
import { DataTypes, Model } from 'sequelize';
import { LocalUser } from './local-user';
@Table()
export class Role extends Model {
@Column({
allowNull: false,
type: DataTypes.STRING(64),
})
public code: string;
@Column({
allowNull: false,
type: DataTypes.STRING(128),
})
public name: string;
@Association('belongsToMany', {
foreignKey: 'roleId',
target: () => LocalUser,
through: 'LocalUserRoles',
otherKey: 'localUserId',
})
public localUsers?: LocalUser[];
}
index.ts
import { createConnection } from 'crunch-sequelize';
import { Sequelize } from 'sequelize';
import { LocalUser } from './local-user';
import { Role } from './role';
import { User } from './user';
const sequelize = new Sequelize({
database: 'DB_NAME',
define: {
paranoid: true,
timestamps: true,
},
logging: false,
dialect: 'mysql',
password: 'DB_PASS',
username: 'DB_USER',
});
createConnection({
sequelize,
models: [LocalUser, Role, User],
});