2022-05-24 20:16:49 +00:00
|
|
|
import path from 'path';
|
|
|
|
import fg from 'fast-glob';
|
2022-05-26 20:50:51 +00:00
|
|
|
|
|
|
|
import { print } from "graphql/language/printer.js";
|
2022-05-24 20:16:49 +00:00
|
|
|
|
|
|
|
export const capitalize = (value: string) => value.charAt(0).toUpperCase() + value.slice(1);
|
|
|
|
export const dropFileExtension = (filename: string) => path.parse(filename).name;
|
|
|
|
|
2022-05-26 20:41:21 +00:00
|
|
|
export const inferWebhooks = async (baseURL: string, generatedGraphQL: any) => {
|
|
|
|
const entries = await fg(["*.ts"], { cwd: "pages/api/webhooks" });
|
2022-05-24 20:16:49 +00:00
|
|
|
|
|
|
|
return entries.map(dropFileExtension).map((name: string) => {
|
2022-05-26 20:41:21 +00:00
|
|
|
const camelcaseName = name.split("-").map(capitalize).join("");
|
|
|
|
|
|
|
|
const eventName = name.toUpperCase().replace(new RegExp("-", "g"), "_");
|
|
|
|
let eventType: string;
|
|
|
|
if (Object.values(generatedGraphQL.WebhookEventTypeAsyncEnum).includes(eventName)) {
|
|
|
|
eventType = "asyncEvents";
|
|
|
|
} else if (Object.values(generatedGraphQL.WebhookEventTypeSyncEnum).includes(eventName)) {
|
|
|
|
eventType = "syncEvents";
|
|
|
|
} else {
|
|
|
|
throw Error("Event type not found.");
|
|
|
|
}
|
|
|
|
|
2022-05-24 20:16:49 +00:00
|
|
|
const statement = `${camelcaseName}SubscriptionDocument`;
|
2022-05-26 20:41:21 +00:00
|
|
|
let query: string;
|
|
|
|
if (statement in generatedGraphQL) {
|
|
|
|
query = print((generatedGraphQL as any)[statement]);
|
|
|
|
} else {
|
|
|
|
throw Error("Subscription not found.");
|
|
|
|
}
|
2022-05-24 20:16:49 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
name,
|
2022-05-26 20:41:21 +00:00
|
|
|
[eventType]: [eventName],
|
|
|
|
query,
|
2022-05-24 20:16:49 +00:00
|
|
|
targetUrl: `${baseURL}/api/webhooks/${name}`,
|
|
|
|
};
|
|
|
|
});
|
|
|
|
};
|