Created basic runner controller

ref #13
This commit is contained in:
Nicolai Ort 2020-12-02 18:46:40 +01:00
parent 96a99c4e3b
commit 701207e100
1 changed files with 91 additions and 0 deletions

View File

@ -0,0 +1,91 @@
import { JsonController, Param, Body, Get, Post, Put, Delete, NotFoundError, OnUndefined, NotAcceptableError, Authorized } from 'routing-controllers';
import { getConnectionManager, Repository } from 'typeorm';
import { EntityFromBody } from 'typeorm-routing-controllers-extensions';
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
import { Runner } from '../models/Runner';
import { IsInt, IsNotEmpty, IsPositive, IsString } from 'class-validator';
import {RunnerIdsNotMatchingError, RunnerNotFoundError} from "../errors/RunnerErrors";
class CreateRunner {
@IsString()
@IsNotEmpty()
name: string;
@IsInt()
@IsPositive()
length: number;
}
@JsonController('/runners')
@Authorized("RUNNERS:read")
export class RunnerController {
private runnerRepository: Repository<Runner>;
/**
* Gets the repository of this controller's model/entity.
*/
constructor() {
this.runnerRepository = getConnectionManager().get().getRepository(Runner);
}
@Get()
@ResponseSchema(Runner, { isArray: true })
@OpenAPI({ description: "Lists all runners." })
getAll() {
return this.runnerRepository.find();
}
@Get('/:id')
@ResponseSchema(Runner)
@ResponseSchema(RunnerNotFoundError, {statusCode: 404})
@OnUndefined(RunnerNotFoundError)
@OpenAPI({ description: "Returns a runner of a specified id (if it exists)" })
getOne(@Param('id') id: number) {
return this.runnerRepository.findOne({ id: id });
}
@Post()
@ResponseSchema(Runner)
@OpenAPI({ description: "Create a new runner object (id will be generated automagicly)." })
post(
@Body({ validate: true })
runner: CreateRunner
) {
return this.runnerRepository.save(runner);
}
@Put('/:id')
@ResponseSchema(Runner)
@ResponseSchema(RunnerNotFoundError, {statusCode: 404})
@ResponseSchema(RunnerIdsNotMatchingError, {statusCode: 406})
@OpenAPI({description: "Update a runner object (id can't be changed)."})
async put(@Param('id') id: number, @EntityFromBody() runner: Runner) {
let oldRunner = await this.runnerRepository.findOne({ id: id });
if (!oldRunner) {
throw new RunnerNotFoundError();
}
if(oldRunner.id != runner.id){
throw new RunnerIdsNotMatchingError();
}
await this.runnerRepository.update(oldRunner, runner);
return runner;
}
@Delete('/:id')
@ResponseSchema(Runner)
@ResponseSchema(RunnerNotFoundError, {statusCode: 404})
@OpenAPI({description: "Delete a specified runner (if it exists)."})
async remove(@Param('id') id: number) {
let runner = await this.runnerRepository.findOne({ id: id });
if (!runner) {
throw new RunnerNotFoundError();
}
await this.runnerRepository.delete(runner);
return runner;
}
}