Skip to content

Instantly share code, notes, and snippets.

@LouisSung
Created March 15, 2020 11:55
Show Gist options
  • Save LouisSung/ec6ea1744741b0f1bcf15cf4bc29593a to your computer and use it in GitHub Desktop.
Save LouisSung/ec6ea1744741b0f1bcf15cf4bc29593a to your computer and use it in GitHub Desktop.
NestJS example
/**
* @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;};
/**
* @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