-
Notifications
You must be signed in to change notification settings - Fork 914
/
Copy pathPetController.ts
85 lines (69 loc) · 2.17 KB
/
PetController.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
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
83
84
85
import { IsNotEmpty, IsNumber, IsUUID, ValidateNested } from 'class-validator';
import {
Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post, Put
} from 'routing-controllers';
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
import { PetNotFoundError } from '../errors/PetNotFoundError';
import { Pet } from '../models/Pet';
import { PetService } from '../services/PetService';
import { UserResponse } from './UserController';
class BasePet {
@IsNotEmpty()
public name: string;
@IsNumber()
public age: number;
}
export class PetResponse extends BasePet {
@IsUUID()
public id: string;
@ValidateNested()
public user: UserResponse;
}
class CreatePetBody extends BasePet {
@IsUUID()
public userId: string;
}
@Authorized()
@JsonController('/pets')
@OpenAPI({ security: [{ basicAuth: [] }] })
/**
* Loader is a place where you can configure all your modules during microframework
* bootstrap process. All loaders are executed one by one in a sequential order.
*/
export class PetController {
constructor(
private petService: PetService
) { }
@Get()
@ResponseSchema(PetResponse, { isArray: true })
public find(): Promise<Pet[]> {
return this.petService.find();
}
@Get('/:id')
@OnUndefined(PetNotFoundError)
@ResponseSchema(PetResponse)
public one(@Param('id') id: string): Promise<Pet | undefined> {
return this.petService.findOne(id);
}
@Post()
@ResponseSchema(PetResponse)
public create(@Body({ required: true }) body: CreatePetBody): Promise<Pet> {
const pet = new Pet();
pet.age = body.age;
pet.name = body.name;
pet.userId = body.userId;
return this.petService.create(pet);
}
@Put('/:id')
@ResponseSchema(PetResponse)
public update(@Param('id') id: string, @Body() body: BasePet): Promise<Pet> {
const pet = new Pet();
pet.age = body.age;
pet.name = body.name;
return this.petService.update(id, pet);
}
@Delete('/:id')
public delete(@Param('id') id: string): Promise<void> {
return this.petService.delete(id);
}
}