Created
March 15, 2020 11:55
-
-
Save LouisSung/ec6ea1744741b0f1bcf15cf4bc29593a to your computer and use it in GitHub Desktop.
NestJS example
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
/** | |
* @file [Abstract Class] Base class for APIs to unify entrypoint for all implementations | |
* @version v1.0.0 | |
* @author LouisSung | |
* @license MIT | |
*/ | |
export abstract class BaseApi { | |
protected readonly reqBody: {[key: string]: Json;}; | |
protected constructor(reqBody: {[key: string]: Json;}) { | |
this.reqBody = reqBody; | |
} | |
public abstract entry(): Json; | |
} | |
// ===== Type Definitions ===== | |
export type Json = null | boolean | number | string | Array<Json> | {[key: string]: Json;}; |
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
/** | |
* @file [API Endpoint] Copycat endpoint (`/copycat`) | |
* @version v1.1.0 | |
* @author LouisSung | |
* @license MIT | |
*/ | |
import {Body, Controller, Get, Post, Req} from '@nestjs/common'; | |
import {Request} from 'express'; | |
import {BaseApi, Json} from '../../core/base-api'; | |
@Controller('copycat') | |
export class CopycatController { | |
@Get(['/', '/get']) | |
public copyGet(@Req()req: Request): ReqQuery & Hi { | |
const hi: Hi = {host: req.hostname, method: req.method, mew: 'ฅ• ω •ฅ'}; | |
return {...(req.query as ReqQuery), ...hi}; | |
} | |
@Post(['/', '/post']) | |
public copyPost(@Req()req: Request, @Body()copycatDto: CopycatDto): SayHi { | |
const hi: Hi = {host: req.hostname, method: req.method, mew: 'ฅ´• ω •`ฅ'}; | |
return {...copycatDto, ...hi}; | |
} | |
@Post('/valid') | |
public copyValid(@Req()req: Request, @Body()copycatDto: CopycatDto): SayHi { | |
// @LS: Copycat is defined as class below | |
// eslint-disable-next-line @typescript-eslint/no-use-before-define | |
return new Copycat(req, copycatDto).entry(); | |
} | |
} | |
class Copycat extends BaseApi { | |
protected readonly reqBody: CopycatDto & Hi; | |
constructor(req: Request, copycatDto: CopycatDto) { | |
const hi: Hi = {host: req.hostname, method: req.method, mew: 'ฅ´• ω •`ฅ'}; | |
super({...copycatDto, ...hi}); | |
} | |
public entry(): SayHi { return {...this.reqBody, mew: 'ฅ`• ω •´ฅ'}; } | |
} | |
// ===== Type Definitions ===== | |
interface ReqQuery {[key: string]: string | Array<string>;} | |
interface Hi {host: string; method: string; mew: 'ฅ• ω •ฅ' | 'ฅ´• ω •`ฅ' | 'ฅ`• ω •´ฅ';} | |
interface CopycatDto {[key: string]: Json;} | |
interface SayHi extends Hi, CopycatDto {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment