forked from Sairyss/domain-driven-hexagon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-user.http.controller.ts
50 lines (46 loc) · 1.72 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
49
50
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 { ID } from '@src/libs/ddd/domain/value-objects/id.value-object';
import { ConflictException } from '@src/libs/exceptions';
import { match, Result } from 'oxide.ts/dist';
import { CreateUserCommand } from './create-user.command';
import { UserAlreadyExistsError } from '../../errors/user.errors';
import { CreateUserRequest } from './create-user.request.dto';
@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: CreateUserRequest): Promise<IdResponse> {
const command = new CreateUserCommand(body);
const result: Result<
ID,
UserAlreadyExistsError
> = await this.commandBus.execute(command);
// Deciding what to do with a Result (similar to Rust matching)
// if Ok we return a response with an id
// if Error decide what to do with it depending on its type
return match(result, {
Ok: id => new IdResponse(id.value),
Err: error => {
if (error instanceof UserAlreadyExistsError)
throw new ConflictException(error.message);
throw error;
},
});
}
}