Skip to content

Commit

Permalink
Refactor proxy response handling
Browse files Browse the repository at this point in the history
  • Loading branch information
betschki committed Aug 31, 2024
1 parent c964d07 commit 28c2ec4
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ const proxy = httpProxy.createProxyServer({
secure: false,
changeOrigin: true,
selfHandleResponse: true,
proxyTimeout: 5000,
});

proxy.on('proxyReq', function (proxyReq, req, res, options) {
Expand Down Expand Up @@ -145,8 +146,17 @@ proxy.on('proxyRes', async (proxyRes, req, res) => {
});

proxyRes.on('end', () => {
res.writeHead(proxyRes.statusCode || 500, proxyRes.headers);
res.end(body);
const responseBody = body.toString('utf-8');

if (proxyRes.statusCode && proxyRes.statusCode >= 400) {
console.error('Ghost error:', responseBody);
res.statusCode = proxyRes.statusCode; // Set the status code
res.setHeader('Content-Type', 'application/json'); // Ensure JSON response
res.end(JSON.stringify({ error: responseBody })); // Send the JSON error response
} else {
res.writeHead(proxyRes.statusCode || 500, proxyRes.headers);
res.end(body);
}

if (proxyRes.headers['x-cache-invalidate']) {
console.log('Detected x-cache-invalidate header, purging cache...');
Expand All @@ -155,6 +165,7 @@ proxy.on('proxyRes', async (proxyRes, req, res) => {
});
});


// Error handler replicates the error page from Ghost
proxy.on('error', (err, req, res) => {
console.error('Error during proxy operation:', err);
Expand Down

0 comments on commit 28c2ec4

Please sign in to comment.