-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathFileAttachmentsManager.ts
More file actions
87 lines (71 loc) · 2.76 KB
/
FileAttachmentsManager.ts
File metadata and controls
87 lines (71 loc) · 2.76 KB
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
85
86
87
import {
AttachmentManager,
BacktraceModule,
BacktraceModuleBindData,
BacktraceStorage,
SessionFiles,
} from '@backtrace/sdk-core';
import { BacktraceFileAttachment, BacktraceFileAttachmentFactory } from './BacktraceFileAttachment.js';
const ATTACHMENT_FILE_NAME = 'bt-attachments';
type SavedAttachment = [path: string, name: string];
export class FileAttachmentsManager implements BacktraceModule {
private _attachmentsManager?: AttachmentManager;
constructor(
private readonly _storage: BacktraceStorage,
private readonly _fileAttachmentFactory: BacktraceFileAttachmentFactory,
private _fileName?: string,
) {}
public static create(storage: BacktraceStorage, fileAttachmentFactory: BacktraceFileAttachmentFactory) {
return new FileAttachmentsManager(storage, fileAttachmentFactory);
}
public static createFromSession(
sessionFiles: SessionFiles,
fileSystem: BacktraceStorage,
fileAttachmentFactory: BacktraceFileAttachmentFactory,
) {
const fileName = sessionFiles.getFileName(ATTACHMENT_FILE_NAME);
return new FileAttachmentsManager(fileSystem, fileAttachmentFactory, fileName);
}
public initialize(): void {
this.saveAttachments();
}
public bind({ attachmentManager, sessionFiles }: BacktraceModuleBindData): void {
if (this._fileName) {
throw new Error('This instance is already bound.');
}
if (!sessionFiles) {
return;
}
this._fileName = sessionFiles.getFileName(ATTACHMENT_FILE_NAME);
this._attachmentsManager = attachmentManager;
attachmentManager.attachmentEvents.on('scoped-attachments-updated', () => this.saveAttachments());
}
public dispose(): void {
this._fileName = undefined;
}
public async get(): Promise<BacktraceFileAttachment[]> {
if (!this._fileName) {
return [];
}
try {
const content = await this._storage.get(this._fileName);
if (!content) {
return [];
}
const attachments = JSON.parse(content) as SavedAttachment[];
return attachments.map(([path, name]) => this._fileAttachmentFactory.create(path, name));
} catch {
return [];
}
}
private async saveAttachments() {
if (!this._fileName || !this._attachmentsManager) {
return;
}
const fileAttachments = this._attachmentsManager
.get('scoped')
.filter((f): f is BacktraceFileAttachment => f instanceof BacktraceFileAttachment)
.map<SavedAttachment>((f) => [f.filePath, f.name]);
await this._storage.set(this._fileName, JSON.stringify(fileAttachments));
}
}