// Runkit wrapper for express.js https://runkit.com/docs/endpoint
var express = require("@runkit/runkit/express-endpoint/1.0.0");
var responseTime = require('response-time');
const axios = require('axios');
var bodyParser = require('body-parser');
var got = require("got@11.8.2");
var app = express(exports);
app.use(responseTime());
app.use(bodyParser.json());
const rateLimitRecipes = true;
// Custom middleware function that overrides the route response for certain routes
function customResponseMiddleware(req, res, next) {
// Check if the request URL matches the specific route you want to override
if (req.url.startsWith('/recipe')) {
// Override the route's response with a custom response
return res.status(429).json({ message: 'Rate limit hit. Please try again later.' });
}
// If the route doesn't match, continue with the normal route handling
next();
}
if (rateLimitRecipes) {
// Register the custom middleware globally
app.use(customResponseMiddleware);
}
function pluralize(count, noun, suffix = 's') {
return `${count} ${noun}${count !== 1 ? suffix : ''}`;
}
app.post("/run-process", (req, res) => {
const { callbackUrl } = req.body;
var data = {
process_id: req.body.process_id,
status: 'running',
callbackUrl: callbackUrl
};
// Return HTTP 200 response immediately
console.log(`Sending 200 response with Callback URL: ${callbackUrl}`);
res.status(200).send(data);
// After 45 secs, send a POST request to callbackUrl
const delay = 45000; // in milliseconds
setTimeout(() => {
var ts = Date.now();
data.status = 'complete';
data.completed_at = ts;
console.log(`Setting up callback request with 'setTimeout' | Callback URL: ${callbackUrl}`);
axios.post(callbackUrl, data)
.then(response => {
console.log(`Callback successful: ${response.data}. Callback URL: ${callbackUrl}`);
})
.catch(error => {
console.error(`Callback failed: ${error}. Callback URL: ${callbackUrl}`);
});
}, delay);
});
app.post("/hello", (req, res) => {
var delay;
if (req.query.delay && !isNaN(req.query.delay)) {
delay = req.query.delay;
} else {
delay = 0;
}
console.log(`request-params: ${JSON.stringify(req.query)}`);
setTimeout((() => {
var data = {message: `Hello there! I waited ${pluralize(delay/1000, 'second')} to respond!`};
console.log(`response-body: ${JSON.stringify(data)}`);
res.send(data);
}), delay)
});
app.get("/action", (req, res) => {
var ts = Date.now();
var data;
var sendError = false;
if (sendError) {
data = {error: 'An error occurred!'};
res.status(401);
} else {
data = {id: ts};
}
res.send(data);
});
app.get("/recipe/:id", async (req, res) => {
var recipeURL = `https://auth-json-server.zapier-staging.com/recipes/${req.params.id}?api_key=secret`;
console.log(`Getting from: ${recipeURL}`);
try {
var data = await got(recipeURL).json();
res.send([data]);
} catch (error) {
console.log(error);
res.status(500);
res.send({ error: error.message });
}
});
app.get("/lead/:id", (req, res) => {
var data = [];
var now = new Date();
if (req.params.id == '1234567') {
var lead = {};
lead.id = req.params.id;
lead.ts = Math.floor(now / 1000);
lead.ts_friendly = now.toISOString();
data.push(lead);
res.send(data);
} else {
res.send(data);
}
});
app.get("/status/:code", (req, res) => {
res.status(req.params.code);
// var data = {status: req.params.code};
var data = {};
res.send(data);
});
app.post("/echo/:code", (req, res) => {
res.status(req.params.code);
const payload = req.body;
// Send the payload in the response
res.json({ payload });
});
app.get("/lead/:id/details", (req, res) => {
if (req.params.id == '1234567') {
var lead = {};
var now = new Date();
lead.id = req.params.id;
lead.ts = Math.floor(now / 1000);
lead.ts_friendly = now.toISOString();
lead.name = "John Smith";
lead.email = "john.smith@test.com";
lead.mobile = "+00 123 456 789";
res.send(lead);
} else {
res.send();
}
});
app.post("/auth", (req, res) => {
console.log(req.body);
if (req.body.username === 'test' && req.body.password === '1234567890') {
var data = {};
data.access_token = 'ABCDEF999XYZ';
data.authorized_accounts = ["Birdseed Test Zapier", "BirdSeed Sales Website"];
console.log(JSON.stringify(data));
res.send(data);
} else {
var error = {};
error.code = '401 - Unauthorized';
error.message = 'Username/password incorrect'
res.status(401);
res.send(error);
}
});
app.post("/escaped-unicode", (req, res) => {
var data = `{
"data": {
"createCard": null
},
"errors": [
{
"message": "Invalid input: what_s_the_amount_due ([\"Testy Tester \u003cesty.tester@testing.com\u003e\"])",
"locations": [
{
"line": 3,
"column": 5
}
],
"path": [
"createCard"
],
"code": 30000,
"type": "RuntimeError"
}
]
}`;
res.setHeader('content-type', 'application/json');
res.send(data);
});