From 2cc50182aa844f5937b09fcb99415572878d014d Mon Sep 17 00:00:00 2001 From: Thomas Dax Date: Fri, 10 Jan 2025 10:43:00 +0100 Subject: [PATCH] Add upgrade script for replacing ExceptionInterceptor with ExceptionFilter --- ...ption-interceptor-with-exception-filter.ts | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/v7/replace-exception-interceptor-with-exception-filter.ts diff --git a/src/v7/replace-exception-interceptor-with-exception-filter.ts b/src/v7/replace-exception-interceptor-with-exception-filter.ts new file mode 100644 index 0000000..a6f73be --- /dev/null +++ b/src/v7/replace-exception-interceptor-with-exception-filter.ts @@ -0,0 +1,38 @@ +import { readFile, writeFile } from "fs/promises"; +import { Project } from "ts-morph"; + +import { formatCode } from "../util/format-code.util"; + +/** + * Replaces the old ExceptionInterceptor with the new ExceptionFilter + */ +export default async function replaceExceptionInterceptorWithExceptionFilter() { + const filePath = "api/src/main.ts"; + let fileContent = (await readFile(filePath)).toString(); + + if (!fileContent.includes("ExceptionInterceptor")) { + console.log("ExceptionInterceptor not found in main.ts. Make sure that you use the new ExceptionFilter."); + return; + } + + const searchString = "app.useGlobalInterceptors\\(new ExceptionInterceptor\\(config.debug\\)\\);"; + const re = new RegExp(`^.*${searchString}.*$`, "gm"); + fileContent = fileContent.replace(re, "app.useGlobalFilters(new ExceptionFilter(config.debug));"); + + await writeFile(filePath, await formatCode(fileContent, filePath)); + + const project = new Project({ tsConfigFilePath: "./api/tsconfig.json" }); + + const sourceFile = project.getSourceFile(filePath); + + if (!sourceFile) { + throw new Error(`Can't get source file for ${filePath}`); + } + + sourceFile.addImportDeclaration({ + namedImports: ["ExceptionFilter"], + moduleSpecifier: "@comet/cms-api", + }); + + sourceFile.saveSync(); +}