-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #6 from yldrmzffr/feature/new-routing-system
feat(major restructuring): implement controller and request handler c…
- Loading branch information
Showing
7 changed files
with
217 additions
and
162 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import {RouteManager} from '../routing/route-manager'; | ||
import * as pathLib from 'path'; | ||
import {Route} from '../interfaces'; | ||
|
||
export type ControllerDecorator = (path?: string) => ClassDecorator; | ||
|
||
export class ControllerFactory { | ||
constructor(private routeManager: RouteManager) {} | ||
public Controller: ControllerDecorator = (path = '') => { | ||
return (target: any) => { | ||
Reflect.defineMetadata('path', path, target); | ||
|
||
const properties = Object.getOwnPropertyNames(target.prototype); | ||
|
||
const routers: (Route | undefined)[] = properties.map(property => { | ||
const routeHandler = target.prototype[property]; | ||
const method = Reflect.getMetadata('method', routeHandler); | ||
const url = Reflect.getMetadata('url', routeHandler); | ||
|
||
if (!method || !url) return; | ||
|
||
const fullPath = pathLib.join(path, url); | ||
|
||
return { | ||
method, | ||
url: fullPath, | ||
handler: routeHandler.bind(target.prototype), | ||
} as Route; | ||
}); | ||
|
||
this.routeManager.addRoutes(routers.filter(Boolean) as Route[]); | ||
|
||
return target; | ||
}; | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import {Request} from '../interfaces'; | ||
import {Response} from '../types'; | ||
import {RouteManager} from '../routing/route-manager'; | ||
import {NotFoundException} from '../exceptions/not-found.exception'; | ||
import {getRequestBody, parseQueryParams} from '../utils'; | ||
import {MuzuException} from '../exceptions/muzu.exception'; | ||
import {BadRequestException} from '../exceptions/bad-request.exception'; | ||
export class RequestHandler { | ||
private routeManager: RouteManager; | ||
|
||
constructor(routeManager: RouteManager) { | ||
this.routeManager = routeManager; | ||
} | ||
|
||
private async sendResponse( | ||
res: Response, | ||
statusCode: number, | ||
body: Object | ||
): Promise<void> { | ||
res.writeHead(statusCode, {'Content-Type': 'application/json'}); | ||
res.end(JSON.stringify(body)); | ||
console.log('📤 Response', {statusCode, body}); | ||
} | ||
|
||
public async handleRequest(req: Request, res: Response): Promise<void> { | ||
try { | ||
const {url, method} = req; | ||
const path = url!.split('?')[0]; | ||
|
||
req.params = parseQueryParams(url!); | ||
|
||
const route = await this.routeManager.find(path, method); | ||
|
||
if (!route) { | ||
throw new NotFoundException(`Route ${method} ${path} not found`, { | ||
method, | ||
path, | ||
}); | ||
} | ||
|
||
try { | ||
const body = await getRequestBody(req); | ||
req.body = body; | ||
} catch (error) { | ||
console.log('🚨 Error parsing body', error); | ||
const err = error as MuzuException; | ||
throw new BadRequestException('Error parsing body', err.details); | ||
} | ||
|
||
let result: Object = route.handler(req, res); | ||
|
||
if (result instanceof Promise) { | ||
result = await result; | ||
} | ||
|
||
const statusCode = res.statusCode || 200; | ||
return this.sendResponse(res, statusCode, result); | ||
} catch (error) { | ||
console.log('🚨 Error handling request', error); | ||
const knownError = error as MuzuException; | ||
|
||
if (knownError.kind === 'MuzuException') { | ||
return this.sendResponse(res, knownError.status, knownError); | ||
} | ||
|
||
return this.sendResponse(res, 500, { | ||
message: '500 Internal Server Error', | ||
stack: knownError.stack, | ||
}); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import {RequestMethod} from '../types'; | ||
|
||
type HttpMethodDecorator = ( | ||
target: any, | ||
propertyKey: string, | ||
descriptor: PropertyDescriptor | ||
) => PropertyDescriptor; | ||
|
||
export type MethodDecorator = (url?: string) => HttpMethodDecorator; | ||
|
||
export class MethodFactory { | ||
public HttpMethod(method: RequestMethod, url: string): HttpMethodDecorator { | ||
return ( | ||
target: any, | ||
propertyKey: string, | ||
descriptor: PropertyDescriptor | ||
) => { | ||
Reflect.defineMetadata( | ||
'url', | ||
`${url}`.toLowerCase(), | ||
target[propertyKey] | ||
); | ||
Reflect.defineMetadata('method', method, target[propertyKey]); | ||
return descriptor; | ||
}; | ||
} | ||
Get = (url = '/'): HttpMethodDecorator => { | ||
return this.HttpMethod(RequestMethod.GET, url); | ||
}; | ||
|
||
Post = (url = '/'): HttpMethodDecorator => { | ||
return this.HttpMethod(RequestMethod.POST, url); | ||
}; | ||
|
||
Delete = (url = '/'): HttpMethodDecorator => { | ||
return this.HttpMethod(RequestMethod.DELETE, url); | ||
}; | ||
|
||
Put = (url = '/'): HttpMethodDecorator => { | ||
return this.HttpMethod(RequestMethod.PUT, url); | ||
}; | ||
|
||
Patch = (url = '/'): HttpMethodDecorator => { | ||
return this.HttpMethod(RequestMethod.PATCH, url); | ||
}; | ||
} |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.