-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdocument.service.ts
More file actions
176 lines (158 loc) · 5.67 KB
/
Copy pathdocument.service.ts
File metadata and controls
176 lines (158 loc) · 5.67 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { Injectable, Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { existsSync } from "fs";
import { mkdir, writeFile } from "fs/promises";
import { join } from "path";
import { v4 as uuidv4 } from "uuid";
import { DocumentStatus } from "@/generated/enums";
import { DatabaseService, DocumentData } from "../database/database.service";
import { JsonValue } from "../generated/internal/prismaNamespace";
export interface UploadedDocument {
id: string;
title: string;
original_filename: string;
file_path: string;
file_type: string;
file_size: number;
metadata?: Record<string, unknown>;
source: string;
status: DocumentStatus;
created_at: Date;
updated_at: Date;
}
@Injectable()
export class DocumentService {
private readonly logger = new Logger(DocumentService.name);
private readonly storagePath: string;
constructor(
private databaseService: DatabaseService,
private configService: ConfigService,
) {
this.storagePath =
this.configService.get<string>("STORAGE_PATH") ||
join(process.cwd(), "storage", "documents");
this.ensureStorageDirectory();
}
private async ensureStorageDirectory(): Promise<void> {
try {
if (!existsSync(this.storagePath)) {
await mkdir(this.storagePath, { recursive: true });
this.logger.log(`Created storage directory: ${this.storagePath}`);
}
} catch (error) {
this.logger.error(`Failed to create storage directory: ${error.message}`);
throw error;
}
}
private getFileExtension(fileType: string): string {
const typeMap: Record<string, string> = {
pdf: "pdf",
image: "jpg",
scan: "pdf",
};
return typeMap[fileType.toLowerCase()] || "bin";
}
private generateFileName(originalFilename: string, fileType: string): string {
const extension = this.getFileExtension(fileType);
const uuid = uuidv4();
const sanitizedOriginal = originalFilename
.replace(/[^a-zA-Z0-9.-]/g, "_")
.substring(0, 50);
return `${uuid}_${sanitizedOriginal}.${extension}`;
}
async uploadDocument(
title: string,
fileBase64: string,
fileType: string,
originalFilename: string,
metadata?: Record<string, unknown>,
): Promise<UploadedDocument> {
this.logger.debug("=== DocumentService.uploadDocument ===");
this.logger.debug(
`Title: ${title}, FileType: ${fileType}, OriginalFilename: ${originalFilename}`,
);
try {
// Decode base64 file
let fileBuffer: Buffer;
try {
// Remove data URL prefix if present (e.g., "data:application/pdf;base64,")
const base64Data = fileBase64.includes(",")
? fileBase64.split(",")[1]
: fileBase64;
fileBuffer = Buffer.from(base64Data, "base64");
} catch (error) {
this.logger.error(`Failed to decode base64 file: ${error.message}`);
throw new Error("Invalid base64 file data");
}
const fileSize = fileBuffer.length;
this.logger.debug(`Decoded file size: ${fileSize} bytes`);
// Generate unique filename and path
const fileName = this.generateFileName(originalFilename, fileType);
const fullFilePath = join(this.storagePath, fileName);
// Store relative path in database (relative to storage root)
const relativePath = `storage/documents/${fileName}`;
// Ensure storage directory exists
await this.ensureStorageDirectory();
// Save file to filesystem
await writeFile(fullFilePath, fileBuffer);
this.logger.debug(`File saved to: ${fullFilePath}`);
// Store metadata in database via API
const documentData: Omit<
DocumentData,
"id" | "created_at" | "updated_at"
> = {
title,
original_filename: originalFilename,
file_path: relativePath,
file_type: fileType,
file_size: fileSize,
metadata: (metadata || {}) as JsonValue,
source: "api",
status: DocumentStatus.ongoing_ocr,
apim_request_id: null,
};
const savedDocument =
await this.databaseService.createDocument(documentData);
this.logger.debug(`Document saved to database: ${savedDocument.id}`);
const result: UploadedDocument = {
id: savedDocument.id!,
title: savedDocument.title,
original_filename: savedDocument.original_filename,
file_path: savedDocument.file_path,
file_type: savedDocument.file_type,
file_size: savedDocument.file_size,
metadata: savedDocument.metadata as Record<string, unknown>,
source: savedDocument.source,
status: savedDocument.status,
created_at: savedDocument.created_at || new Date(),
updated_at: savedDocument.updated_at || new Date(),
};
this.logger.debug("=== DocumentService.uploadDocument completed ===");
return result;
} catch (error) {
this.logger.error(`Error uploading document: ${error.message}`);
this.logger.error(`Stack: ${error.stack}`);
throw error;
}
}
async getDocument(id: string): Promise<UploadedDocument | null> {
this.logger.debug(`DocumentService.getDocument: ${id}`);
const document = await this.databaseService.findDocument(id);
if (!document) {
return null;
}
return {
id: document.id!,
title: document.title,
original_filename: document.original_filename,
file_path: document.file_path,
file_type: document.file_type,
file_size: document.file_size,
metadata: document.metadata as Record<string, unknown>,
source: document.source,
status: document.status,
created_at: document.created_at || new Date(),
updated_at: document.updated_at || new Date(),
};
}
}