The road to zero TypeScript errors (#1756)

* Type fixes

* Type fixes

* Type fixes

* Type fixes

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
Omar López 2022-02-10 03:44:46 -07:00 committed by GitHub
parent 798930bf23
commit 5d0ba3dafc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 54 additions and 53 deletions

2
environment.d.ts vendored
View file

@ -14,7 +14,7 @@ declare namespace NodeJS {
readonly ZOOM_CLIENT_SECRET: string | undefined; readonly ZOOM_CLIENT_SECRET: string | undefined;
readonly EMAIL_FROM: string | undefined; readonly EMAIL_FROM: string | undefined;
readonly EMAIL_SERVER_HOST: string | undefined; readonly EMAIL_SERVER_HOST: string | undefined;
readonly EMAIL_SERVER_PORT: number | undefined; readonly EMAIL_SERVER_PORT: string | undefined;
readonly EMAIL_SERVER_USER: string | undefined; readonly EMAIL_SERVER_USER: string | undefined;
readonly EMAIL_SERVER_PASSWORD: string | undefined; readonly EMAIL_SERVER_PASSWORD: string | undefined;
readonly CRON_API_KEY: string | undefined; readonly CRON_API_KEY: string | undefined;

View file

@ -33,7 +33,7 @@ export const symmetricDecrypt = function (text: string, key: string) {
const _key = Buffer.from(key, "latin1"); const _key = Buffer.from(key, "latin1");
const components = text.split(":"); const components = text.split(":");
const iv_from_ciphertext = Buffer.from(components.shift(), OUTPUT_ENCODING); const iv_from_ciphertext = Buffer.from(components.shift() || "", OUTPUT_ENCODING);
const decipher = crypto.createDecipheriv(ALGORITHM, _key, iv_from_ciphertext); const decipher = crypto.createDecipheriv(ALGORITHM, _key, iv_from_ciphertext);
let deciphered = decipher.update(components.join(":"), OUTPUT_ENCODING, INPUT_ENCODING); let deciphered = decipher.update(components.join(":"), OUTPUT_ENCODING, INPUT_ENCODING);
deciphered += decipher.final(INPUT_ENCODING); deciphered += decipher.final(INPUT_ENCODING);

View file

@ -18,7 +18,7 @@ export interface EventResult {
success: boolean; success: boolean;
uid: string; uid: string;
createdEvent?: Event; createdEvent?: Event;
updatedEvent?: Event; updatedEvent?: Event | Event[];
originalEvent: CalendarEvent; originalEvent: CalendarEvent;
} }
@ -207,9 +207,10 @@ export default class EventManager {
// If and only if event type is a dedicated meeting, update the dedicated video meeting. // If and only if event type is a dedicated meeting, update the dedicated video meeting.
if (isDedicated) { if (isDedicated) {
const result = await this.updateVideoEvent(evt, booking); const result = await this.updateVideoEvent(evt, booking);
if (result.updatedEvent) { const [updatedEvent] = Array.isArray(result.updatedEvent) ? result.updatedEvent : [result.updatedEvent];
evt.videoCallData = result.updatedEvent; if (updatedEvent) {
evt.location = result.updatedEvent.url; evt.videoCallData = updatedEvent;
evt.location = updatedEvent.url;
} }
results.push(result); results.push(result);
} }

View file

@ -8,6 +8,7 @@ import { VideoCallData } from "@lib/videoClient";
import { NewCalendarEventType } from "../constants/types"; import { NewCalendarEventType } from "../constants/types";
import { ConferenceData } from "./GoogleCalendar"; import { ConferenceData } from "./GoogleCalendar";
import type { Event } from "@lib/events/EventManager";
export type Person = { export type Person = {
name: string; name: string;
@ -66,7 +67,7 @@ type EventBusyDate = Record<"start" | "end", Date | string>;
export interface Calendar { export interface Calendar {
createEvent(event: CalendarEvent): Promise<NewCalendarEventType>; createEvent(event: CalendarEvent): Promise<NewCalendarEventType>;
updateEvent(uid: string, event: CalendarEvent): Promise<unknown>; updateEvent(uid: string, event: CalendarEvent): Promise<Event | Event[]>;
deleteEvent(uid: string, event: CalendarEvent): Promise<unknown>; deleteEvent(uid: string, event: CalendarEvent): Promise<unknown>;

View file

@ -25,6 +25,7 @@ import { CALDAV_CALENDAR_TYPE } from "../constants/generals";
import { CalendarEventType, EventBusyDate, NewCalendarEventType } from "../constants/types"; import { CalendarEventType, EventBusyDate, NewCalendarEventType } from "../constants/types";
import { Calendar, CalendarEvent, IntegrationCalendar } from "../interfaces/Calendar"; import { Calendar, CalendarEvent, IntegrationCalendar } from "../interfaces/Calendar";
import { convertDate, getAttendees, getDuration } from "../utils/CalendarUtils"; import { convertDate, getAttendees, getDuration } from "../utils/CalendarUtils";
import type { Event } from "@lib/events/EventManager";
dayjs.extend(utc); dayjs.extend(utc);
dayjs.extend(timezone); dayjs.extend(timezone);
@ -121,7 +122,7 @@ export default abstract class BaseCalendarService implements Calendar {
} }
} }
async updateEvent(uid: string, event: CalendarEvent): Promise<unknown> { async updateEvent(uid: string, event: CalendarEvent) {
try { try {
const events = await this.getEventsByUID(uid); const events = await this.getEventsByUID(uid);
@ -141,7 +142,12 @@ export default abstract class BaseCalendarService implements Calendar {
if (error) { if (error) {
this.log.debug("Error creating iCalString"); this.log.debug("Error creating iCalString");
return {}; return {
type: event.type,
id: typeof event.uid === "string" ? event.uid : "-1",
password: "",
url: typeof event.location === "string" ? event.location : "-1",
};
} }
const eventsToUpdate = events.filter((e) => e.uid === uid); const eventsToUpdate = events.filter((e) => e.uid === uid);
@ -157,7 +163,7 @@ export default abstract class BaseCalendarService implements Calendar {
headers: this.headers, headers: this.headers,
}); });
}) })
); ).then((p) => p.map((r) => r.json() as unknown as Event));
} catch (reason) { } catch (reason) {
this.log.error(reason); this.log.error(reason);

View file

@ -23,22 +23,22 @@ export function parseZone(
date, date,
{ {
utc: true, utc: true,
...format, ...(typeof format === "string" ? { format } : { ...format }),
}, },
locale, locale,
strict strict
); );
} }
const [, dateTime, sign, tzHour, tzMinute] = match; const [, dateTime, sign, tzHour, tzMinute] = match;
const uOffset: number = tzHour * 60 + parseInt(tzMinute, 10); const uOffset: number = parseInt(tzHour) * 60 + parseInt(tzMinute, 10);
const offset = sign === "+" ? uOffset : -uOffset; const offset = sign === "+" ? uOffset : -uOffset;
return dayjs( return dayjs(
dateTime, dateTime,
{ {
$offset: offset, $offset: offset,
...format, ...(typeof format === "string" ? { format } : { ...format }),
} as dayjs.OptionType, } as dayjs.OptionType & { $offset: number },
locale, locale,
strict strict
); );

