import http from 'http' import consola from 'consola' import UrlParse, { qs } from 'url-parse' import camelcase from 'camelcase' import mongodb from 'mongodb' import { NextFunction } from 'connect' import { QRequest, QRequestControllerConstructorData, } from '../../../types/server' interface ExeControllerConfig { method: string url: string body?: any next?: NextFunction db: mongodb.Db req?: QRequest res?: http.ServerResponse dirname?: string } export async function ImportController({ method, url, body, next, db, req, res, }: ExeControllerConfig) { const { default: config } = await import(`${process.cwd()}/config.js`) if (url.includes('/v2/')) { url = url.replace('/v2/', '/') } const parsedURL = new UrlParse(url) const splittedURL = parsedURL.pathname.split('/').filter((v) => v) const controllerName = splittedURL[0] const originalFunctionName = splittedURL[1] || 'index' const functionName = camelcase(originalFunctionName) const query = parsedURL ? qs.parse(String(parsedURL.query)) : null try { const ControllerModule = await req?.Router.routes[controllerName] const Controller = ControllerModule?.default if (Controller) { const requestData: QRequestControllerConstructorData = { method, db, body, req, res, session: req?.session, query, url, splittedURL, config, } const controller = new Controller(requestData) let answer let methodFunctionName = `_${functionName}_${method}` if (controller[methodFunctionName]) { answer = await controller[methodFunctionName]() } else if (controller._param) { methodFunctionName = `__param_${method}` answer = await controller[methodFunctionName](originalFunctionName) } else { if (res) { res.statusCode = 404 res.end('Not found') } return false } if (answer === undefined) { if (res) { res.statusCode = 404 res.end('Not found') } return false } let answerData = answer if (res) { const hasContentType = res.getHeader('Content-Type') if (!hasContentType) { res.setHeader('Content-Type', 'application/json') answerData = JSON.stringify(answerData) } res.end(answerData) return false } return JSON.stringify(answerData) } } catch (error) { if (process.env.NODE_ENV !== 'production') { consola.error(error) } if (res) { res.statusCode = 404 res.end('Not found') } return false } next && next() }