Files
calendar/packages/trpc/server/routers/viewer/availability/schedule/create.handler.ts
T
1eeb91a793 perf: lazy load tRPC routes (#8167)
* experiment: cold start perf

* fix: update failing test

* chore: add database indexes

* chore: use json protocol and add query batching back

* Update [status].tsx

* Update [trpc].ts

* Delete getSlimSession.ts

* Update createContext.ts

* remove trpc caller

* correctly import Prisma

* lazy ethRouter

* replace crypto with md5

* import fixes

* public event endpoint refactor

* Update yarn.lock

* Update yarn.lock

* Using yarn.lock from main

---------

Co-authored-by: Omar López <zomars@me.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Efraín Rochín <roae.85@gmail.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2023-04-25 19:39:47 -03:00

74 lines
1.8 KiB
TypeScript

import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../../trpc";
import type { TCreateInputSchema } from "./create.schema";
type CreateOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TCreateInputSchema;
};
export const createHandler = async ({ input, ctx }: CreateOptions) => {
const { user } = ctx;
if (input.eventTypeId) {
const eventType = await prisma.eventType.findUnique({
where: {
id: input.eventTypeId,
},
select: {
userId: true,
},
});
if (!eventType || eventType.userId !== user.id) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to create a schedule for this event type",
});
}
}
const data: Prisma.ScheduleCreateInput = {
name: input.name,
user: {
connect: {
id: user.id,
},
},
// If an eventTypeId is provided then connect the new schedule to that event type
...(input.eventTypeId && { eventType: { connect: { id: input.eventTypeId } } }),
};
const availability = getAvailabilityFromSchedule(input.schedule || DEFAULT_SCHEDULE);
data.availability = {
createMany: {
data: availability.map((schedule) => ({
days: schedule.days,
startTime: schedule.startTime,
endTime: schedule.endTime,
})),
},
};
const schedule = await prisma.schedule.create({
data,
});
if (!user.defaultScheduleId) {
await prisma.user.update({
where: {
id: user.id,
},
data: {
defaultScheduleId: schedule.id,
},
});
}
return { schedule };
};