Search This Blog

2023/04/28

How to use Sequelize with express in typescript project

 create your project using following generator


ts-express --view=ejs sequelize-typescript

do
npm i

create User Model as
import { DataTypes, Model, Optional } from 'sequelize'
import sequelizeConnection from '../utils/database'

interface UserAttributes {
id: number;
firstName: string;
lastName: string;
email: string;
password: string;
createdAt?: Date;
updatedAt?: Date;
deletedAt?: Date;
}

// we're telling the Model that 'id' is optional
// when creating an instance of the model (such as using Model.create()).
export interface UserInput extends Optional<UserAttributes, 'id'> { }


export class User extends Model<UserAttributes, UserInput> implements UserAttributes {
public id!: number
public firstName!: string
public lastName!: string
public email!: string
public password!: string

// timestamps!
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
public readonly deletedAt!: Date;
}

User.init({
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
},
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: false
}
}, {
timestamps: true,
sequelize: sequelizeConnection,
paranoid: true
})



create model/index.js

import { User } from './user'

export {
User
}

Now in our user route add

import express from 'express';
import { getLogger } from '@/utils/loggers';
const router = express.Router();
const logger = getLogger('USER_ROUTE');
import { User } from '../models';
import bcrypt from "bcrypt";


router.post('/signin', async function (req, res, next) {
if (!req.body.email || !req.body.password) {
res.status(400).send({
msg: 'Please enter email and password.'
});
} else {
try {
var foundUser = await User.findOne({
where: { email: req.body.email }
})
if (foundUser) {
res.status(400).send({
msg: 'Email ' + foundUser.email + ' already taken ,please login'
});
} else {
let hashedPassword = await bcrypt.hash(req.body.password, bcrypt.genSaltSync(8))
let user = await User.create({
email: req.body.email,
password: hashedPassword,
firstName: req.body.firstName,
lastName: req.body.lastName
})

var returnValue = JSON.parse(JSON.stringify(user))
delete returnValue.password;

res.status(201).send({
msg: 'User created successfully',
data: returnValue
});
}
} catch (exp: any) {
res.status(201).send({
msg: 'Error Occured while creating User:' + exp.toString()
});
}

}


});

export default router;


Util/database


import { Dialect, Sequelize } from 'sequelize'

const dbName = process.env.MYSQL_DATABASE as string
const dbUser = process.env.MYSQL_USER_NAME as string
const dbHost = process.env.MYSQL_HOST
const dbDriver = process.env.NYSQL_DRIVER as Dialect
const dbPassword = process.env.MYSQL_PASSWORD

const sequelizeConnection = new Sequelize(dbName, dbUser, dbPassword, {
host: dbHost,
dialect: dbDriver
})

export default sequelizeConnection

Util/init

import { User } from '../models'
const isDev = process.env.NODE_ENV === 'development'

const dbInit = () => {
User.sync({ alter: isDev })
}
export default dbInit

.env file

MYSQL_USER_NAME = root
MYSQL_PASSWORD = "sangram#81"
MYSQL_PORT = 3306
MYSQL_DATABASE = MatrimonyDb
MYSQL_HOST = localhost
NYSQL_DRIVER = mysql
SECRET_KEY = abcd1234
NODE_ENV = 'development'

bin/www

add following in top in file

import dbInit from '../src/utils/init'
dbInit()


in etc/build.sh

rimraf dist

export NODE_ENV=developement

tsc -p ./tsconfig.build.json --pretty

cp -R src/public dist/src/public

cp package.json dist/

cp .env dist/

Now run application as

npm start

Hit Endpoint using Postman

Endpoint:localhost:3000/users/signin
Body:
{
"firstName": "sanjay",
"lastName": "desai",
"email": "sanjay@gamil.com",
"password": "Wwara#81"
}

Output:
{
"msg": "User created successfully",
"data": {
"id": 2,
"email": "sanjay@gamil.com",
"firstName": "sanjay",
"lastName": "desai",
"updatedAt": "2023-04-28T18:08:32.773Z",
"createdAt": "2023-04-28T18:08:32.773Z"
}
}



Code of this application is at https://github.com/gitsangramdesai/typescript-sequelize

No comments:

Post a Comment