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

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

View File

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

View File

@ -1,64 +1,92 @@
import {
JsonController,
Param,
Body,
Get,
Post,
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";
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';
class CreateTrack {
@IsString()
@IsNotEmpty()
name: string;
@IsString()
@IsNotEmpty()
name: string;
@IsInt()
@IsPositive()
length: string;
@IsInt()
@IsPositive()
length: number;
}
@JsonController("/track")
// @Authorized("TRACKS:read")
export class TrackNotFoundError extends NotFoundError {
constructor() {
super('Track not found!');
}
}
@JsonController('/tracks')
@Authorized("TRACKS:read")
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()
@ResponseSchema(Track, { isArray: true })
getAll() {
return this.trackRepository.find();
}
@Get()
@ResponseSchema(Track, { isArray: true })
@OpenAPI({ description: "Lists all tracks." })
getAll() {
return this.trackRepository.find();
}
@Get("/:id")
@ResponseSchema(Track)
getOne(@Param("id") id: number) {
return this.trackRepository.findOne({ id: id });
}
@Get('/:id')
@ResponseSchema(Track)
@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 });
}
@Authorized()
@Post()
post(@Body({ validate: true }) track: CreateTrack) {
return this.trackRepository.save(track);
}
@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);
}
@Authorized("TRACKS:write")
@Put("/:id")
put(@Param("id") id: number, @EntityFromBody() track: Track) {
return this.trackRepository.update({ id: id }, track);
}
@Put('/:id')
@ResponseSchema(Track)
@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 });
@Delete("/:id")
remove(@Param("id") id: number) {
return this.trackRepository.delete({ id: id });
}
if (!oldTrack) {
throw new TrackNotFoundError();
}
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';
export default async (app: Application) => {
app.get('/status', (req, res) => res.status(200).end());
app.enable('trust proxy');
app.use(cors());
// app.use(bodyParser.urlencoded({ extended: false }));
// more middlewares
return app;
};

View File

@ -11,7 +11,9 @@ export default async (app: Application) => {
});
const spec = routingControllersToSpec(
storage,
{},
{
routePrefix: "/api"
},
{
components: {
schemas,
@ -27,11 +29,11 @@ export default async (app: Application) => {
explorer: true,
};
app.use(
"/docs",
"/api/docs",
swaggerUiExpress.serve,
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);
});
return app;

View File

@ -7,6 +7,12 @@ import {
IsString,
} 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()
export class Track {
@PrimaryGeneratedColumn()
@ -22,5 +28,5 @@ export class Track {
@Column()
@IsInt()
@IsPositive()
length: string;
length: number;
}