import { fetch } from "https://esm.town/v/std/fetch";
import { resyPublicAPIKey } from "https://esm.town/v/vtdocs/resyPublicAPIKey";
export const resyGetMatchingSlot = async (
token: string,
venueId: number,
day: string,
start: string,
end: string,
partySize: number,
): Promise<{
"config": {
"id": number;
"type": string;
"token": string;
};
"date": {
"end": string;
"start": string;
};
}> => {
const startTime = new Date(`${day} ${start}`);
const endTime = new Date(`${day} ${end}`);
const slotsRes = await fetch(
`https://api.resy.com/4/find?lat=0&long=0&day=${day}&party_size=${partySize}&venue_id=${venueId}`,
{
"headers": {
"authorization":
`ResyAPI api_key="${resyPublicAPIKey}"`,
"x-resy-auth-token": token,
},
},
);
const slotsJSON = await slotsRes.json();
if (slotsJSON.results.venues[0].slots.length === 0) {
throw new Error(`no slots on ${day}`);
}
const availableSlots = slotsJSON.results.venues[0].slots;
const matchingSlots = availableSlots.filter((slot) => {
const time = new Date(slot.date.start);
return time >= startTime && time <= endTime;
});
if (matchingSlots.length === 0) {
throw new Error(
`there were some slots on ${day} but none between ${startTime.toISOString()}-${startTime.toISOString()}`,
);
}
const middleSlotIndex = Math.floor(matchingSlots.length / 2);
const slot = matchingSlots.at(middleSlotIndex);
return {
config: slot.config,
date: slot.date,
};
};