-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdocument.controller.ts
More file actions
200 lines (173 loc) · 5.82 KB
/
Copy pathdocument.controller.ts
File metadata and controls
200 lines (173 loc) · 5.82 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import {
Controller,
Get,
HttpCode,
HttpStatus,
Logger,
NotFoundException,
Param,
Req,
Res,
} from "@nestjs/common";
import { Request, Response } from "express";
import { readFile } from "fs/promises";
import { join } from "path";
import { OcrResult } from "@/generated/client";
import { Roles } from "../auth/roles.decorator";
import { DatabaseService, DocumentData } from "../database/database.service";
@Controller("api")
export class DocumentController {
private readonly logger = new Logger(DocumentController.name);
constructor(private readonly databaseService: DatabaseService) {}
@Get("protected")
getProtectedData(@Req() req: Request): {
message: string;
user: {
idirUsername?: string;
displayName?: string;
email?: string;
};
} {
const user = req.user; // Contains decoded token
return {
message: "Protected data",
user: {
idirUsername: user?.idir_username,
displayName: user?.display_name,
email: user?.email,
},
};
}
@Get("admin")
@Roles("admin")
getAdminData(@Req() req: Request): {
message: string;
user: {
idirUsername?: string;
displayName?: string;
email?: string;
roles: string[];
};
} {
const user = req.user;
return {
message: "Admin only data",
user: {
idirUsername: user?.idir_username,
displayName: user?.display_name,
email: user?.email,
roles: user?.roles || [],
},
};
}
@Get("documents")
@HttpCode(HttpStatus.OK)
async getAllDocuments(): Promise<DocumentData[]> {
this.logger.debug("=== DocumentController.getAllDocuments ===");
try {
const documents = await this.databaseService.findAllDocuments();
this.logger.debug(`Retrieved ${documents.length} documents`);
this.logger.debug("=== DocumentController.getAllDocuments completed ===");
return documents;
} catch (error) {
this.logger.error(`Error retrieving documents: ${error.message}`);
this.logger.error(`Stack: ${error.stack}`);
throw new NotFoundException(
error.message || "Failed to retrieve documents",
);
}
}
@Get("documents/:documentId/ocr")
@HttpCode(HttpStatus.OK)
async getOcrResult(
@Param("documentId") documentId: string,
): Promise<OcrResult> {
this.logger.debug(`=== DocumentController.getOcrResult ===`);
this.logger.debug(`Document ID: ${documentId}`);
try {
// First check if document exists and its status
const document = await this.databaseService.findDocument(documentId);
if (document) {
this.logger.debug(`Document status: ${document.status}`);
this.logger.debug(`Document created: ${document.created_at}`);
if (document.apim_request_id) {
this.logger.debug(`APIM Request ID: ${document.apim_request_id}`);
}
} else {
this.logger.warn(`Document not found: ${documentId}`);
throw new NotFoundException(`Document not found: ${documentId}`);
}
const ocrResult = await this.databaseService.findOcrResult(documentId);
if (!ocrResult) {
this.logger.warn(`OCR result not found for document: ${documentId}`);
this.logger.warn(`Document status is: ${document.status}`);
throw new NotFoundException(
`OCR result not found for document: ${documentId}. Current status: ${document.status}`,
);
}
this.logger.debug(
`OCR result retrieved successfully for document: ${documentId}`,
);
this.logger.debug(`OCR processed at: ${ocrResult.processed_at}`);
this.logger.debug("=== DocumentController.getOcrResult completed ===");
return ocrResult;
} catch (error) {
this.logger.error(`Error retrieving OCR result: ${error.message}`);
this.logger.error(`Stack: ${error.stack}`);
if (error instanceof NotFoundException) {
throw error;
}
throw new NotFoundException(
error.message ||
`Failed to retrieve OCR result for document: ${documentId}`,
);
}
}
@Get("documents/:documentId/download")
@HttpCode(HttpStatus.OK)
async downloadDocument(
@Param("documentId") documentId: string,
@Res() res: Response,
): Promise<void> {
this.logger.debug(`=== DocumentController.downloadDocument ===`);
this.logger.debug(`Document ID: ${documentId}`);
try {
// Find the document
const document = await this.databaseService.findDocument(documentId);
if (!document) {
throw new NotFoundException(`Document not found: ${documentId}`);
}
// Resolve stored relative path to absolute (we only store relative paths)
const filePath = join(process.cwd(), document.file_path);
// Read file
const fileBuffer = await readFile(filePath);
// Set appropriate headers
const fileName = document.original_filename || `document-${documentId}`;
const mimeType =
document.file_type === "pdf"
? "application/pdf"
: document.file_type === "image"
? "image/jpeg"
: "application/octet-stream";
res.setHeader("Content-Type", mimeType);
res.setHeader("Content-Disposition", `inline; filename="${fileName}"`);
res.setHeader("Content-Length", fileBuffer.length);
this.logger.debug(
`Serving file: ${filePath} (${fileBuffer.length} bytes)`,
);
this.logger.debug(
"=== DocumentController.downloadDocument completed ===",
);
res.send(fileBuffer);
} catch (error) {
this.logger.error(`Error downloading document: ${error.message}`);
this.logger.error(`Stack: ${error.stack}`);
if (error instanceof NotFoundException) {
throw error;
}
throw new NotFoundException(
error.message || `Failed to download document: ${documentId}`,
);
}
}
}