Files
few-line-engine/src/query/base/base-query.controller.ts

95 lines
2.4 KiB
TypeScript

import {
Body,
Delete,
Headers,
Inject,
Param,
Post,
Req,
Res,
UseGuards,
} from "@nestjs/common";
import { Response, Request } from "express";
import { QueryHandlerService } from "../handler/query.handler.service";
import { ApiTokenGuard } from "src/api/guards/api-token.guard";
import { QueryExecuterService } from "../executer/query.executer.service";
import { QueryGuard } from "src/query/guards/query.guard";
@UseGuards(ApiTokenGuard)
export abstract class BaseQueryController {
constructor(
@Inject(QueryHandlerService)
protected readonly queryHandlerService: QueryHandlerService,
@Inject(QueryExecuterService)
protected readonly queryExecuterService: QueryExecuterService
) {}
protected abstract getIsCommand(): boolean;
@Post("create")
async createQuery(
@Body() queryData: { projectToken: string; source: string }
) {
return this.queryHandlerService.createQuery(queryData, this.getIsCommand());
}
@Post("update/:id")
@UseGuards(QueryGuard)
async updateQuery(
@Body() updateData: Partial<{ source: string }>,
@Param("id") id: string
) {
return this.queryHandlerService.updateQuery(id, updateData);
}
@Post("/run/:id")
@UseGuards(QueryGuard)
async runQuery(
@Param("id") id: string,
@Body() query: Record<string, any>,
@Headers() headers: Record<string, any>,
@Res() res: Response
) {
const queryResult = await this.queryExecuterService.runQueryQueued(
id,
query,
headers,
headers.cookie.split("; ").reduce((acc, cookie) => {
const [key, value] = cookie.split("=");
acc[key] = value;
return acc;
}, {})
);
res.status(queryResult?.statusCode || 200);
if (queryResult?.cookies) {
for (const [key, value] of Object.entries(queryResult?.cookies || {})) {
res.cookie(key, value);
}
}
if (
queryResult?.redirect ||
(queryResult?.statusCode === 302 &&
queryResult?.headers &&
queryResult?.headers["Location"])
) {
res.redirect(queryResult?.redirect || queryResult?.headers["Location"]);
return;
}
for (const [key, value] of Object.entries(queryResult?.headers || {})) {
res.setHeader(key, value);
}
res.send(queryResult?.response || null);
}
@Delete("/delete/:id")
@UseGuards(QueryGuard)
async deleteQuery(@Param("id") id: string) {
return this.queryHandlerService.deleteQuery(id);
}
}