88 lines
2.6 KiB
TypeScript
88 lines
2.6 KiB
TypeScript
import { Body, Delete, Get, JsonController, OnUndefined, Param, Post, Put } from 'routing-controllers';
|
|
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
|
|
import { getConnectionManager, Repository } from 'typeorm';
|
|
import { EntityFromBody, EntityFromParam } from 'typeorm-routing-controllers-extensions';
|
|
import { UserIdsNotMatchingError, UserNotFoundError } from '../errors/UserErrors';
|
|
import { UserGroupNotFoundError } from '../errors/UserGroupErrors';
|
|
import { CreateUser } from '../models/actions/CreateUser';
|
|
import { User } from '../models/entities/User';
|
|
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
|
|
|
|
|
|
@JsonController('/users')
|
|
export class UserController {
|
|
private userRepository: Repository<User>;
|
|
|
|
/**
|
|
* Gets the repository of this controller's model/entity.
|
|
*/
|
|
constructor() {
|
|
this.userRepository = getConnectionManager().get().getRepository(User);
|
|
}
|
|
|
|
@Get()
|
|
@ResponseSchema(User, { isArray: true })
|
|
@OpenAPI({ description: 'Lists all users.' })
|
|
getAll() {
|
|
return this.userRepository.find();
|
|
}
|
|
|
|
@Get('/:id')
|
|
@ResponseSchema(User)
|
|
@ResponseSchema(UserNotFoundError, { statusCode: 404 })
|
|
@OnUndefined(UserNotFoundError)
|
|
@OpenAPI({ description: 'Returns a user of a specified id (if it exists)' })
|
|
getOne(@Param('id') id: number) {
|
|
return this.userRepository.findOne({ id: id });
|
|
}
|
|
|
|
@Post()
|
|
@ResponseSchema(User)
|
|
@ResponseSchema(UserGroupNotFoundError)
|
|
@OpenAPI({ description: 'Create a new user object (id will be generated automagicly).' })
|
|
async post(@Body({ validate: true }) createUser: CreateUser) {
|
|
let user;
|
|
try {
|
|
user = await createUser.toUser();
|
|
} catch (error) {
|
|
throw error;
|
|
}
|
|
|
|
return this.userRepository.save(user);
|
|
}
|
|
|
|
@Put('/:id')
|
|
@ResponseSchema(User)
|
|
@ResponseSchema(UserNotFoundError, { statusCode: 404 })
|
|
@ResponseSchema(UserIdsNotMatchingError, { statusCode: 406 })
|
|
@OpenAPI({ description: "Update a user object (id can't be changed)." })
|
|
async put(@Param('id') id: number, @EntityFromBody() user: User) {
|
|
let oldUser = await this.userRepository.findOne({ id: id });
|
|
|
|
if (!oldUser) {
|
|
throw new UserNotFoundError();
|
|
}
|
|
|
|
if (oldUser.id != user.id) {
|
|
throw new UserIdsNotMatchingError();
|
|
}
|
|
|
|
await this.userRepository.update(oldUser, user);
|
|
return user;
|
|
}
|
|
|
|
@Delete('/:id')
|
|
@ResponseSchema(User)
|
|
@ResponseSchema(ResponseEmpty, { statusCode: 204 })
|
|
@OnUndefined(204)
|
|
@OpenAPI({ description: 'Delete a specified runner (if it exists).' })
|
|
async remove(@EntityFromParam('id') user: User) {
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
await this.userRepository.delete(user);
|
|
return user;
|
|
}
|
|
}
|