View file

@ -1,10 +1,13 @@
function detectTransport(): string | any { import SendmailTransport from "nodemailer/lib/sendmail-transport";
import SMTPConnection from "nodemailer/lib/smtp-connection";
function detectTransport(): SendmailTransport.Options | SMTPConnection.Options | string {
if (process.env.EMAIL_SERVER) { if (process.env.EMAIL_SERVER) {
return process.env.EMAIL_SERVER; return process.env.EMAIL_SERVER;
} }
if (process.env.EMAIL_SERVER_HOST) { if (process.env.EMAIL_SERVER_HOST) {
const port = parseInt(process.env.EMAIL_SERVER_PORT); const port = parseInt(process.env.EMAIL_SERVER_PORT!);
const transport = { const transport = {
host: process.env.EMAIL_SERVER_HOST, host: process.env.EMAIL_SERVER_HOST,
port, port,

View file

@ -1,31 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@lib/auth";
import prisma from "../../../lib/prisma";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const session = await getSession({ req: req });
if (!session) {
res.status(401).json({ message: "Not authenticated" });
return;
}
if (req.method == "PATCH") {
const startMins = req.body.start;
const endMins = req.body.end;
await prisma.schedule.update({
where: {
id: session.user.id,
},
data: {
startTime: startMins,
endTime: endMins,
},
});
res.status(200).json({ message: "Start and end times updated successfully" });
}
}

View file

@ -533,9 +533,14 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (results.length) { if (results.length) {
// TODO: Handle created event metadata more elegantly // TODO: Handle created event metadata more elegantly
metadata.hangoutLink = results[0].updatedEvent?.hangoutLink; const [updatedEvent] = Array.isArray(results[0].updatedEvent)
metadata.conferenceData = results[0].updatedEvent?.conferenceData; ? results[0].updatedEvent
metadata.entryPoints = results[0].updatedEvent?.entryPoints; : [results[0].updatedEvent];
if (updatedEvent) {
metadata.hangoutLink = updatedEvent.hangoutLink;
metadata.conferenceData = updatedEvent.conferenceData;
metadata.entryPoints = updatedEvent.entryPoints;
}
} }
await sendRescheduledEmails({ ...evt, additionInformation: metadata }); await sendRescheduledEmails({ ...evt, additionInformation: metadata });

View file

@ -5,6 +5,7 @@ import { getSession } from "@lib/auth";
import prisma from "@lib/prisma"; import prisma from "@lib/prisma";
import { resizeBase64Image } from "@server/lib/resizeBase64Image"; import { resizeBase64Image } from "@server/lib/resizeBase64Image";
import { PrismaClientKnownRequestError } from "@prisma/client/runtime";
export default async function handler(req: NextApiRequest, res: NextApiResponse) { export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const session = await getSession({ req: req }); const session = await getSession({ req: req });
@ -36,8 +37,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}, },
}); });
} catch (e) { } catch (e) {
if (e.code === "P2002") { if (e instanceof PrismaClientKnownRequestError) {
return res.status(409).json({ message: "Username already taken" }); if (e.code === "P2002") {
return res.status(409).json({ message: "Username already taken" });
}
} }
throw e; throw e;
} }

