Skip to content

Commit

Permalink
[EF-137] add staff - add env in pipeline, add transaction when send e…
Browse files Browse the repository at this point in the history
…mail (#37)
  • Loading branch information
MinhhTien authored Feb 10, 2024
1 parent 8baad3b commit f15c160
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 45 deletions.
10 changes: 9 additions & 1 deletion .github/workflows/develop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,19 @@ jobs:
echo NODE_ENV=${{ vars.NODE_ENV }} >> .env
echo PORT=${{ vars.PORT }} >> .env
echo MONGODB_CONNECTION_STRING=${{ secrets.MONGODB_CONNECTION_STRING }} >> .env
echo CORS_VALID_ORIGINS=${{ vars.CORS_VALID_ORIGINS }} >> .env
echo JWT_ACCESS_SECRET=${{ vars.JWT_ACCESS_SECRET }} >> .env
echo JWT_ACCESS_EXPIRATION=${{ vars.JWT_ACCESS_EXPIRATION }} >> .env
echo JWT_REFRESH_SECRET=${{ vars.JWT_REFRESH_SECRET }} >> .env
echo JWT_REFRESH_EXPIRATION=${{ vars.JWT_REFRESH_EXPIRATION }} >> .env
echo CORS_VALID_ORIGINS=${{ vars.CORS_VALID_ORIGINS }} >> .env
echo SMTP_USERNAME=${{ secrets.SMTP_USERNAME }} >> .env
echo SMTP_PASSWORD=${{ secrets.SMTP_PASSWORD }} >> .env
echo SMTP_HOST=${{ vars.SMTP_HOST }} >> .env
echo SMTP_PORT=${{ vars.SMTP_PORT }} >> .env
echo SMTP_FROM_EMAIL=${{ vars.SMTP_FROM_EMAIL }} >> .env
echo SMTP_FROM_NAME=${{ vars.SMTP_FROM_NAME }} >> .env
- name: Deploy
run: pm2 restart efurniture-api

Expand Down
98 changes: 54 additions & 44 deletions src/staff/services/staff.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,67 +8,77 @@ import { MailerService } from '@nestjs-modules/mailer'
import { MongoServerError } from 'mongodb'
import { Staff } from '@staff/schemas/staff.schema'
import * as _ from 'lodash'
import { InjectConnection } from '@nestjs/mongoose'
import { Connection } from 'mongoose'

@Injectable()
export class StaffService {
constructor(
@InjectConnection() readonly connection: Connection,
private readonly staffRepository: StaffRepository,
private readonly providerRepository: ProviderRepository,
private readonly authService: AuthService,
private readonly mailerService: MailerService
) {}

public async createStaff(createStaffDto: CreateStaffDto) {
const provider = await this.providerRepository.findOne({
conditions: {}
})
createStaffDto.providerId = provider._id
const session = await this.connection.startSession()
session.startTransaction()
try {
const provider = await this.providerRepository.findOne({
conditions: {}
})
createStaffDto.providerId = provider._id

// Generate random password
const password = Math.random().toString(36).slice(-8)
createStaffDto.password = await this.authService.hashPassword(password)
// Generate random password
const password = Math.random().toString(36).slice(-8)
createStaffDto.password = await this.authService.hashPassword(password)

let staff: Staff
try {
staff = await this.staffRepository.create(createStaffDto)
} catch (err) {
if (err instanceof MongoServerError) {
const { code, keyPattern, keyValue } = err
if (code === 11000) {
if (_.get(keyPattern, 'staffCode') === 1)
throw new BadRequestException(
`Mã nhân viên: ${_.get(keyValue, 'staffCode')} đã tổn tại. Vui lòng nhập mã nhân viên khác.`
)
if (_.get(keyPattern, 'email') === 1)
throw new BadRequestException(
`Email: ${_.get(keyValue, 'email')} đã tổn tại. Vui lòng nhập email khác.`
)
let staff: Staff
try {
staff = await this.staffRepository.create(createStaffDto, { session })
} catch (err) {
if (err instanceof MongoServerError) {
const { code, keyPattern, keyValue } = err
if (code === 11000) {
if (_.get(keyPattern, 'staffCode') === 1)
throw new BadRequestException(
`Mã nhân viên: ${_.get(keyValue, 'staffCode')} đã tổn tại. Vui lòng nhập mã nhân viên khác.`
)
if (_.get(keyPattern, 'email') === 1)
throw new BadRequestException(`Email: ${_.get(keyValue, 'email')} đã tổn tại. Vui lòng nhập email khác.`)
}
}
console.error(err)
throw err
}
console.error(err)
throw err
}
// Send email
try {
await this.mailerService.sendMail({
to: createStaffDto.email,
subject: '[eFurniture] Thông tin đăng nhập hệ thống',
template: 'invite-staff',
context: {
name: `${createStaffDto.firstName} ${createStaffDto.lastName}`,
email: createStaffDto.email,
password
// Send email
try {
await this.mailerService.sendMail({
to: createStaffDto.email,
subject: '[eFurniture] Thông tin đăng nhập hệ thống',
template: 'invite-staff',
context: {
name: `${createStaffDto.firstName} ${createStaffDto.lastName}`,
email: createStaffDto.email,
password
}
})
} catch (error) {
console.error(`send mail error=${error}, stack=${JSON.stringify(error['stack'])}`)
if (error['responseCode'] === 501) {
console.error('501 can not send mail')
throw new BadRequestException('Dịch vụ email đang gặp sự cố. Vui lòng thử lại sau!')
} else {
throw error
}
})
} catch (error) {
console.error(`send mail error=${error}, stack=${JSON.stringify(error['stack'])}`)
if (error['responseCode'] === 501) {
console.error('501 can not send mail')
throw new BadRequestException('Dịch vụ email đang gặp sự cố. Vui lòng thử lại sau!')
} else {
throw error
}

await session.commitTransaction()
return new IDResponse(staff._id)
} catch (error) {
await session.abortTransaction()
throw error
}
return new IDResponse(staff._id)
}
}

0 comments on commit f15c160

Please sign in to comment.