-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathUserController.ts
More file actions
82 lines (65 loc) · 2.29 KB
/
UserController.ts
File metadata and controls
82 lines (65 loc) · 2.29 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { buildFastifyRoute } from '@lokalise/fastify-api-contracts'
import { AbstractController, type BuildRoutesReturnType } from 'opinionated-machine'
import {
deleteUserContract,
getUserContract,
patchUpdateUserContract,
postCreateUserContract,
} from '../schemas/userApiContracts.ts'
import type { UserService } from '../services/UserService.ts'
import type { UsersInjectableDependencies } from '../UserModule.ts'
type UserControllerContractsType = typeof UserController.contracts
export class UserController extends AbstractController<UserControllerContractsType> {
public static contracts = {
createUser: postCreateUserContract,
getUser: getUserContract,
deleteUser: deleteUserContract,
updateUser: patchUpdateUserContract,
} as const
private readonly userService: UserService
constructor(dependencies: UsersInjectableDependencies) {
super()
this.userService = dependencies.userService
}
private createUser = buildFastifyRoute(postCreateUserContract, async (req, reply) => {
const { name, email, age } = req.body
const { userService } = req.diScope.cradle
const createdUser = await userService.createUser({
name,
email,
age,
})
return reply.status(201).send({
data: createdUser,
})
})
private getUser = buildFastifyRoute(getUserContract, async (req, reply) => {
const { userId } = req.params
const { reqContext } = req
const user = await this.userService.getUser(reqContext, userId)
return reply.send({
data: user,
})
})
private deleteUser = buildFastifyRoute(deleteUserContract, async (req, reply) => {
const { userId } = req.params
const { reqContext } = req
await this.userService.deleteUser(reqContext, userId)
return reply.status(204).send()
})
private updateUser = buildFastifyRoute(patchUpdateUserContract, async (req, reply) => {
const { userId } = req.params
const updatedUser = req.body
const { reqContext } = req
await this.userService.updateUser(reqContext, userId, updatedUser)
return reply.status(204).send()
})
buildRoutes(): BuildRoutesReturnType<UserControllerContractsType> {
return {
createUser: this.createUser,
getUser: this.getUser,
deleteUser: this.deleteUser,
updateUser: this.updateUser,
}
}
}