Refector Typescript code to convert JSON api to CSV [duplicate]

I have a project in Node JS with Typescipt in which I have a class that receives a JSON from an api and converts it to CSV format.

The problem is that I have all the code in the main controller, I am trying to refactor the code but I don't really know how to do it.

This is my controller.ts:

class IndexController {

    public async index(req: Request, res: Response) {
        const api = req.query.api; // 'api1'

        let json = await axios.get(new jsonUtils().jsonUrl(api));

        let dir = new createDir().checkExistsOrCreate(`src/output/`, api); //create directory => return: 'src/output/api1'

        let nameFile = new jsonUtils().fileName(api);   //name file => return: dev.api1

        let constUt = new constUtils(); //return: maxRecors: 100
        let json2csvCallback = function (err: any, csv: any) {
            if (err) throw err;
            const headers = csv.split('\n').slice(0, 1);
            const records = csv.split('\n').slice(0,);

            for (let i = 1; i < records.length; i = i + constUt.maxRecords) {
                let dataOut = headers.concat(records.slice(i, i + constUt.maxRecords)).join('\n');
                let id = Math.floor(i / constUt.maxRecords) + 1;
                fs.writeFileSync(`${dir}/${nameFile}.${id}.csv`, dataOut);


        converter.json2csv(, json2csvCallback);          



export const indexController = new IndexController();

What I'm trying to do: create another class in another file that creates the CSV to call from the controller and convert the function to async / await. I've been studying Node JS for a very short time and I'm not sure how to do it. Any suggestions to improve the code would be very useful.

Read more here:

Content Attribution

This content was originally published by menphis at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: