import http from 'http' import mongodb from 'mongodb' import { QRequest, QRequestControllerConstructorData, } from './../../types/server.d' export class QRequestController { method!: string body!: any db!: mongodb.Db query?: any session?: any req?: QRequest res?: http.ServerResponse url?: string splittedURL: string[] = [] config: any constructor({ method, body, db, query, session, req, res, url, splittedURL, config, }: QRequestControllerConstructorData) { this.method = method this.body = body this.db = db this.query = query this.session = session this.req = req this.res = res this.url = url this.splittedURL = splittedURL this.config = config } answer(result: boolean, data?: any, message?: string) { return { result, data, message } } setStatusCode(code: number) { if (this.res) { this.res.statusCode = code } } setHeader(name: string, value: string) { if (this.res) { this.res.setHeader(name, value) } } setSession(key: string, data: any) { if (this.req) { this.req.session[key] = data this.session[key] = data } } deleteSession(key: string) { if (this.req) { this.req.session[key] = null this.session[key] = null } } } export function GET(target: any, key: any, descriptor: PropertyDescriptor) { const newPropertyKey = `_${key}_GET` Object.defineProperty(target, newPropertyKey, descriptor) } export function POST(target: any, key: any, descriptor: PropertyDescriptor) { Object.defineProperty(target, `_${key}_POST`, descriptor) } export function DELETE(target: any, key: any, descriptor: PropertyDescriptor) { const newPropertyKey = `_${key}_DELETE` Object.defineProperty(target, newPropertyKey, descriptor) } export function PUT(target: any, key: any, descriptor: PropertyDescriptor) { const newPropertyKey = `_${key}_DELETE` Object.defineProperty(target, newPropertyKey, descriptor) } interface SecureConfig { allow?: string[] } export function SECURE(config?: SecureConfig) { const allow = config?.allow || [] return function (_: any, __: any, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value const isDev = process.env.NODE_ENV !== 'production' if (isDev) { return } descriptor.value = function (...args: any) { const instanse = this as QRequestController if (instanse.session.auth) { if (allow && allow.length) { if (allow.includes(instanse.session.auth.role)) { return originalMethod.apply(this, args) } else { if (instanse.res) { instanse.res.statusCode = 401 } return null } } else { return originalMethod.apply(this, args) } } else { if (instanse.res) { instanse.res.statusCode = 401 } return null } } } }