Task: Fixed controller and application for routes and allow middleware for json and form urclosed
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Sambo Chea 2021-09-14 09:44:25 +07:00
parent 67c94211e7
commit 20fa35a575
5 changed files with 52 additions and 2 deletions

View File

@ -12,6 +12,8 @@ class Application {
constructor() {
this._instance = express()
this._instance.use(express.json())
this._instance.use(express.urlencoded({ extended: false }))
this.registerRoutes()
}

View File

@ -10,4 +10,9 @@ export default class IndexController {
public index(req: Request, res: Response) {
res.send(`Hello Index`)
}
@Get("/:name")
public hello(req: Request, res: Response) {
res.send(`Hello ${req.params.name}`)
}
}

View File

@ -1,3 +1,4 @@
import IndexController from "./index.controller"
import PersonController from "./person.controller"
export const controllers = [IndexController]
export const controllers = [IndexController, PersonController]

View File

@ -0,0 +1,36 @@
import { Request, Response } from "express"
import Controller from "../decorators/controller.decorator"
import { Post, Get } from "../decorators/handlers.decorator"
const persons: Array<any> = [
{
id: 1,
name: "Sambo",
},
]
@Controller("/person")
export default class PersonController {
@Get()
public getPersons(req: Request, res: Response) {
res.json(persons)
}
@Post()
public createPerson(req: Request, res: Response) {
const person = req.body
if (person == null) {
return res.status(400).json({
status: 400,
message: "Person is required",
})
}
persons.push(person)
res.json({
message: "Person created successfully",
body: person,
})
}
}

View File

@ -3,6 +3,9 @@ import { MetadataKeys } from "../constants/metadata.keys"
export enum Method {
GET = "get",
POST = "post",
PUT = "put",
DELETE = "delete",
PATCH = "patch",
}
export interface RouteHandler {
@ -12,7 +15,7 @@ export interface RouteHandler {
}
const methodDecoratorFactory = (method: Method) => {
return (path: string): MethodDecorator => {
return (path: string = ""): MethodDecorator => {
return (target: any, propertyKey: string | symbol): void => {
const controllerClass = target.constructor
const routers: RouteHandler[] = Reflect.hasMetadata(
@ -39,3 +42,6 @@ const methodDecoratorFactory = (method: Method) => {
export const Get = methodDecoratorFactory(Method.GET)
export const Post = methodDecoratorFactory(Method.POST)
export const Put = methodDecoratorFactory(Method.PUT)
export const Delete = methodDecoratorFactory(Method.DELETE)
export const Patch = methodDecoratorFactory(Method.PATCH)