Entity
Services
Controller
Routes
Index.js
const { EntitySchema } = require('typeorm');
module.exports = new EntitySchema({
name: 'User',
tableName: 'users',
columns: {
id: {
type: 'int',
primary: true,
generated: true,
},
username: {
type: 'varchar',
unique: true,
nullable: false,
},
email: {
type: 'varchar',
unique: true,
nullable: false,
},
password: {
type: 'varchar',
nullable: false,
},
phone: {
type: 'varchar',
unique: true,
nullable: true,
},
firstName: {
type: 'varchar',
nullable: true,
},
lastName: {
type: 'varchar',
nullable: true,
},
isActivated: {
type: 'boolean',
default: false,
},
googleId: {
type: 'varchar',
unique: true,
nullable: true,
},
facebookId: {
type: 'varchar',
unique: true,
nullable: true,
},
otp: {
type: 'varchar',
nullable: true,
},
otpExpires: {
type: 'timestamp',
nullable: true,
},
activationToken: {
type: 'varchar',
nullable: true,
},
resetToken: {
type: 'varchar',
nullable: true,
},
createdAt: {
name: 'created_at',
type: 'timestamp',
createDate: true,
},
updatedAt: {
name: 'updated_at',
type: 'timestamp',
updateDate: true,
},
},
relations: {
role: {
type: 'many-to-one',
target: 'Role',
joinColumn: { name: 'role_id' },
nullable: true,
onDelete: 'SET NULL',
},
usergroup: {
type: 'many-to-one',
target: 'UserGroup',
joinColumn: { name: 'usergroup_id' },
nullable: true,
onDelete: 'SET NULL',
},
},
});
Explanation:
Columns:
id
: This is the primary key, auto-incremented.username
: A unique and non-nullable string.email
: A unique and non-nullable string.password
: A non-nullable string for storing the hashed password.createdAt
: Automatically set to the current timestamp when a new record is created.updatedAt
: Automatically updated to the current timestamp whenever the record is updated.
Relations:
role
: A many-to-one relationship with theRole
entity. The foreign key isrole_id
, and if the referenced role is deleted, this relationship will be set toNULL
.usergroup
: A many-to-one relationship with theUserGroup
entity. The foreign key isusergroup_id
, and if the referenced user group is deleted, this relationship will be set toNULL
.
Note: Assigning role_id
and usergroup_id
directly in the users
table establishes a Many-to-One relationship:
- User to Role: Many users can have the same role.
- User to UserGroup: Many users can belong to the same user group.