mirror of
https://github.com/Lissy93/web-check.git
synced 2024-11-26 18:23:21 +01:00
102 lines
3.0 KiB
JavaScript
102 lines
3.0 KiB
JavaScript
const express = require('express');
|
|
const awsServerlessExpress = require('aws-serverless-express');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const historyApiFallback = require('connect-history-api-fallback');
|
|
require('dotenv').config();
|
|
|
|
const app = express();
|
|
|
|
const API_DIR = '/api'; // Name of the dir containing the lambda functions
|
|
const dirPath = path.join(__dirname, API_DIR); // Path to the lambda functions dir
|
|
|
|
// Execute the lambda function
|
|
const executeHandler = async (handler, req) => {
|
|
return new Promise((resolve, reject) => {
|
|
const callback = (err, response) => err ? reject(err) : resolve(response);
|
|
const promise = handler(req, {}, callback);
|
|
|
|
if (promise && typeof promise.then === 'function') {
|
|
promise.then(resolve).catch(reject);
|
|
}
|
|
});
|
|
};
|
|
|
|
// Array of all the lambda function file names
|
|
const fileNames = fs.readdirSync(dirPath, { withFileTypes: true })
|
|
.filter(dirent => dirent.isFile() && dirent.name.endsWith('.js'))
|
|
.map(dirent => dirent.name);
|
|
|
|
const handlers = {};
|
|
|
|
fileNames.forEach(file => {
|
|
const routeName = file.split('.')[0];
|
|
const route = `${API_DIR}/${routeName}`;
|
|
const handler = require(path.join(dirPath, file)).handler;
|
|
|
|
handlers[route] = handler;
|
|
|
|
app.get(route, async (req, res) => {
|
|
try {
|
|
const { statusCode = 200, body = '' } = await executeHandler(handler, req);
|
|
res.status(statusCode).json(JSON.parse(body));
|
|
} catch (err) {
|
|
res.status(500).json({ error: err.message });
|
|
}
|
|
});
|
|
});
|
|
|
|
const timeout = (ms, jobName = null) => {
|
|
return new Promise((_, reject) => {
|
|
setTimeout(() => {
|
|
reject(new Error(`Timed out after the ${ms}ms limit${jobName ? `, when executing the ${jobName} task` : ''}`));
|
|
}, ms);
|
|
});
|
|
}
|
|
|
|
app.get('/api', async (req, res) => {
|
|
const results = {};
|
|
const { url } = req.query;
|
|
const maxExecutionTime = process.env.API_TIMEOUT_LIMIT || 10000;
|
|
|
|
const handlerPromises = Object.entries(handlers).map(async ([route, handler]) => {
|
|
const routeName = route.replace(`${API_DIR}/`, '');
|
|
|
|
try {
|
|
const result = await Promise.race([
|
|
executeHandler(handler, { query: { url } }),
|
|
timeout(maxExecutionTime, routeName)
|
|
]);
|
|
results[routeName] = JSON.parse((result || {}).body);
|
|
|
|
} catch (err) {
|
|
results[routeName] = { error: err.message };
|
|
}
|
|
});
|
|
|
|
await Promise.all(handlerPromises);
|
|
res.json(results);
|
|
});
|
|
|
|
// Handle SPA routing
|
|
app.use(historyApiFallback({
|
|
rewrites: [
|
|
{ from: /^\/api\/.*$/, to: function(context) { return context.parsedUrl.path; } },
|
|
]
|
|
}));
|
|
|
|
// Serve React App (static files from ./build)
|
|
app.use(express.static(path.join(__dirname, 'build')));
|
|
|
|
|
|
// Create serverless express server
|
|
const port = process.env.API_PORT || 3000;
|
|
const server = awsServerlessExpress.createServer(app).listen(port, () => {
|
|
console.log(`Server is running on port ${port}`);
|
|
});
|
|
|
|
exports.handler = (event, context) => {
|
|
// console.log(`EVENT: ${JSON.stringify(event)}`);
|
|
awsServerlessExpress.proxy(server, event, context);
|
|
};
|