import { CacheScreeningRepository } from '@lib/outbound/repository/cache-screening.repository'
import { createWriteStream, createReadStream, existsSync } from 'fs'
import { format } from 'fast-csv'
import { parse } from '@fast-csv/parse'
import { logger } from '@lib/config/logger'
import { RawScreening } from '@lib/model/screening.model'
import { RawPatient } from '@lib/model/patient.model'
import { RawRegistration } from '@lib/model/registration.model'
export class CsvCacheScreeningRepository implements CacheScreeningRepository {
private csvStream: any
private filePath = 'lib/outbound/repository/cache/data.csv'
private rawDataScreening: RawScreening[] = []
private rawPatient: RawPatient[] = []
private rawRegistration: RawRegistration[] = []
constructor() {
this.initCsvStream()
}
private initCsvStream() {
const isFileExist = existsSync(this.filePath)
const ws = createWriteStream(this.filePath, { flags: 'a' })
this.csvStream = format({ headers: !isFileExist })
this.csvStream.pipe(ws)
this.countRows()
}
async create(data: RawScreening): Promise<string> {
const dataCsv = [JSON.stringify(data)]
await this.csvStream.write(dataCsv)
return 'success'
}
async get(): Promise<any> {}
async countRows(): Promise<void> {
const rs = createReadStream(this.filePath)
const csv = parse({ headers: false, skipLines: 1 })
const count = 0
rs.pipe(csv)
.on('error', (error) => logger.error(error))
.on('data', (row) => count++)
.on('end', () => {})
}
}