From 0db548330e544f19ff866d208a9c23ef11248533 Mon Sep 17 00:00:00 2001 From: Shreyash Date: Sat, 23 Dec 2023 10:58:12 +0530 Subject: [PATCH] Created a generalized catchAsync wrapper function to avoid use of redundant try catch blocks statements --- src/index.ts | 20 ++++++++------------ src/utils/catchAsync.ts | 10 ++++++++++ 2 files changed, 18 insertions(+), 12 deletions(-) create mode 100644 src/utils/catchAsync.ts diff --git a/src/index.ts b/src/index.ts index d308068..5af5625 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,8 +1,9 @@ import { promises as fs ,existsSync} from "fs"; import {createIfNot} from "./utils/fileUtils.js" import * as path from "node:path" -async function writeSQL(statement: string, saveFileAs = "", isAppend: boolean = false) { - try { +import { catchAsync } from "./utils/catchAsync.js"; + +const writeSQL = catchAsync(async function (statement: string, saveFileAs = "", isAppend: boolean = false) { const destinationFile = process.argv[2] || saveFileAs; if (!destinationFile) { throw new Error("Missing saveFileAs parameter"); @@ -13,13 +14,9 @@ async function writeSQL(statement: string, saveFileAs = "", isAppend: boolean = }else{ await fs.writeFile(`sql/${process.argv[2]}.sql`, statement); } - } catch (err) { - console.log(err); - } -} +}); -async function readCSV(csvFileName = "", batchSize: number = 0) { - try { +const readCSV = catchAsync(async function (csvFileName = "", batchSize: number = 0) { const fileAndTableName = process.argv[2] || csvFileName; batchSize = parseInt(process.argv[3]) || batchSize || 500; @@ -87,9 +84,8 @@ async function readCSV(csvFileName = "", batchSize: number = 0) { const sqlStatement = beginSQLInsert + values; // Write File writeSQL(sqlStatement, fileAndTableName, isAppend); - } catch (err) { - console.log(err); - } -} +}) + + readCSV(); console.log("Finished!"); diff --git a/src/utils/catchAsync.ts b/src/utils/catchAsync.ts new file mode 100644 index 0000000..69583f2 --- /dev/null +++ b/src/utils/catchAsync.ts @@ -0,0 +1,10 @@ +type AsyncCallback = (...args : any[]) => Promise + +export const catchAsync = (fn : AsyncCallback) =>{ + return (...args : any []) => { + fn(...args) + .catch((err) => { + console.error(err); + }); + }; +}; \ No newline at end of file