92 lines
2.7 KiB
TypeScript
92 lines
2.7 KiB
TypeScript
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 { Track } from '../models/Track';
|
|
import { IsInt, IsNotEmpty, IsPositive, IsString } from 'class-validator';
|
|
import {TrackIdChangeNotAllowedError, TrackNotFoundError} from "../errors/TrackErrors";
|
|
|
|
class CreateTrack {
|
|
@IsString()
|
|
@IsNotEmpty()
|
|
name: string;
|
|
|
|
@IsInt()
|
|
@IsPositive()
|
|
length: number;
|
|
}
|
|
|
|
@JsonController('/tracks')
|
|
@Authorized("TRACKS:read")
|
|
export class TrackController {
|
|
private trackRepository: Repository<Track>;
|
|
|
|
/**
|
|
* Gets the repository of this controller's model/entity.
|
|
*/
|
|
constructor() {
|
|
this.trackRepository = getConnectionManager().get().getRepository(Track);
|
|
}
|
|
|
|
@Get()
|
|
@ResponseSchema(Track, { isArray: true })
|
|
@OpenAPI({ description: "Lists all tracks." })
|
|
getAll() {
|
|
return this.trackRepository.find();
|
|
}
|
|
|
|
@Get('/:id')
|
|
@ResponseSchema(Track)
|
|
@ResponseSchema(TrackNotFoundError, {statusCode: 404})
|
|
@OnUndefined(TrackNotFoundError)
|
|
@OpenAPI({ description: "Returns a track of a specified id (if it exists)" })
|
|
getOne(@Param('id') id: number) {
|
|
return this.trackRepository.findOne({ id: id });
|
|
}
|
|
|
|
@Post()
|
|
@ResponseSchema(Track)
|
|
@OpenAPI({ description: "Create a new track object (id will be generated automagicly)." })
|
|
post(
|
|
@Body({ validate: true })
|
|
track: CreateTrack
|
|
) {
|
|
return this.trackRepository.save(track);
|
|
}
|
|
|
|
@Put('/:id')
|
|
@ResponseSchema(Track)
|
|
@ResponseSchema(TrackNotFoundError, {statusCode: 404})
|
|
@ResponseSchema(TrackIdChangeNotAllowedError, {statusCode: 406})
|
|
@OpenAPI({description: "Update a track object (id can't be changed)."})
|
|
async put(@Param('id') id: number, @EntityFromBody() track: Track) {
|
|
let oldTrack = await this.trackRepository.findOne({ id: id });
|
|
|
|
if (!oldTrack) {
|
|
throw new TrackNotFoundError();
|
|
}
|
|
|
|
if(oldTrack.id != track.id){
|
|
throw new TrackIdChangeNotAllowedError();
|
|
}
|
|
|
|
await this.trackRepository.update(oldTrack, track);
|
|
return track;
|
|
}
|
|
|
|
@Delete('/:id')
|
|
@ResponseSchema(Track)
|
|
@ResponseSchema(TrackNotFoundError, {statusCode: 404})
|
|
@OpenAPI({description: "Delete a specified track (if it exists)."})
|
|
async remove(@Param('id') id: number) {
|
|
let track = await this.trackRepository.findOne({ id: id });
|
|
|
|
if (!track) {
|
|
throw new TrackNotFoundError();
|
|
}
|
|
|
|
await this.trackRepository.delete(track);
|
|
return track;
|
|
}
|
|
}
|