forked from Sairyss/domain-driven-hexagon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate-user.http.controller.ts
48 lines (44 loc) · 1.63 KB
/
create-user.http.controller.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { Body, Controller, HttpStatus, Post } from '@nestjs/common';
import { IdResponse } from '@libs/ddd/interface-adapters/dtos/id.response.dto';
import { routesV1 } from '@config/app.routes';
import { ApiOperation, ApiResponse } from '@nestjs/swagger';
import { CommandBus } from '@nestjs/cqrs';
import { Result } from '@src/libs/ddd/domain/utils/result.util';
import { ID } from '@src/libs/ddd/domain/value-objects/id.value-object';
import { ConflictException } from '@src/libs/exceptions';
import { CreateUserCommand } from './create-user.command';
import { CreateUserHttpRequest } from './create-user.request.dto';
import { UserAlreadyExistsError } from '../../errors/user.errors';
@Controller(routesV1.version)
export class CreateUserHttpController {
constructor(private readonly commandBus: CommandBus) {}
@Post(routesV1.user.root)
@ApiOperation({ summary: 'Create a user' })
@ApiResponse({
status: HttpStatus.OK,
type: IdResponse,
})
@ApiResponse({
status: HttpStatus.CONFLICT,
description: UserAlreadyExistsError.message,
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
})
async create(@Body() body: CreateUserHttpRequest): Promise<IdResponse> {
const command = new CreateUserCommand(body);
const result: Result<
ID,
UserAlreadyExistsError
> = await this.commandBus.execute(command);
return result.unwrap(
id => new IdResponse(id.value), // if ok return an id
error => {
// if error decide what to do with it
if (error instanceof UserAlreadyExistsError)
throw new ConflictException(error.message);
throw error;
},
);
}
}