(client: DocumentEngineClient, req: Request, res: Response)
| 143 | * File download handler |
| 144 | */ |
| 145 | export async function downloadHandler(client: DocumentEngineClient, req: Request, res: Response) { |
| 146 | try { |
| 147 | const paramId = req.params.id; |
| 148 | const documentId = Array.isArray(paramId) ? paramId[0] : paramId; |
| 149 | |
| 150 | if (!documentId) { |
| 151 | return res.status(400).send(errorTemplate('Document ID is required')); |
| 152 | } |
| 153 | |
| 154 | // Get document info to get the title for the filename |
| 155 | const documentInfo = await client['fetch-document-info']({ documentId }); |
| 156 | |
| 157 | // Check if document info exists and has title |
| 158 | const documentData = documentInfo.data.data; |
| 159 | if (!documentData) { |
| 160 | throw new Error(`No document data returned for document ID: ${documentId}`); |
| 161 | } |
| 162 | |
| 163 | const documentTitle = documentData.title || 'document'; |
| 164 | const safeFilename = documentTitle.replace(/[^a-z0-9]/gi, '_').toLowerCase() + '.pdf'; |
| 165 | |
| 166 | // Download the document as PDF with proper binary response handling |
| 167 | const response = await client['download-document-pdf']({ documentId }, undefined, { |
| 168 | responseType: 'arraybuffer', |
| 169 | }); |
| 170 | |
| 171 | // Set headers for file download |
| 172 | res.setHeader('Content-Type', 'application/pdf'); |
| 173 | res.setHeader('Content-Disposition', `attachment; filename="${safeFilename}"`); |
| 174 | |
| 175 | res.send(Buffer.from(response.data)); |
| 176 | } catch (error) { |
| 177 | logger.error(null, 'Document download error', { error }); |
| 178 | res |
| 179 | .status(500) |
| 180 | .send( |
| 181 | errorTemplate( |
| 182 | `An error occurred while downloading the document: ${error instanceof Error ? error.message : 'Unknown error'}` |
| 183 | ) |
| 184 | ); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | /** |
| 189 | * File delete handler |
no test coverage detected