Last active
September 12, 2022 21:30
-
-
Save prateekkathal/c467c37f68ace77d2d899374b157d166 to your computer and use it in GitHub Desktop.
For Medium Article (Creating/Writing/Downloading Files in NestJS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This file should exist in `src/models/users` | |
import { parse } from "json2csv"; | |
import { Injectable, NotFoundException } from "@nestjs/common"; | |
import { | |
getFile, | |
createFile, | |
checkIfFileOrDirectoryExists, | |
} from "./../../common/helpers/storage.helper"; | |
/** | |
* Service dealing with User based operations. | |
* | |
* @class | |
*/ | |
@Injectable() | |
export class UsersService { | |
/** | |
* Creates a CSV file with users data | |
* | |
* @returns {Promise<string>} | |
*/ | |
async exportUserDataToCSV(): Promise<string> { | |
return await this.getMany() // Some function that gets users data. | |
.then(async (users) => { | |
const [csvData, csvFields] = | |
this.transformUsersDataForCSV(users); // Some function that returns you csv data & fields. | |
if (!csvData || !csvFields) { | |
return Promise.reject("Unable to transform users data for CSV."); | |
} | |
const csv = parse(csvData, { fields: csvFields }); | |
const filePath = `storage/app/exports/users`; | |
const fileName = `users-${new Date().toISOString()}.csv`; | |
await createFile(filePath, fileName, csv); | |
return Promise.resolve(fileName); | |
}) | |
.catch((error) => Promise.reject(error)); | |
} | |
/** | |
* Gets an exported CSV file | |
* | |
* @param {string} filename | |
* | |
* @returns {Promise<string>} | |
*/ | |
async getExportedUserCSV(filename: string): Promise<string> { | |
const filePath = `storage/app/exports/users/${filename}`; | |
if (!checkIfFileOrDirectoryExists(filePath)) { | |
throw new NotFoundException('Users export not found.'); | |
} | |
return (await getFile(filePath, 'utf8')).toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment