Skip to content

Instantly share code, notes, and snippets.

@ryuichi24
Created May 28, 2021 08:04
Show Gist options
  • Save ryuichi24/a645a5973027a63f24a030e5ca50abfb to your computer and use it in GitHub Desktop.
Save ryuichi24/a645a5973027a63f24a030e5ca50abfb to your computer and use it in GitHub Desktop.
base controller for typescript (node js)
import { HttpResponseBuilder } from './HttpResponseBuilder';
import { HttpStatusCode } from './HttpStatusCode';
import { Route } from './RouteBuilder';
abstract class BaseController {
protected _basePath: string;
protected _routes: Route[];
constructor() {
this._basePath = '';
this._routes = [];
this.setupRoutes();
this.setBasePath();
}
public ok(data?: any) {
return new HttpResponseBuilder()
.setStatusCode(HttpStatusCode.OK)
.setBody(data)
.build();
}
public Json(data: any) {
return new HttpResponseBuilder()
.setStatusCode(HttpStatusCode.OK)
.setJsonBody(data)
.build();
}
public created(sourceId: string) {
return new HttpResponseBuilder()
.setStatusCode(HttpStatusCode.CREATED)
.setSourceLocation(sourceId)
.build();
}
public noContent() {
return new HttpResponseBuilder()
.setStatusCode(HttpStatusCode.NO_CONTENT)
.build();
}
public unauthorized(message: Error | string = 'Unauthorized') {
return new HttpResponseBuilder()
.setStatusCode(HttpStatusCode.UNAUTHORIZED)
.setError(message)
.build();
}
public notFound(message: Error | string = 'Not Found') {
return new HttpResponseBuilder()
.setStatusCode(HttpStatusCode.NOT_FOUND)
.setError(message)
.build();
}
public forbidden(message: Error | string = 'Forbidden') {
return new HttpResponseBuilder()
.setStatusCode(HttpStatusCode.FORBIDDEN)
.setError(message)
.build();
}
public internalServerError(error: Error | string = 'Internal Server Error') {
return new HttpResponseBuilder()
.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR)
.setError(error)
.build();
}
protected setBasePath() {
this._basePath = this.constructor.name
.replace('Controller', 's')
.toLowerCase();
}
protected abstract setupRoutes(): void;
get baseRoute() {
return this._basePath;
}
get routes() {
return this._routes;
}
}
export { BaseController };
enum HttpMethod {
GET,
POST,
PUT,
DELETE,
}
export { HttpMethod };
interface HttpRequest {
body: any;
params: any;
query: any;
baseUrl: string;
}
class HttpRequestBuilder {
private _httpRequest: HttpRequest;
constructor() {
this._httpRequest = {
body: null,
params: {},
query: {},
baseUrl: '',
};
}
public setBody(body: any) {
this._httpRequest.body = body;
return this;
}
public setParams(params: any) {
this._httpRequest.params = params;
return this;
}
public setQuery(query: any) {
this._httpRequest.query = query;
return this;
}
public setBaseUrl(baseUrl: string) {
this._httpRequest.baseUrl = baseUrl;
return this;
}
public build() {
return this._httpRequest;
}
}
export { HttpRequestBuilder, HttpRequest };
import { HttpStatusCode } from './HttpStatusCode';
interface HttpResponse {
httpStatus: HttpStatusCode;
body: { isJson: boolean; content: any };
headers: { [prop: string]: string }[];
}
class HttpResponseBuilder {
private _httpResponse: HttpResponse;
constructor() {
this._httpResponse = {
httpStatus: 0,
body: { isJson: false, content: null },
headers: [],
};
}
public setHeader(header: { [prop: string]: string }) {
this._httpResponse.headers.push(header);
return this;
}
public setBody(data?: any) {
this._httpResponse.body.content = data;
return this;
}
public setJsonBody(data: any) {
this._httpResponse.body.isJson = true;
this._httpResponse.body.content = this.buildSuccessContent(data);
return this;
}
public setError(error: string | Error) {
this._httpResponse.body.isJson = true;
this._httpResponse.body.content = this.buildErrorContent(error);
return this;
}
public setStatusCode(code: HttpStatusCode) {
this._httpResponse.httpStatus = code;
return this;
}
public setSourceLocation(sourceId: string) {
this._httpResponse.headers.push({ Location: sourceId });
return this;
}
public build() {
return this._httpResponse;
}
private buildSuccessContent(data: any) {
return {
data,
};
}
private buildErrorContent(error: string | Error) {
return {
error: {
code: this._httpResponse.httpStatus,
message: error.toString(),
timestamp: new Date().toISOString(),
},
};
}
}
export { HttpResponseBuilder, HttpResponse };
enum HttpStatusCode {
OK = 200,
CREATED = 201,
NO_CONTENT = 204,
UNAUTHORIZED = 401,
NOT_FOUND = 404,
FORBIDDEN = 403,
INTERNAL_SERVER_ERROR = 500,
}
export { HttpStatusCode };
import { HttpMethod } from './HttpMethod';
interface Route {
method: HttpMethod;
path: string;
handler: any;
middlewares: any[];
}
class RouteBuilder {
private _route: Route;
constructor() {
this._route = {
method: HttpMethod.GET,
path: '',
handler: null,
middlewares: [],
};
}
public setMethod(method: HttpMethod) {
this._route.method = method;
return this;
}
public setPath(path: string) {
this._route.path = path;
return this;
}
public setHandler(handler: any) {
this._route.handler = handler;
return this;
}
public setMiddlewares(middlewares: any[]) {
this._route.middlewares = middlewares;
return this;
}
public build() {
return this._route;
}
}
export { RouteBuilder, Route };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment