I have an API route in my next.js project, the idea is that it process the stats from an API the company I work for is using. It makes it's way through the whole function without issue until it comes time to convert the CSV to a JSON array, then it just returns as []
I figured out if I remove the CSVtoJSON conversion code and run to download the file, then alter the code so it has the CSVtoJSON code but removing the download of the file it will parse the CSV into the JSON I want without issue.
I am using asyn/await functions so I am not sure why it is reading the file as empty when I try to run it as one whole function but not if I run each chunk individually.
// logs.ts
import {NextApiRequest, NextApiResponse} from 'next'
import {processStats, fetchCsv, downloadFile} from './functions'
export default async (req: NextApiRequest, res: NextApiResponse) => {
const request = await processStats(1, 1, 'UTC', 'records', 'calls')
const csv_url = await fetchCsv(request.request_id)
const parsedf = await downloadFile(csv_url.download_url)
res.status(200).json(parsedf)
}
// downloadFile function
export async function downloadFile(url) {
const fs = require('fs')
const https = require('https')
const csv = require('csvtojson')
const fp = await fs.createWriteStream('pages/api/stats/data.csv')
const req = await https.get(url, function (res) {
res.pipe(fp)
})
const jsonArray = await csv().fromFile('pages/api/stats/data.csv')
return jsonArray
}
No errors are thrown it just sends back the empty []
array.
Any help would be amazingly appreciated.
Mac