Refactor/booking logic (#183)

refs #175 

Reuses the same logic for creating bookings from the web app.

Co-authored-by: Leo Giovanetti <[email protected]>
This commit is contained in:
Omar LópezandLeo Giovanetti authored and GitHub committed 2022-10-13 12:29:30 -06:00
1 parent f13694fd13
commit 8c24c5c714
9 files changed
+88 -266

No files matched your search

-79
View File
@@ -1,79 +0,0 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Webhook } from "@prisma/client";
import { compile } from "handlebars";
// import type { CalendarEvent } from "@calcom/types/Calendar"; Add this to make it strict, change data: any to CalendarEvent type
type ContentType = "application/json" | "application/x-www-form-urlencoded";
function applyTemplate(template: string, data: any, contentType: ContentType) {
const compiled = compile(template)(data);
if (contentType === "application/json") {
return JSON.stringify(jsonParse(compiled));
}
return compiled;
}
function jsonParse(jsonString: string) {
try {
return JSON.parse(jsonString);
} catch (e) {
// don't do anything.
console.error(`error jsonParsing in sendPayload`);
}
return false;
}
const sendPayload = async (
triggerEvent: string,
createdAt: string,
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
data: any & {
metadata?: { [key: string]: string };
rescheduleUid?: string;
bookingId?: number;
}
) => {
const { subscriberUrl, appId, payloadTemplate: template } = webhook;
if (!subscriberUrl || !data) {
throw new Error("Missing required elements to send webhook payload.");
}
const contentType =
!template || jsonParse(template) ? "application/json" : "application/x-www-form-urlencoded";
data.description = data.description || data.additionalNotes;
let body;
/* Zapier id is hardcoded in the DB, we send the raw data for this case */
if (appId === "zapier") {
body = JSON.stringify(data);
} else if (template) {
body = applyTemplate(template, data, contentType);
} else {
body = JSON.stringify({
triggerEvent: triggerEvent,
createdAt: createdAt,
payload: data,
});
}
const response = await fetch(subscriberUrl, {
method: "POST",
headers: {
"Content-Type": contentType,
},
body,
});
const text = await response.text();
return {
ok: response.ok,
status: response.status,
message: text,
};
};
export default sendPayload;
-40
View File
@@ -1,40 +0,0 @@
import { WebhookTriggerEvents, PrismaClient } from "@prisma/client";
export type GetSubscriberOptions = {
userId: number;
eventTypeId: number;
triggerEvent: WebhookTriggerEvents;
};
const getWebhooks = async (options: GetSubscriberOptions, prisma: PrismaClient) => {
const { userId, eventTypeId } = options;
const allWebhooks = await prisma.webhook.findMany({
where: {
OR: [
{
userId,
},
{
eventTypeId,
},
],
AND: {
eventTriggers: {
has: options.triggerEvent,
},
active: {
equals: true,
},
},
},
select: {
subscriberUrl: true,
payloadTemplate: true,
appId: true,
},
});
return allWebhooks;
};
export default getWebhooks;