Completed
Push — master ( ce7cb4...236e78 )
by Nicolas
15s queued 13s
created

DownloadPaySlipAction.index   A

Complexity

Conditions 3

Size

Total Lines 34
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 34
rs 9.208
c 0
b 0
f 0
cc 3
1
import {
2
  Controller,
3
  Inject,
4
  BadRequestException,
5
  UseGuards,
6
  Get,
7
  Param,
8
  ForbiddenException,
9
  Res
10
} from '@nestjs/common';
11
import {PassThrough} from 'stream';
12
import {ApiUseTags, ApiBearerAuth, ApiOperation} from '@nestjs/swagger';
13
import {AuthGuard} from '@nestjs/passport';
14
import {User} from 'src/Domain/HumanResource/User/User.entity';
15
import {IdDTO} from 'src/Infrastructure/Common/DTO/IdDTO';
16
import {LoggedUser} from '../../User/Decorator/LoggedUser';
17
import {IQueryBus} from 'src/Application/IQueryBus';
18
import {DownloadFileQuery} from 'src/Application/File/Command/DownloadFileQuery';
19
import {GetPaySlipByIdQuery} from 'src/Application/HumanResource/PaySlip/Query/GetPaySlipByIdQuery';
20
import {PaySlipView} from 'src/Application/HumanResource/PaySlip/View/PaySlipView';
21
import {DownloadedFileView} from 'src/Application/File/View/DownloadedFileView';
22
23
@Controller('pay_slips')
24
@ApiUseTags('Human Resource')
25
@ApiBearerAuth()
26
@UseGuards(AuthGuard('bearer'))
27
export class DownloadPaySlipAction {
28
  constructor(
29
    @Inject('IQueryBus')
30
    private readonly queryBus: IQueryBus
31
  ) {}
32
33
  @Get(':id/download')
34
  @ApiOperation({title: 'Download payslip'})
35
  public async index(
36
    @Param() dto: IdDTO,
37
    @LoggedUser() loggedUser: User,
38
    @Res() res
39
  ) {
40
    try {
41
      const {user, file}: PaySlipView = await this.queryBus.execute(
42
        new GetPaySlipByIdQuery(dto.id)
43
      );
44
45
      if (user.id !== loggedUser.getId()) {
46
        throw new ForbiddenException();
47
      }
48
49
      const {
50
        buffer,
51
        originalName,
52
        mimeType
53
      }: DownloadedFileView = await this.queryBus.execute(
54
        new DownloadFileQuery(file.id)
55
      );
56
57
      res.set('Content-disposition', `attachment; filename=${originalName}`);
58
      res.set('Content-Type', mimeType);
59
      res.set('Content-Length', buffer.length);
60
61
      const stream = new PassThrough();
62
      stream.end(buffer);
63
      stream.pipe(res);
64
    } catch (e) {
65
      throw new BadRequestException(e.message);
66
    }
67
  }
68
}
69