Stop relying on sendgrid client pkg

This commit is contained in:
Leo Giovanetti 2022-11-15 18:50:00 -03:00
parent f94aaf50fb
commit dd61851572
8 changed files with 48 additions and 24 deletions

View File

@ -8,7 +8,10 @@ const log = logger.getChildLogger({ prefix: ["CalendarManager"] });
export const getCalendar = (credential: CredentialPayload | null): Calendar | null => {
if (!credential || !credential.key) return null;
const { type: calendarType } = credential;
let { type: calendarType } = credential;
if (calendarType === "sendgrid_other_calendar") {
calendarType = "sendgrid";
}
const calendarApp = appStore[calendarType.split("_").join("") as keyof typeof appStore];
if (!(calendarApp && "lib" in calendarApp && "CalendarService" in calendarApp.lib)) {
log.warn(`calendar of type ${calendarType} is not implemented`);

View File

@ -28,8 +28,8 @@ function useAddAppMutation(_type: App["type"] | null, options?: Parameters<typeo
isOmniInstall = variables.isOmniInstall;
type = variables.type;
}
if (type?.endsWith("_other_calendar")) {
type = type.split("_other_calendar")[0];
if (type === "sendgrid_other_calendar") {
type = "sendgrid";
}
const state: IntegrationOAuthCallbackState = {
returnTo:

View File

@ -1,11 +1,8 @@
jest.mock("@calcom/lib/logger", () => ({
default: {
getChildLogger: () => ({
debug: jest.fn(),
error: jest.fn(),
log: jest.fn(),
}),
},
debug: jest.fn(),
error: jest.fn(),
log: jest.fn(),
getChildLogger: jest.fn(),
}));
jest.mock("@calcom/lib/crypto", () => ({

View File

@ -7,6 +7,14 @@ import {
} from "@calcom/lib/CloseComeUtils";
import type { CalendarEvent } from "@calcom/types/Calendar";
jest.mock("@calcom/lib/CloseCom", () => ({
default: class {
constructor() {
/* Mock */
}
},
}));
afterEach(() => {
jest.resetAllMocks();
});
@ -160,7 +168,7 @@ test("prepare data to create custom activity type instance: two attendees, no ad
const event = {
attendees,
startTime: now.toISOString(),
} as unknown as CalendarEvent;
} as CalendarEvent;
CloseCom.prototype.activity = {
type: {

View File

@ -7,8 +7,7 @@
"description": "SendGrid delivers your transactional and marketing emails through the world's largest cloud-based email delivery platform.",
"dependencies": {
"@calcom/lib": "*",
"@calcom/prisma": "*",
"@sendgrid/client": "^7.7.0"
"@calcom/prisma": "*"
},
"devDependencies": {
"@calcom/types": "*"

View File

@ -869,7 +869,8 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
results = createManager.results;
referencesToCreate = createManager.referencesToCreate;
if (results.length > 0 && results.every((res) => !res.success)) {
const nonAppResults = results.filter((res) => !res.appName);
if (nonAppResults.length > 0 && nonAppResults.every((res) => !res.success)) {
const error = {
errorCode: "BookingCreatingMeetingFailed",
message: "Booking failed",

View File

@ -1,5 +1,3 @@
import client from "@sendgrid/client";
import logger from "@calcom/lib/logger";
export type SendgridFieldOptions = [string, string][];
@ -48,11 +46,14 @@ const environmentApiKey = process.env.SENDGRID_SYNC_API_KEY || "";
*/
export default class Sendgrid {
private log: typeof logger;
private apiKey: string;
private apiUrl: string;
constructor(providedApiKey = "") {
this.log = logger.getChildLogger({ prefix: [`[[lib] sendgrid`] });
this.log = logger.getChildLogger({ prefix: [`[lib] sendgrid`] });
if (!providedApiKey && !environmentApiKey) throw Error("Sendgrid Api Key not present");
client.setApiKey(providedApiKey || environmentApiKey);
this.apiKey = providedApiKey || environmentApiKey;
this.apiUrl = "https://api.sendgrid.com";
}
public username = async () => {
@ -63,12 +64,28 @@ export default class Sendgrid {
return username;
};
public async sendgridRequest<R>(data: any): Promise<R> {
this.log.debug("sendgridRequest:request", data);
const results = await client.request(data);
public async sendgridRequest<R>(requestData: { url: string; method: string; body?: unknown }): Promise<R> {
this.log.debug("sendgridRequest:request", requestData);
const results = await fetch(`${this.apiUrl}${requestData.url}`, {
method: requestData.method,
headers: new Headers({
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}),
...(requestData.body ? { body: JSON.stringify(requestData.body) } : {}),
})
.then(async (res) => {
const jsonRes = await res.json();
if (jsonRes.errors) {
throw Error(`Sendgrid request error: ${jsonRes.errors[0]}`);
}
return jsonRes;
})
.catch((error) => {
throw Error(`Sendgrid request error: ${error}`);
});
this.log.debug("sendgridRequest:results", results);
if (results[1].errors) throw Error(`Sendgrid request error: ${results[1].errors}`);
return results[1];
return results;
}
public async getSendgridContactId(email: string) {

View File

@ -14,7 +14,6 @@
"@calcom/config": "*",
"@calcom/dayjs": "*",
"@prisma/client": "^4.2.1",
"@sendgrid/client": "^7.7.0",
"@vercel/og": "^0.0.19",
"bcryptjs": "^2.4.3",
"ical.js": "^1.4.0",