Im trying to read an uploaded CSV file in nest and get the following error
' ERROR [ExceptionHandler] Nest can't resolve dependencies of the AssetsController (AssetsService, ?). Please make sure that the argument CsvParser at index [1] is available in the AssetsModule context.'
I have imported the package: https://www.npmjs.com/package/nest-csv-parser
import {CsvParser} from 'nest-csv-parser'
Added the constructor
constructor(private readonly csvParser: CsvParser) {}
Created the entity
class Asset {
assetID: string;
assetName: string;
assetType: string;
assetDescription: string;
assetLocation: string;
assetImage: string;
assetStatus: string;
assetNotes: string;
assetClientID: string;
assetSiteID: string;
assetContractorID: string;
assetMaintenanceID: string;
assetDocumentID: string;
assetCreated: string;
assetUpdated: string;
assetCreatedBy: string;
assetUpdatedBy: string;
}
and my function looks like so
@Get('import')
async parseCSVFile()
{
const csvPath = getCSVFile();
console.log(" => ", csvPath);
const stream = fs.createReadStream(csvPath)
const entities: ParsedData<InstanceType<any>> = await this.csvParser.parse(stream, Asset)
// You will get JSON
console.log(entities);
}
Module
import { Module } from '@nestjs/common';
import { AssetsService } from './assets.service';
import { AssetsController } from './assets.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { AssetSchema } from 'assets/schemas/assets.schema';
@Module({
imports: [
MongooseModule.forFeature([{name: 'Assets', schema: AssetSchema}])
],
providers: [AssetsService],
controllers: [AssetsController]
})
export class AssetsModule {}
I have been following along with How do I read an uploaded file (text/.csv) using nestjs and Multer
Read the docs of nest-csv-parser
:
that CsvParser
provider is registered and exported by CsvModule
, thus you must import it into your AssetsModule
module.