import { Request , Response } from 'express' ; import { IncomingHttpHeaders } from 'http' ; import fetch , { Headers } from 'node-fetch' ; import getAccessTokenOnBehalfOf from './auth' ; param { string } incomingAuthHeader returns { Promise < string > } async function processIncomingToken ( incomingAuthHeader ) { if ( process . env . AUTH_PASS_THROUGH === 'true' ) { return incomingAuthHeader ; } const graphToken = await getAccessTokenOnBehalfOf ( incomingAuthHeader ) ; return graphToken || '' ; } param { IncomingHttpHeaders } incomingHeaders returns { Promise < Headers > } async function copyRequiredHeaders ( incomingHeaders ) { const graphHeaders = new Headers ( ) ; if ( incomingHeaders [ 'accept' ] ) { console . log ( `Accept: ${ incomingHeaders [ 'accept' ] }` ) ; graphHeaders . append ( 'accept' , incomingHeaders [ 'accept' ] ) ; } if ( incomingHeaders [ 'if-match' ] ) { console . log ( `If-Match: ${ incomingHeaders [ 'if-match' ] }` ) ; graphHeaders . append ( 'if-match' , incomingHeaders [ 'if-match' ] ) ; } if ( incomingHeaders [ 'content-type' ] ) { console . log ( `Content-Type: ${ incomingHeaders [ 'content-type' ] }` ) ; graphHeaders . append ( 'content-type' , incomingHeaders [ 'content-type' ] ) ; } if ( incomingHeaders [ 'authorization' ] ) { const graphAuthHeader = await processIncomingToken ( incomingHeaders [ 'authorization' ] ) ; graphHeaders . append ( 'authorization' , graphAuthHeader ) ; } return graphHeaders ; } param { Request } req param { Response } res returns { Promise < void > } export default async function proxyRequest ( req , res ) { console . log ( `${ req . method } ${ req . url }` ) ; const headers = await copyRequiredHeaders ( req . headers ) ; const graphUrl = `${ process . env . GRAPH_HOST }${ req . url }` ; const graphResponse = await fetch ( graphUrl , { method : req . method , headers : headers , body : req . method !== 'GET' ? JSON . stringify ( req . body ) : undefined } ) ; const responseType = graphResponse . headers . get ( 'content-type' ) ?? 'application/json' ; const bodyData = await graphResponse . buffer ( ) ; res . status ( graphResponse . status ) . type ( responseType ) . set ( { 'request-id' : graphResponse . headers . get ( 'request-id' ) , 'client-request-id' : graphResponse . headers . get ( 'client-request-id' ) } ) . send ( bodyData ) ; }