import { Router, Request, Response } from 'express'; import { requireAuth } from '../../auth-connector/source/server/auth'; import https from 'https'; const REMOTE_HOST = 'roject.rokojori.com'; const router = Router(); router.use( requireAuth ); router.all( '*', ( req: Request, res: Response ) => { const remotePath = '/api' + req.path; const qs = req.url.slice( req.path.length ); const token = ( req.headers.authorization as string ) ?? ''; let bodyBuffer: Buffer | undefined; if ( req.body !== undefined && ( req.method === 'POST' || req.method === 'PUT' ) ) { bodyBuffer = typeof req.body === 'string' ? Buffer.from( req.body, 'utf8' ) : Buffer.from( JSON.stringify( req.body ), 'utf8' ); } const reqHeaders: Record = { 'Authorization': token }; const ct = req.headers[ 'content-type' ]; if ( ct ) reqHeaders[ 'Content-Type' ] = ct; if ( bodyBuffer ) reqHeaders[ 'Content-Length' ] = bodyBuffer.length; const proxyReq = https.request( { hostname: REMOTE_HOST, path: remotePath + qs, method: req.method, headers: reqHeaders }, ( proxyRes ) => { res.status( proxyRes.statusCode ?? 200 ); const resCt = proxyRes.headers[ 'content-type' ]; if ( resCt ) res.setHeader( 'Content-Type', resCt ); proxyRes.pipe( res ); } ); proxyReq.on( 'error', ( err ) => { res.status( 502 ).json( { error: 'Remote server unreachable', detail: err.message } ); } ); if ( bodyBuffer ) proxyReq.write( bodyBuffer ); proxyReq.end(); } ); export default router;