forked from sourcefuse/loopback4-microservice-catalog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexport-to-csv.service.ts
84 lines (73 loc) · 2.72 KB
/
export-to-csv.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import {PutObjectCommand, S3} from '@aws-sdk/client-s3';
import {BindingScope, Provider, inject, injectable} from '@loopback/core';
import {EntityCrudRepository, repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {AuditLog, AuditLogRepository} from '@sourceloop/audit-log';
import {AWSS3Bindings, AwsS3Config} from '../keys';
import {ExportToCsvFn} from '../types';
@injectable({scope: BindingScope.TRANSIENT})
export class ExportToCsvProvider implements Provider<ExportToCsvFn> {
constructor(
@inject(AWSS3Bindings.Config, {optional: true})
private readonly config: AwsS3Config,
@repository(AuditLogRepository)
public auditLogRepository: EntityCrudRepository<AuditLog, string, {}>,
) {}
value(): ExportToCsvFn {
return async (selectedAuditLogs: AuditLog[]) => {
return this.exportToCsv(selectedAuditLogs);
};
}
async exportToCsv(selectedAuditLogs: AuditLog[]): Promise<string> {
const csvRows = [];
const header = Object.keys(selectedAuditLogs[0]);
csvRows.push(header.join(','));
for (const auditLog of selectedAuditLogs) {
const values = [];
for (const key of header) {
let value = auditLog[key];
// Check if the value is the "after" object
if (key === 'after' || key === 'before') {
value = JSON.stringify(auditLog[key]);
// Escape existing quotation marks within the value
value = value.replace(/"/g, '""');
// Surround the value with quotation marks
value = `"${value}"`;
} else if (key === 'actedAt') {
value = new Date(value).toISOString();
} else {
//this is intentional
}
values.push(value);
}
csvRows.push(values.join(','));
}
const csvString = csvRows.join('\n');
const timestamp = new Date().toISOString();
//Example: PATH_TO_UPLOAD_FILES='/uploads'
const fileName = `${process.env?.PATH_TO_UPLOAD_FILES}/audit_logs_${timestamp}.csv`;
const s3Config: AwsS3Config = {
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? this.config.accessKeyId,
secretAccessKey:
process.env.AWS_SECRET_ACCESS_KEY ?? this.config.secretAccessKey,
},
region: process.env.AWS_REGION ?? this.config.region,
...this?.config,
// Other properties...
};
const s3Client: S3 = new S3(s3Config);
const bucketName = process.env.AWS_S3_BUCKET_NAME;
const params = {
Body: csvString,
Key: fileName,
Bucket: bucketName as string,
};
try {
await s3Client.send(new PutObjectCommand(params));
return params.Key;
} catch (error) {
throw new HttpErrors.UnprocessableEntity(error.message);
}
}
}