Compare commits

..

11 Commits

Author SHA1 Message Date
d85c126c27 implementation details
ref #6
2020-11-27 21:24:55 +01:00
e29c0cb7a1 Merge branch 'main' into feature/authed-routes
# Conflicts:
#	src/app.ts
#	src/controllers/TrackController.ts
2020-11-27 21:19:58 +01:00
aef2f9562a Put now isn't allowed to change ids
ref #4
2020-11-27 19:59:07 +01:00
b267d87ba6 Added endpoint descriptions
ref #4
2020-11-27 19:58:00 +01:00
d2278fd248 Added jsdoc style class documentation
ref #3
2020-11-27 19:57:10 +01:00
24d890f638 Moved cors to the routing-controller function
ref #4
2020-11-27 19:32:54 +01:00
4e5e08483d Added "/api" route prefix
ref #4 #5
2020-11-27 19:32:29 +01:00
b382f0689b Added errors and fixed the create model
ref #4
2020-11-27 18:48:22 +01:00
56ee91e762 Merge branch 'main' of git.odit.services:lfk/backend into main 2020-11-27 18:46:08 +01:00
f2efc4e37b Set env to node_env for the server 2020-11-27 18:46:04 +01:00
27462b0615 Fixed wrong type 2020-11-27 18:40:11 +01:00
6 changed files with 109 additions and 75 deletions

View File

@ -4,4 +4,5 @@ DB_HOST=bla
DB_PORT=bla DB_PORT=bla
DB_USER=bla DB_USER=bla
DB_PASSWORD=bla DB_PASSWORD=bla
DB_NAME=bla DB_NAME=bla
NODE_ENV=production

View File

@ -5,22 +5,25 @@ import consola from "consola";
import loaders from "./loaders/index"; import loaders from "./loaders/index";
import authchecker from "./authchecker"; import authchecker from "./authchecker";
import { ErrorHandler } from './middlewares/ErrorHandler'; import { ErrorHandler } from './middlewares/ErrorHandler';
//
dotenvSafe.config(); dotenvSafe.config();
const PORT = process.env.APP_PORT || 4010; const PORT = process.env.APP_PORT || 4010;
const app = createExpressServer({ const app = createExpressServer({
authorizationChecker: authchecker, authorizationChecker: authchecker,
middlewares: [ErrorHandler], middlewares: [ErrorHandler],
development: false, development: process.env.NODE_ENV === "production",
controllers: [`${__dirname}/controllers/*.ts`], cors: true,
routePrefix: "/api",
controllers: [__dirname + "/controllers/*.ts"],
}); });
(async () => { async function main() {
await loaders(app); await loaders(app);
app.listen(PORT, () => { app.listen(PORT, () => {
consola.success( consola.success(
`⚡️[server]: Server is running at http://localhost:${PORT}` `⚡️[server]: Server is running at http://localhost:${PORT}`
); );
}); });
})(); }
main();

View File

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

View File

@ -3,12 +3,6 @@ import bodyParser from 'body-parser';
import cors from 'cors'; import cors from 'cors';
export default async (app: Application) => { export default async (app: Application) => {
app.get('/status', (req, res) => res.status(200).end());
app.enable('trust proxy'); app.enable('trust proxy');
app.use(cors());
// app.use(bodyParser.urlencoded({ extended: false }));
// more middlewares
return app; return app;
}; };

View File

@ -11,7 +11,9 @@ export default async (app: Application) => {
}); });
const spec = routingControllersToSpec( const spec = routingControllersToSpec(
storage, storage,
{}, {
routePrefix: "/api"
},
{ {
components: { components: {
schemas, schemas,
@ -27,11 +29,11 @@ export default async (app: Application) => {
explorer: true, explorer: true,
}; };
app.use( app.use(
"/docs", "/api/docs",
swaggerUiExpress.serve, swaggerUiExpress.serve,
swaggerUiExpress.setup(spec, options) swaggerUiExpress.setup(spec, options)
); );
app.get(["/openapi.json", "/swagger.json"], (req, res) => { app.get(["/api/openapi.json", "/api/swagger.json"], (req, res) => {
res.json(spec); res.json(spec);
}); });
return app; return app;

View File

@ -7,6 +7,12 @@ import {
IsString, IsString,
} from "class-validator"; } from "class-validator";
/**
* @classdesc Defines a track of given length.
* @property {number} id - Autogenerated unique id
* @property {string} name - The track's name
* @property {number} lenth - The track's length in meters
*/
@Entity() @Entity()
export class Track { export class Track {
@PrimaryGeneratedColumn() @PrimaryGeneratedColumn()
@ -22,5 +28,5 @@ export class Track {
@Column() @Column()
@IsInt() @IsInt()
@IsPositive() @IsPositive()
length: string; length: number;
} }