View file

@ -1,10 +1,11 @@
import { getSession } from "@lib/auth"; import { getSession } from "@lib/auth";
import { NextPageContext } from "next";
function RedirectPage() { function RedirectPage() {
return; return;
} }
export async function getServerSideProps(context) { export async function getServerSideProps(context: NextPageContext) {
const session = await getSession(context); const session = await getSession(context);
if (!session?.user?.id) { if (!session?.user?.id) {
return { redirect: { permanent: false, destination: "/auth/login" } }; return { redirect: { permanent: false, destination: "/auth/login" } };

View file

@ -6,6 +6,7 @@ import { WEBHOOK_TRIGGER_EVENTS } from "@lib/webhooks/constants";
import sendPayload from "@lib/webhooks/sendPayload"; import sendPayload from "@lib/webhooks/sendPayload";
import { createProtectedRouter } from "@server/createRouter"; import { createProtectedRouter } from "@server/createRouter";
import { getTranslation } from "@server/lib/i18n";
export const webhookRouter = createProtectedRouter() export const webhookRouter = createProtectedRouter()
.query("list", { .query("list", {
@ -94,6 +95,11 @@ export const webhookRouter = createProtectedRouter()
}), }),
async resolve({ input }) { async resolve({ input }) {
const { url, type, payloadTemplate } = input; const { url, type, payloadTemplate } = input;
const translation = await getTranslation("en", "common");
const language = {
locale: "en",
translate: translation,
};
const data = { const data = {
type: "Test", type: "Test",
@ -106,12 +112,14 @@ export const webhookRouter = createProtectedRouter()
email: "jdoe@example.com", email: "jdoe@example.com",
name: "John Doe", name: "John Doe",
timeZone: "Europe/London", timeZone: "Europe/London",
language,
}, },
], ],
organizer: { organizer: {
name: "Cal", name: "Cal",
email: "", email: "",
timeZone: "Europe/London", timeZone: "Europe/London",
language,
}, },
}; };

View file

@ -10,6 +10,8 @@ it("can find lucky users", async () => {
timeZone: "GMT", timeZone: "GMT",
bufferTime: 0, bufferTime: 0,
email: "test@example.com", email: "test@example.com",
destinationCalendar: null,
locale: "en",
}, },
{ {
id: 2, id: 2,
@ -19,6 +21,8 @@ it("can find lucky users", async () => {
timeZone: "GMT", timeZone: "GMT",
bufferTime: 0, bufferTime: 0,
email: "test2@example.com", email: "test2@example.com",
destinationCalendar: null,
locale: "en",
}, },
]; ];
expect( expect(