All files / src/pages/api email-esrf.ts

85.71% Statements 18/21
75% Branches 6/8
100% Functions 2/2
85.71% Lines 18/21

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 73 74 75 76 77 78 79          1x           3x 1x 1x 1x     2x 1x     1x 1x     1x   1x 1x             1x       1x           1x                                     1x                     1x 1x    
import { NextApiRequest, NextApiResponse } from 'next'
 
import { EmailEsrfApiRequestBody } from '../../lib/types'
import { getLogger } from '../../logging/log-util'
 
const logger = getLogger('email-esrf')
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<string>,
) {
  if (req.method !== 'POST') {
    logger.debug(`Status 405: Invalid request method ${req.method}`)
    res.status(405).send(`Invalid request method ${req.method}`)
    return
  }
 
  if (req.headers['content-type'] !== 'application/json') {
    logger.debug(
      `Status 415: Invalid media type ${req.headers['content-type']}`,
    )
    res.status(415).send(`Invalid media type ${req.headers['content-type']}`)
    return
  }
 
  const body = req.body as EmailEsrfApiRequestBody
 
  try {
    await emailEsrfApi(res, body)
  } catch (error) {
    logger.error(error, 'Unhandled exception: Internal Server Error (500)')
    res.status(500).send('Something went wrong.')
  }
}
 
const emailEsrfApi = async (
  res: NextApiResponse<string>,
  emailEsrfApiRequestBody: EmailEsrfApiRequestBody,
) => {
  Iif (!process.env.PASSPORT_STATUS_API_BASE_URI) {
    throw Error(
      'process.env.PASSPORT_STATUS_API_BASE_URI must not be undefined, null or empty',
    )
  }
 
  const body = {
    Client: {
      BirthDate: {
        Date: emailEsrfApiRequestBody.dateOfBirth,
      },
      PersonContactInformation: {
        ContactEmailID: emailEsrfApiRequestBody.email,
      },
      PersonName: {
        PersonGivenName: [emailEsrfApiRequestBody.givenName],
        PersonSurName: emailEsrfApiRequestBody.surname,
      },
      PersonPreferredLanguage: {
        LanguageName:
          emailEsrfApiRequestBody.locale === 'fr' ? 'FRENCH' : 'ENGLISH',
      },
    },
  }
 
  const response = await fetch(
    `${process.env.PASSPORT_STATUS_API_BASE_URI}/api/v1/esrf-requests`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    },
  )
 
  logger.debug(`Status ${response.status}: ${response.statusText}`)
  res.status(response.status).send(response.statusText)
}