saleor-app-sdk-REDIS_APL/src/index.ts

56 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-05-27 11:10:12 +00:00
import path from "path";
import fg from "fast-glob";
import { print } from "graphql/language/printer.js";
2022-05-24 20:16:49 +00:00
2022-05-27 11:10:12 +00:00
const capitalize = (value: string) =>
value.charAt(0).toUpperCase() + value.slice(1);
const dropFileExtension = (filename: string) => path.parse(filename).name;
2022-05-24 20:16:49 +00:00
export const inferWebhooks = async (baseURL: string, generatedGraphQL: any) => {
2022-05-27 11:10:12 +00:00
let entries;
if (process.env.NODE_ENV === "production") {
entries = await fg(["*.js"], { cwd: `${__dirname}/webhooks` });
} else {
entries = await fg(["*.ts"], { cwd: `pages/api/webhooks` });
}
2022-05-24 20:16:49 +00:00
return entries.map(dropFileExtension).map((name: string) => {
const camelcaseName = name.split("-").map(capitalize).join("");
const eventName = name.toUpperCase().replace(new RegExp("-", "g"), "_");
let eventType: string;
2022-05-27 11:10:12 +00:00
if (
Object.values(generatedGraphQL.WebhookEventTypeAsyncEnum).includes(
eventName
)
) {
eventType = "asyncEvents";
2022-05-27 11:10:12 +00:00
} 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`;
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,
[eventType]: [eventName],
query,
2022-05-24 20:16:49 +00:00
targetUrl: `${baseURL}/api/webhooks/${name}`,
};
});
2022-05-27 11:10:12 +00:00
};