All files / pages/api download.ts

0% Statements 0/30
0% Branches 0/8
0% Functions 0/4
0% Lines 0/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                               
import { getMessageService } from './message.service'
import { getServerSession } from 'next-auth'
import { NextApiRequest, NextApiResponse } from 'next'
import { authOptions } from './auth/[...nextauth]'
import { MessageEntity } from '../../entities/entities/message.entity'
import { getLogger } from '../../logging/log-util'
import { cachified } from 'cachified'
import {
  lruCache as cache,
  defaultTtl as ttl,
} from '../../lib/message-cache-utils'
 
const logger = getLogger('download')
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const messageId = req.query['id'] ? req.query['id'].toString() : ''
 
  const session = await getServerSession(req, res, authOptions)
 
  const sin: string = session?.user?.name ? session.user.name.split('|')[0] : ''
  const userId: string = session?.user?.name
    ? session.user.name.split('|')[2]
    : ''
  const messages: MessageEntity[] = await getCachedContent(sin, userId)
 
  // Optional TODO: add a check to see if the letter belongs to the user. (Done with LetterService call)
 
  let message
  Iif (messages.length > 0) {
    message = messages.find((message) => message.messageId === messageId)
  }
  Iif (!message) {
    throw new Error('could not find message')
  }
 
  const pdfBytes = await getMessageService().getPdfByMessageId({
    letterId: messageId,
    userId: userId,
  })
 
  logger.trace('got back to downloads page')
 
  const decodedPdfBytes = Buffer.from(pdfBytes, 'base64')
 
  logger.trace('decoded pdf bytes: ' + decodedPdfBytes)
 
  res.setHeader('Content-Type', 'application/pdf')
  res.setHeader('Content-Length', decodedPdfBytes.length.toString())
  res.setHeader('Content-Disposition', `inline; filename="${messageId}.pdf"`)
 
  logger.trace('added headers')
 
  res.send(decodedPdfBytes)
}
 
const getCachedContent = (sin: string, userId: string) => {
  return cachified({
    key: `messages-entities-${sin}`,
    cache,
    getFreshValue: async (): Promise<MessageEntity[]> => {
      return await getMessageService().findMessagesBySin({
        sin: sin,
        userId: userId,
      })
    },
    ttl,
  })
}