npm i json2csv
그다음 post로 보내준 데이터를 받아서 아래 코드 처럼 적용하면 csv형식으로 변환된다.
import { Parser } from 'json2csv';
async convertCsv(createRealTimeRpmDto: CreateRealTimeRpmDto) {
const fields = ['rpm', 'time']; //필드이름 정의
const json2csvParser = new Parser({ fields });//필드이름 적용
const csv = json2csvParser.parse(createRealTimeRpmDto.rpmBlocks);
console.log(csv);
}
GCP에 들어가 Cloud Storage항목을 선택합니다.
버킷을 만들어 줍니다. 자세한 내용은 참고에 있는 링크를 참고해주세요.
.env
PROJECT_ID = "project_id"
PRIVATE_KEY = "private_key"
CLIENT_EMAIL = "client_email"
STORAGE_MEDIA_BUCKET = "buket_name" // 위에서 생성한 버켓의 이름을 넣어주면 됨
import { ConfigService } from '@nestjs/config';
import { Bucket, Storage } from '@google-cloud/storage';
import { BadRequestException, Injectable } from '@nestjs/common';
import { parse } from 'path';
@Injectable()
export class CloudStorageService {
private bucket: Bucket;
private storage: Storage;
constructor(private readonly configService: ConfigService) {
this.storage = new Storage({
projectId: this.configService.get('PROJECT_ID'),
credentials: {
client_email: this.configService.get('CLIENT_EMAIL'),
private_key: this.configService.get('PRIVATE_KEY'),
},
});
this.bucket = this.storage.bucket(
configService.get('STORAGE_MEDIA_BUCKET'),
);
}
async uploadFromMemory(uploadedFile: string, destination: string) {
const file = this.bucket.file(destination);
try {
await file.save(uploadedFile);
} catch (error) {
throw new BadRequestException(error?.message);
}
return {
publicUrl: `https://storage.googleapis.com/${this.bucket.name}/${file.name}`,
};
}
import { Injectable } from '@nestjs/common';
import { CreateRealTimeRpmDto } from './dto/create-realtime-rpm.dto';
import { UpdateRealTimeRpmDto } from './dto/update-realtime-rpm.dto';
import { Parser } from 'json2csv';
import { CloudStorageService } from 'src/common/services/cloud-storage.service';
@Injectable()
export class RealTimeRpmService {
constructor(private readonly cloudStorageService: CloudStorageService) {}
async convertCsv(createRealTimeRpmDto: CreateRealTimeRpmDto) {
const fields = ['rpm', 'time'];
const json2csvParser = new Parser({ fields });
const csv = json2csvParser.parse(createRealTimeRpmDto.rpmBlocks);
console.log(csv);
/////////////////////////////////cloud storage 코드 추가
const TIME_ZONE = 9 * 60 * 60 * 1000; // 9시간
const now = new Date(Date() + TIME_ZONE)
.toISOString()
.replace('T', '')
.replace(/\..*/, '');
//////////////////////////파일 이름에 저장한 시간 추가
const destination = 'realtime-RPM/' + now + '_RPM.csv';
const csvFile = await this.cloudStorageService.uploadFromMemory(
csv,
destination,
);
return csvFile;
}