const moment = require('moment');
const { MongoClient } = require('mongodb');
const mongoConnectionString = process.env.SF_MONGO_CONNECTION_STRING;
const AutomationCloud = require('@automationcloud/client');
const auth = process.env.SF_SECRET_KEY;
exports.endpoint = async function(req, res) {
const url = new URL("https://example.com" + req.url);
const ibe = url.searchParams.get("ibe");
const count = url.searchParams.get('count') | 5;
const client = new MongoClient(mongoConnectionString, { useUnifiedTopology: true });
await client.connect();
const database = client.db('hotelier');
const hotels = database.collection('hotels');
const allHotels = await hotels.find({ ibe }).toArray();
const randomHotels = [];
if (allHotels.length === 0) {
return res.end('No hotels found');
}
for (let i = 0; i < count; i++) {
const randomIndex = Math.floor(Math.random() * allHotels.length);
const hotel = allHotels[randomIndex];
const client = new AutomationCloud.Client({
serviceId: hotel.serviceId,
auth: auth
});
const search = {
hotelId: hotel.hotelId,
checkIn: moment(new Date()).add(Math.random() * 30, 'days').format('YYYY-MM-DD'),
nights: Math.floor(Math.random() * 5) + 1,
guests: 2
};
const input = {
url: hotel.url,
searches: [search]
};
await client.createJob({ input });
}
const redirectUrl = `https://dashboard.automationcloud.net/jobs?serviceId=${allHotels[0].serviceId}&period=15m&category=test`;
res.end('<script>window.location = "' + redirectUrl + '";</script>');
};