Merge pull request #47 from calcom/feat/api-ready-go
This commit is contained in:
39 files changed
+642
-673
No files matched your search
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
yarn pre-commit
|
||||
@@ -1 +0,0 @@
|
||||
module.exports = require("../../packages/config/prettier-preset");
|
||||
@@ -1,3 +0,0 @@
|
||||
module.exports = {
|
||||
presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-typescript"],
|
||||
};
|
||||
+22
-16
@@ -1,34 +1,40 @@
|
||||
import type { IncomingMessage } from "http";
|
||||
import { NextMiddleware } from "next-api-middleware";
|
||||
|
||||
import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
// Used to check if the API key is not expired, could be extracted if reused. but not for now.
|
||||
export const dateInPast = function (date: Date) {
|
||||
/** @todo figure how to use the one from `@calcom/types`fi */
|
||||
declare module "next" {
|
||||
export interface NextApiRequest extends IncomingMessage {
|
||||
userId: number;
|
||||
}
|
||||
}
|
||||
|
||||
// Used to check if the apiKey is not expired, could be extracted if reused. but not for now.
|
||||
export const dateNotInPast = function (date: Date) {
|
||||
const now = new Date();
|
||||
if (now.setHours(0, 0, 0, 0) <= date.setHours(0, 0, 0, 0)) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// This verifies the API key and sets the user if it is valid.
|
||||
// This verifies the apiKey and sets the user if it is valid.
|
||||
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
|
||||
if (!req.query.apiKey) res.status(401).json({ message: "No api key provided" });
|
||||
if (!req.query.apiKey) return res.status(401).json({ message: "No apiKey provided" });
|
||||
// We remove the prefix from the user provided api_key. If no env set default to "cal_"
|
||||
const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "cal_", "");
|
||||
// Hash the key again before matching against the database records.
|
||||
const hashedKey = hashAPIKey(strippedApiKey);
|
||||
// Check if the hashed api key exists in database.
|
||||
await prisma.apiKey.findUnique({ where: { hashedKey } }).then(async (apiKey) => {
|
||||
// If we cannot find any api key. Throw a 401 Unauthorized.
|
||||
if (!apiKey) res.status(401).json({ error: "Your api key is not valid" });
|
||||
if (apiKey && apiKey.expiresAt && dateInPast(apiKey.expiresAt) && apiKey.userId) {
|
||||
// Right now API Keys are user centric, we only allow resources related to this userId throughout the application.
|
||||
// if the api key is not expired, and the user id is present in the database.
|
||||
// Set the user in the request. as x-calcom-user-id.
|
||||
res.setHeader("X-Calcom-User-ID", apiKey.userId);
|
||||
// Pass the request to the next middleware.
|
||||
await next();
|
||||
}
|
||||
});
|
||||
const apiKey = await prisma.apiKey.findUnique({ where: { hashedKey } });
|
||||
// If we cannot find any api key. Throw a 401 Unauthorized.
|
||||
if (!apiKey) return res.status(401).json({ error: "Your apiKey is not valid" });
|
||||
if (apiKey.expiresAt && dateNotInPast(apiKey.expiresAt)) {
|
||||
return res.status(401).json({ error: "This apiKey is expired" });
|
||||
}
|
||||
if (!apiKey.userId) return res.status(404).json({ error: "No user found for this apiKey" });
|
||||
/* We save the user id in the request for later use */
|
||||
req.userId = apiKey.userId;
|
||||
await next();
|
||||
};
|
||||
@@ -37,6 +37,7 @@ export type UsersResponse = BaseResponse & {
|
||||
// Team
|
||||
export type TeamResponse = BaseResponse & {
|
||||
team?: Partial<Team>;
|
||||
owner?: Partial<Membership>;
|
||||
};
|
||||
export type TeamsResponse = BaseResponse & {
|
||||
teams?: Partial<Team>[];
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
import { NextApiResponse } from "next";
|
||||
|
||||
export const getCalcomUserId = (res: NextApiResponse): number => res.getHeader("x-calcom-user-id") as number;
|
||||
@@ -12,8 +12,8 @@ const schemaEventTypeRequiredParams = z.object({
|
||||
});
|
||||
|
||||
export const schemaEventTypeBodyParams = schemaEventTypeBaseBodyParams.merge(schemaEventTypeRequiredParams);
|
||||
|
||||
export const schemaEventTypePublic = EventType.omit({});
|
||||
// @NOTE: Removing locations and metadata properties before validation, add them later if required
|
||||
export const schemaEventTypePublic = EventType.omit({ locations: true, metadata: true });
|
||||
|
||||
export const withValidEventType = withValidation({
|
||||
schema: schemaEventTypeBodyParams,
|
||||
|
||||
+3
-10
@@ -14,24 +14,17 @@
|
||||
"lint-fix": "next lint --fix && prettier --write .",
|
||||
"test": "jest --detectOpenHandles",
|
||||
"type-check": "tsc --pretty --noEmit",
|
||||
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist",
|
||||
"prepare": "husky install",
|
||||
"pre-commit": "next lint"
|
||||
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.17.8",
|
||||
"@babel/preset-env": "^7.16.11",
|
||||
"@babel/preset-typescript": "^7.16.7",
|
||||
"@calcom/prisma": "*",
|
||||
"@calcom/tsconfig": "*",
|
||||
"@typescript-eslint/eslint-plugin": "^5.16.0",
|
||||
"babel-jest": "^27.5.1",
|
||||
"husky": "^7.0.4",
|
||||
"jest": "^27.5.1",
|
||||
"node-mocks-http": "^1.11.0",
|
||||
"prettier": "^2.6.1"
|
||||
"node-mocks-http": "^1.11.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@calcom/prisma": "*",
|
||||
"@sentry/nextjs": "^6.19.3",
|
||||
"next": "^12.1.4",
|
||||
"next-api-middleware": "^1.0.1",
|
||||
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import type { AttendeeResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import { schemaAttendeeBodyParams, schemaAttendeePublic } from "@lib/validations/attendee";
|
||||
import {
|
||||
schemaQueryIdParseInt,
|
||||
@@ -93,7 +92,7 @@ export async function attendeeById(req: NextApiRequest, res: NextApiResponse<Att
|
||||
if (!safeQuery.success) {
|
||||
throw new Error("Invalid request query", safeQuery.error);
|
||||
}
|
||||
const userId = getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
const userBookings = await prisma.booking.findMany({
|
||||
where: { userId },
|
||||
include: { attendees: true },
|
||||
@@ -101,7 +100,8 @@ export async function attendeeById(req: NextApiRequest, res: NextApiResponse<Att
|
||||
const attendees = userBookings.map((booking) => booking.attendees).flat();
|
||||
const attendeeIds = attendees.map((attendee) => attendee.id);
|
||||
// Here we make sure to only return attendee's of the user's own bookings.
|
||||
if (attendeeIds.includes(safeQuery.data.id)) {
|
||||
if (!attendeeIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.attendee
|
||||
@@ -152,7 +152,7 @@ export async function attendeeById(req: NextApiRequest, res: NextApiResponse<Att
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
} else res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
}
|
||||
|
||||
export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(attendeeById));
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import { AttendeeResponse, AttendeesResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import { schemaAttendeeBodyParams, schemaAttendeePublic, withValidAttendee } from "@lib/validations/attendee";
|
||||
|
||||
/**
|
||||
@@ -43,7 +42,7 @@ async function createOrlistAllAttendees(
|
||||
res: NextApiResponse<AttendeesResponse | AttendeeResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
// Here we make sure to only return attendee's of the user's own bookings.
|
||||
const userBookings = await prisma.booking.findMany({
|
||||
where: {
|
||||
@@ -68,7 +67,7 @@ async function createOrlistAllAttendees(
|
||||
throw new Error("Invalid request body", safe.error);
|
||||
}
|
||||
const bookingId = safe.data.bookingId;
|
||||
const userId = await getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
const userWithBookings = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: { bookings: true },
|
||||
@@ -77,7 +76,8 @@ async function createOrlistAllAttendees(
|
||||
throw new Error("User not found");
|
||||
}
|
||||
const userBookingIds = userWithBookings.bookings.map((booking: any) => booking.id).flat();
|
||||
if (userBookingIds.includes(bookingId)) {
|
||||
if (!userBookingIds.includes(bookingId)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
delete safe.data.bookingId;
|
||||
const noBookingId = safe.data;
|
||||
const data = await prisma.attendee.create({
|
||||
@@ -100,7 +100,7 @@ async function createOrlistAllAttendees(
|
||||
error,
|
||||
});
|
||||
}
|
||||
} else res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
} else res.status(405).json({ message: `Method ${method} not allowed` });
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import type { AvailabilityResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import { schemaAvailabilityBodyParams, schemaAvailabilityPublic } from "@lib/validations/availability";
|
||||
import {
|
||||
schemaQueryIdParseInt,
|
||||
@@ -27,6 +26,8 @@ import {
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - availabilities
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/availability
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
@@ -56,6 +57,8 @@ import {
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - availabilities
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/availability
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, availability edited successfuly
|
||||
@@ -77,6 +80,8 @@ import {
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - availabilities
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/availability
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, availability removed successfuly
|
||||
@@ -91,10 +96,11 @@ export async function availabilityById(req: NextApiRequest, res: NextApiResponse
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaAvailabilityBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
const userId = await getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
const data = await prisma.availability.findMany({ where: { userId } });
|
||||
const availabiltiesIds = data.map((availability) => availability.id);
|
||||
if (availabiltiesIds.includes(safeQuery.data.id)) {
|
||||
if (!availabiltiesIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.availability
|
||||
@@ -137,8 +143,6 @@ export async function availabilityById(req: NextApiRequest, res: NextApiResponse
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import { AvailabilityResponse, AvailabilitiesResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import { schemaAvailabilityBodyParams, schemaAvailabilityPublic } from "@lib/validations/availability";
|
||||
|
||||
/**
|
||||
@@ -16,6 +15,8 @@ import { schemaAvailabilityBodyParams, schemaAvailabilityPublic } from "@lib/val
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - availabilities
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/availability
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
@@ -29,6 +30,8 @@ import { schemaAvailabilityBodyParams, schemaAvailabilityPublic } from "@lib/val
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - availabilities
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/availability
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, availability created
|
||||
@@ -43,7 +46,7 @@ async function createOrlistAllAvailabilities(
|
||||
res: NextApiResponse<AvailabilitiesResponse | AvailabilityResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = await getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
|
||||
if (method === "GET") {
|
||||
const data = await prisma.availability.findMany({ where: { userId } });
|
||||
|
||||
@@ -5,7 +5,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import type { BookingReferenceResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import {
|
||||
schemaBookingReferenceBodyParams,
|
||||
schemaBookingReferencePublic,
|
||||
@@ -98,7 +97,7 @@ export async function bookingReferenceById(
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaBookingReferenceBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
const userId = await getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
const userWithBookings = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: { bookings: true },
|
||||
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import { BookingReferenceResponse, BookingReferencesResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import {
|
||||
schemaBookingReferenceBodyParams,
|
||||
schemaBookingReferencePublic,
|
||||
@@ -46,7 +45,7 @@ async function createOrlistAllBookingReferences(
|
||||
res: NextApiResponse<BookingReferencesResponse | BookingReferenceResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = await getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
const userWithBookings = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: { bookings: true },
|
||||
@@ -72,7 +71,7 @@ async function createOrlistAllBookingReferences(
|
||||
}
|
||||
|
||||
// const booking_reference = schemaBookingReferencePublic.parse(data);
|
||||
const userId = await getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
const userWithBookings = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: { bookings: true },
|
||||
@@ -81,7 +80,8 @@ async function createOrlistAllBookingReferences(
|
||||
throw new Error("User not found");
|
||||
}
|
||||
const userBookingIds = userWithBookings.bookings.map((booking: any) => booking.id).flat();
|
||||
if (userBookingIds.includes(safe.data.bookingId)) {
|
||||
if (!userBookingIds.includes(safe.data.bookingId)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
const booking_reference = await prisma.bookingReference.create({
|
||||
data: { ...safe.data },
|
||||
});
|
||||
@@ -97,7 +97,7 @@ async function createOrlistAllBookingReferences(
|
||||
error,
|
||||
});
|
||||
}
|
||||
} else res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
} else res.status(405).json({ message: `Method ${method} not allowed` });
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import type { BookingResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import { schemaBookingBodyParams, schemaBookingPublic } from "@lib/validations/booking";
|
||||
import {
|
||||
schemaQueryIdParseInt,
|
||||
@@ -91,14 +90,15 @@ export async function bookingById(req: NextApiRequest, res: NextApiResponse<Book
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaBookingBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
const userId = await getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
const userWithBookings = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: { bookings: true },
|
||||
});
|
||||
if (!userWithBookings) throw new Error("User not found");
|
||||
const userBookingIds = userWithBookings.bookings.map((booking: any) => booking.id).flat();
|
||||
if (userBookingIds.includes(safeQuery.data.id)) {
|
||||
if (!userBookingIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.booking
|
||||
@@ -152,7 +152,7 @@ export async function bookingById(req: NextApiRequest, res: NextApiResponse<Book
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
} else res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
}
|
||||
|
||||
export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(bookingById));
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import { BookingResponse, BookingsResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import { schemaBookingBodyParams, schemaBookingPublic, withValidBooking } from "@lib/validations/booking";
|
||||
|
||||
/**
|
||||
@@ -43,7 +42,7 @@ async function createOrlistAllBookings(
|
||||
res: NextApiResponse<BookingsResponse | BookingResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = await getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
|
||||
if (method === "GET") {
|
||||
const data = await prisma.booking.findMany({ where: { userId } });
|
||||
|
||||
@@ -96,52 +96,70 @@ export async function dailyEventReferenceById(
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaDailyEventReferenceBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
const userId = req.userId;
|
||||
const userBookings = await prisma.booking.findMany({ where: { userId } });
|
||||
const userBookingIds = userBookings.map((booking) => booking.id);
|
||||
const userBookingDailyEventReferences = await prisma.dailyEventReference.findMany({
|
||||
where: { bookingId: { in: userBookingIds } },
|
||||
});
|
||||
const userBookingDailyEventReferenceIds = userBookingDailyEventReferences.map(
|
||||
(dailyEventReference) => dailyEventReference.id
|
||||
);
|
||||
if (!userBookingDailyEventReferenceIds.includes(safeQuery.data.id))
|
||||
res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.dailyEventReference
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaDailyEventReferencePublic.parse(data))
|
||||
.then((daily_event_reference) => res.status(200).json({ daily_event_reference }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `DailyEventReference with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.dailyEventReference
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaDailyEventReferencePublic.parse(data))
|
||||
.then((daily_event_reference) => res.status(200).json({ daily_event_reference }))
|
||||
.catch((error: Error) =>
|
||||
res
|
||||
.status(404)
|
||||
.json({ message: `DailyEventReference with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "PATCH":
|
||||
if (!safeBody.success) {
|
||||
throw new Error("Invalid request body");
|
||||
}
|
||||
await prisma.dailyEventReference
|
||||
.update({ where: { id: safeQuery.data.id }, data: safeBody.data })
|
||||
.then((data) => schemaDailyEventReferencePublic.parse(data))
|
||||
.then((daily_event_reference) => res.status(200).json({ daily_event_reference }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `DailyEventReference with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "PATCH":
|
||||
if (!safeBody.success) throw new Error("Invalid request body");
|
||||
await prisma.dailyEventReference
|
||||
.update({
|
||||
where: { id: safeQuery.data.id },
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((data) => schemaDailyEventReferencePublic.parse(data))
|
||||
.then((daily_event_reference) => res.status(200).json({ daily_event_reference }))
|
||||
.catch((error: Error) =>
|
||||
res
|
||||
.status(404)
|
||||
.json({ message: `DailyEventReference with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "DELETE":
|
||||
await prisma.dailyEventReference
|
||||
.delete({
|
||||
where: { id: safeQuery.data.id },
|
||||
})
|
||||
.then(() =>
|
||||
res.status(200).json({
|
||||
message: `DailyEventReference with id: ${safeQuery.data.id} deleted`,
|
||||
})
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `DailyEventReference with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "DELETE":
|
||||
await prisma.dailyEventReference
|
||||
.delete({ where: { id: safeQuery.data.id } })
|
||||
.then(() =>
|
||||
res.status(200).json({ message: `DailyEventReference with id: ${safeQuery.data.id} deleted` })
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res
|
||||
.status(404)
|
||||
.json({ message: `DailyEventReference with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
* security:
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - daily-event-reference
|
||||
* - daily-event-references
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
* security:
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - daily-event-reference
|
||||
* - daily-event-references
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, daily event reference created
|
||||
@@ -45,8 +45,14 @@ async function createOrlistAllDailyEventReferences(
|
||||
res: NextApiResponse<DailyEventReferencesResponse | DailyEventReferenceResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = req.userId;
|
||||
const userBookings = await prisma.booking.findMany({ where: { userId } });
|
||||
const userBookingIds = userBookings.map((booking) => booking.id);
|
||||
|
||||
if (method === "GET") {
|
||||
const data = await prisma.dailyEventReference.findMany();
|
||||
const data = await prisma.dailyEventReference.findMany({
|
||||
where: { bookingId: { in: userBookingIds } },
|
||||
});
|
||||
const daily_event_references = data.map((dailyEventReference) =>
|
||||
schemaDailyEventReferencePublic.parse(dailyEventReference)
|
||||
);
|
||||
|
||||
@@ -96,52 +96,65 @@ export async function destionationCalendarById(
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaDestinationCalendarBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
const userId = req.userId;
|
||||
const data = await prisma.destinationCalendar.findMany({ where: { userId } });
|
||||
const userDestinationCalendars = data.map((destinationCalendar) => destinationCalendar.id);
|
||||
// FIXME: Should we also check ownership of bokingId and eventTypeId to avoid users cross-pollinating other users calendars.
|
||||
// On a related note, moving from sequential integer IDs to UUIDs would be a good idea. and maybe help avoid having this problem.
|
||||
if (userDestinationCalendars.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.destinationCalendar
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaDestinationCalendarPublic.parse(data))
|
||||
.then((destination_calendar) => res.status(200).json({ destination_calendar }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `DestinationCalendar with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.destinationCalendar
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaDestinationCalendarPublic.parse(data))
|
||||
.then((destination_calendar) => res.status(200).json({ destination_calendar }))
|
||||
.catch((error: Error) =>
|
||||
res
|
||||
.status(404)
|
||||
.json({ message: `DestinationCalendar with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "PATCH":
|
||||
if (!safeBody.success) {
|
||||
throw new Error("Invalid request body");
|
||||
}
|
||||
await prisma.destinationCalendar
|
||||
.update({ where: { id: safeQuery.data.id }, data: safeBody.data })
|
||||
.then((data) => schemaDestinationCalendarPublic.parse(data))
|
||||
.then((destination_calendar) => res.status(200).json({ destination_calendar }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `DestinationCalendar with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "PATCH":
|
||||
if (!safeBody.success) throw new Error("Invalid request body");
|
||||
await prisma.destinationCalendar
|
||||
.update({
|
||||
where: { id: safeQuery.data.id },
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((data) => schemaDestinationCalendarPublic.parse(data))
|
||||
.then((destination_calendar) => res.status(200).json({ destination_calendar }))
|
||||
.catch((error: Error) =>
|
||||
res
|
||||
.status(404)
|
||||
.json({ message: `DestinationCalendar with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "DELETE":
|
||||
await prisma.destinationCalendar
|
||||
.delete({
|
||||
where: { id: safeQuery.data.id },
|
||||
})
|
||||
.then(() =>
|
||||
res.status(200).json({
|
||||
message: `DestinationCalendar with id: ${safeQuery.data.id} deleted`,
|
||||
})
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `DestinationCalendar with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "DELETE":
|
||||
await prisma.destinationCalendar
|
||||
.delete({ where: { id: safeQuery.data.id } })
|
||||
.then(() =>
|
||||
res.status(200).json({ message: `DestinationCalendar with id: ${safeQuery.data.id} deleted` })
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res
|
||||
.status(404)
|
||||
.json({ message: `DestinationCalendar with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,8 +45,10 @@ async function createOrlistAllDestinationCalendars(
|
||||
res: NextApiResponse<DestinationCalendarsResponse | DestinationCalendarResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = req.userId;
|
||||
|
||||
if (method === "GET") {
|
||||
const data = await prisma.destinationCalendar.findMany();
|
||||
const data = await prisma.destinationCalendar.findMany({ where: { userId } });
|
||||
const destination_calendars = data.map((destinationCalendar) =>
|
||||
schemaDestinationCalendarPublic.parse(destinationCalendar)
|
||||
);
|
||||
@@ -61,7 +63,7 @@ async function createOrlistAllDestinationCalendars(
|
||||
const safe = schemaDestinationCalendarBodyParams.safeParse(req.body);
|
||||
if (!safe.success) throw new Error("Invalid request body");
|
||||
|
||||
const data = await prisma.destinationCalendar.create({ data: safe.data });
|
||||
const data = await prisma.destinationCalendar.create({ data: { ...safe.data, userId } });
|
||||
const destination_calendar = schemaDestinationCalendarPublic.parse(data);
|
||||
|
||||
if (destination_calendar)
|
||||
|
||||
@@ -93,46 +93,70 @@ async function eventTypeById(req: NextApiRequest, res: NextApiResponse<EventType
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaEventTypeCustomInputBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
const userId = req.userId;
|
||||
const data = await prisma.eventType.findMany({ where: { userId } });
|
||||
const userEventTypes = data.map((eventType) => eventType.id);
|
||||
const userEventTypeCustomInputs = await prisma.eventTypeCustomInput.findMany({
|
||||
where: { eventType: userEventTypes },
|
||||
});
|
||||
const userEventTypeCustomInputIds = userEventTypeCustomInputs.map(
|
||||
(eventTypeCustomInput) => eventTypeCustomInput.id
|
||||
);
|
||||
if (!userEventTypeCustomInputIds.includes(safeQuery.data.id))
|
||||
res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.eventTypeCustomInput
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaEventTypeCustomInputPublic.parse(data))
|
||||
.then((event_type_custom_input) => res.status(200).json({ event_type_custom_input }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `EventType with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.eventTypeCustomInput
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaEventTypeCustomInputPublic.parse(data))
|
||||
.then((event_type_custom_input) => res.status(200).json({ event_type_custom_input }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "PATCH":
|
||||
if (!safeBody.success) {
|
||||
throw new Error("Invalid request body");
|
||||
}
|
||||
await prisma.eventTypeCustomInput
|
||||
.update({ where: { id: safeQuery.data.id }, data: safeBody.data })
|
||||
.then((data) => schemaEventTypeCustomInputPublic.parse(data))
|
||||
.then((event_type_custom_input) => res.status(200).json({ event_type_custom_input }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `EventType with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "PATCH":
|
||||
if (!safeBody.success) throw new Error("Invalid request body");
|
||||
await prisma.eventTypeCustomInput
|
||||
.update({
|
||||
where: { id: safeQuery.data.id },
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((data) => schemaEventTypeCustomInputPublic.parse(data))
|
||||
.then((event_type_custom_input) => res.status(200).json({ event_type_custom_input }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "DELETE":
|
||||
await prisma.eventTypeCustomInput
|
||||
.delete({
|
||||
where: { id: safeQuery.data.id },
|
||||
})
|
||||
.then(() =>
|
||||
res.status(200).json({
|
||||
message: `CustomInputEventType with id: ${safeQuery.data.id} deleted`,
|
||||
})
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `EventType with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "DELETE":
|
||||
await prisma.eventTypeCustomInput
|
||||
.delete({ where: { id: safeQuery.data.id } })
|
||||
.then(() =>
|
||||
res.status(200).json({ message: `CustomInputEventType with id: ${safeQuery.data.id} deleted` })
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,8 +45,12 @@ async function createOrlistAllEventTypeCustomInputs(
|
||||
res: NextApiResponse<EventTypeCustomInputsResponse | EventTypeCustomInputResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = req.userId;
|
||||
const data = await prisma.eventType.findMany({ where: { userId } });
|
||||
const userEventTypes = data.map((eventType) => eventType.id);
|
||||
|
||||
if (method === "GET") {
|
||||
const data = await prisma.eventTypeCustomInput.findMany();
|
||||
const data = await prisma.eventTypeCustomInput.findMany({ where: { eventType: userEventTypes } });
|
||||
const event_type_custom_inputs = data.map((eventTypeCustomInput) =>
|
||||
schemaEventTypeCustomInputPublic.parse(eventTypeCustomInput)
|
||||
);
|
||||
@@ -60,13 +64,25 @@ async function createOrlistAllEventTypeCustomInputs(
|
||||
} else if (method === "POST") {
|
||||
const safe = schemaEventTypeCustomInputBodyParams.safeParse(req.body);
|
||||
if (!safe.success) throw new Error("Invalid request body");
|
||||
|
||||
const data = await prisma.eventTypeCustomInput.create({ data: safe.data });
|
||||
const event_type_custom_input = schemaEventTypeCustomInputPublic.parse(data);
|
||||
|
||||
if (event_type_custom_input)
|
||||
res.status(201).json({ event_type_custom_input, message: "EventTypeCustomInput created successfully" });
|
||||
else
|
||||
// Since we're supporting a create or connect relation on eventType, we need to treat them differently
|
||||
// When using connect on event type, check if userId is the owner of the event
|
||||
if (safe.data.eventType.connect && !userEventTypes.includes(safe.data.eventType.connect.id as number)) {
|
||||
const data = await prisma.eventTypeCustomInput.create({ data: { ...safe.data } });
|
||||
const event_type_custom_input = schemaEventTypeCustomInputPublic.parse(data);
|
||||
if (event_type_custom_input)
|
||||
res
|
||||
.status(201)
|
||||
.json({ event_type_custom_input, message: "EventTypeCustomInput created successfully" });
|
||||
// When creating, no need
|
||||
// FIXME: we might want to pass userId to the new created/linked eventType, though.
|
||||
} else if (safe.data.eventType.create) {
|
||||
const data = await prisma.eventTypeCustomInput.create({ data: { ...safe.data } });
|
||||
const event_type_custom_input = schemaEventTypeCustomInputPublic.parse(data);
|
||||
if (event_type_custom_input)
|
||||
res
|
||||
.status(201)
|
||||
.json({ event_type_custom_input, message: "EventTypeCustomInput created successfully" });
|
||||
} else
|
||||
(error: Error) =>
|
||||
res.status(400).json({
|
||||
message: "Could not create new eventTypeCustomInput",
|
||||
|
||||
@@ -26,6 +26,8 @@ import {
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/event-types
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
@@ -55,6 +57,8 @@ import {
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/event-types
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, eventType edited successfuly
|
||||
@@ -76,6 +80,8 @@ import {
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/event-types
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, eventType removed successfuly
|
||||
@@ -90,44 +96,61 @@ export async function eventTypeById(req: NextApiRequest, res: NextApiResponse<Ev
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaEventTypeBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
const userId = req.userId;
|
||||
const data = await prisma.eventType.findMany({ where: { userId } });
|
||||
const userEventTypes = data.map((eventType) => eventType.id);
|
||||
if (!userEventTypes.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.eventType
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaEventTypePublic.parse(data))
|
||||
.then((event_type) => res.status(200).json({ event_type }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `EventType with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.eventType
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaEventTypePublic.parse(data))
|
||||
.then((event_type) => res.status(200).json({ event_type }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "PATCH":
|
||||
if (!safeBody.success) {
|
||||
throw new Error("Invalid request body");
|
||||
}
|
||||
await prisma.eventType
|
||||
.update({ where: { id: safeQuery.data.id }, data: safeBody.data })
|
||||
.then((data) => schemaEventTypePublic.parse(data))
|
||||
.then((event_type) => res.status(200).json({ event_type }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `EventType with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "PATCH":
|
||||
if (!safeBody.success) throw new Error("Invalid request body");
|
||||
await prisma.eventType
|
||||
.update({
|
||||
where: { id: safeQuery.data.id },
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((data) => schemaEventTypePublic.parse(data))
|
||||
.then((event_type) => res.status(200).json({ event_type }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "DELETE":
|
||||
await prisma.eventType
|
||||
.delete({ where: { id: safeQuery.data.id } })
|
||||
.then(() =>
|
||||
res.status(200).json({
|
||||
message: `EventType with id: ${safeQuery.data.id} deleted`,
|
||||
})
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `EventType with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "DELETE":
|
||||
await prisma.eventType
|
||||
.delete({ where: { id: safeQuery.data.id } })
|
||||
.then(() => res.status(200).json({ message: `EventType with id: ${safeQuery.data.id} deleted` }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ import { schemaEventTypeBodyParams, schemaEventTypePublic } from "@lib/validatio
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/event-types
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
@@ -28,6 +30,8 @@ import { schemaEventTypeBodyParams, schemaEventTypePublic } from "@lib/validatio
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - event-types
|
||||
* externalDocs:
|
||||
* url: https://docs.cal.com/event-types
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, event type created
|
||||
@@ -42,8 +46,10 @@ async function createOrlistAllEventTypes(
|
||||
res: NextApiResponse<EventTypesResponse | EventTypeResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = req.userId;
|
||||
|
||||
if (method === "GET") {
|
||||
const data = await prisma.eventType.findMany();
|
||||
const data = await prisma.eventType.findMany({ where: { userId } });
|
||||
const event_types = data.map((eventType) => schemaEventTypePublic.parse(eventType));
|
||||
if (event_types) res.status(200).json({ event_types });
|
||||
else
|
||||
@@ -56,7 +62,7 @@ async function createOrlistAllEventTypes(
|
||||
const safe = schemaEventTypeBodyParams.safeParse(req.body);
|
||||
if (!safe.success) throw new Error("Invalid request body");
|
||||
|
||||
const data = await prisma.eventType.create({ data: safe.data });
|
||||
const data = await prisma.eventType.create({ data: { ...safe.data, userId } });
|
||||
const event_type = schemaEventTypePublic.parse(data);
|
||||
|
||||
if (data) res.status(201).json({ event_type, message: "EventType created successfully" });
|
||||
|
||||
@@ -106,47 +106,82 @@ export async function membershipById(req: NextApiRequest, res: NextApiResponse<M
|
||||
const safeBody = schemaMembershipBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
// This is how we set the userId and teamId in the query for managing compoundId.
|
||||
const [userId, teamId] = safeQuery.data.id.split("_");
|
||||
const [paramUserId, teamId] = safeQuery.data.id.split("_");
|
||||
const userId = req.userId;
|
||||
if (parseInt(paramUserId) !== userId) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.membership
|
||||
.findUnique({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: userId,
|
||||
teamId: parseInt(teamId),
|
||||
},
|
||||
},
|
||||
})
|
||||
.then((data) => schemaMembershipPublic.parse(data))
|
||||
.then((membership) => res.status(200).json({ membership }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `Membership with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.membership
|
||||
.findUnique({ where: { userId_teamId: { userId: parseInt(userId), teamId: parseInt(teamId) } } })
|
||||
.then((data) => schemaMembershipPublic.parse(data))
|
||||
.then((membership) => res.status(200).json({ membership }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `Membership with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "PATCH":
|
||||
if (!safeBody.success) {
|
||||
throw new Error("Invalid request body");
|
||||
}
|
||||
await prisma.membership
|
||||
.update({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: userId,
|
||||
teamId: parseInt(teamId),
|
||||
},
|
||||
},
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((data) => schemaMembershipPublic.parse(data))
|
||||
.then((membership) => res.status(200).json({ membership }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `Membership with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "PATCH":
|
||||
if (!safeBody.success) throw new Error("Invalid request body");
|
||||
await prisma.membership
|
||||
.update({
|
||||
where: { userId_teamId: { userId: parseInt(userId), teamId: parseInt(teamId) } },
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((data) => schemaMembershipPublic.parse(data))
|
||||
.then((membership) => res.status(200).json({ membership }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `Membership with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "DELETE":
|
||||
await prisma.membership
|
||||
.delete({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: userId,
|
||||
teamId: parseInt(teamId),
|
||||
},
|
||||
},
|
||||
})
|
||||
.then(() =>
|
||||
res.status(200).json({
|
||||
message: `Membership with id: ${safeQuery.data.id} deleted successfully`,
|
||||
})
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `Membership with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "DELETE":
|
||||
await prisma.membership
|
||||
.delete({ where: { userId_teamId: { userId: parseInt(userId), teamId: parseInt(teamId) } } })
|
||||
.then(() =>
|
||||
res.status(200).json({ message: `Membership with id: ${safeQuery.data.id} deleted successfully` })
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `Membership with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,8 +42,9 @@ async function createOrlistAllMemberships(
|
||||
res: NextApiResponse<MembershipsResponse | MembershipResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = req.userId;
|
||||
if (method === "GET") {
|
||||
const data = await prisma.membership.findMany();
|
||||
const data = await prisma.membership.findMany({ where: { userId } });
|
||||
const memberships = data.map((membership) => schemaMembershipPublic.parse(membership));
|
||||
if (memberships) res.status(200).json({ memberships });
|
||||
else
|
||||
@@ -56,7 +57,7 @@ async function createOrlistAllMemberships(
|
||||
const safe = schemaMembershipBodyParams.safeParse(req.body);
|
||||
if (!safe.success) throw new Error("Invalid request body");
|
||||
|
||||
const data = await prisma.membership.create({ data: safe.data });
|
||||
const data = await prisma.membership.create({ data: { ...safe.data, userId } });
|
||||
const membership = schemaMembershipPublic.parse(data);
|
||||
|
||||
if (membership) res.status(201).json({ membership, message: "Membership created successfully" });
|
||||
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import type { PaymentResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import { schemaPaymentPublic } from "@lib/validations/payment";
|
||||
import {
|
||||
schemaQueryIdParseInt,
|
||||
@@ -38,7 +37,7 @@ import {
|
||||
export async function paymentById(req: NextApiRequest, res: NextApiResponse<PaymentResponse>) {
|
||||
const { method, query } = req;
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const userId = await getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
|
||||
if (safeQuery.success && method === "GET") {
|
||||
const userWithBookings = await prisma.user.findUnique({
|
||||
@@ -49,10 +48,10 @@ export async function paymentById(req: NextApiRequest, res: NextApiResponse<Paym
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaPaymentPublic.parse(data))
|
||||
.then((payment) => {
|
||||
if (userWithBookings?.bookings.map((b) => b.id).includes(payment.bookingId)) {
|
||||
res.status(200).json({ payment });
|
||||
} else {
|
||||
if (!userWithBookings?.bookings.map((b) => b.id).includes(payment.bookingId)) {
|
||||
res.status(401).json({ message: "Unauthorized" });
|
||||
} else {
|
||||
res.status(200).json({ payment });
|
||||
}
|
||||
})
|
||||
.catch((error: Error) =>
|
||||
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import { PaymentsResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import { schemaPaymentPublic } from "@lib/validations/payment";
|
||||
|
||||
/**
|
||||
@@ -24,8 +23,8 @@ import { schemaPaymentPublic } from "@lib/validations/payment";
|
||||
* 404:
|
||||
* description: No payments were found
|
||||
*/
|
||||
async function allPayments(_: NextApiRequest, res: NextApiResponse<PaymentsResponse>) {
|
||||
const userId = await getCalcomUserId(res);
|
||||
async function allPayments(req: NextApiRequest, res: NextApiResponse<PaymentsResponse>) {
|
||||
const userId = req.userId;
|
||||
|
||||
const userWithBookings = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import type { ReminderMailResponse } from "@lib/types";
|
||||
import { schemaReminderMailBodyParams, schemaReminderMailPublic } from "@lib/validations/reminder-mail";
|
||||
import {
|
||||
schemaQueryIdParseInt,
|
||||
withValidQueryIdTransformParseInt,
|
||||
} from "@lib/validations/shared/queryIdTransformParseInt";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /v1/reminder-mails/{id}:
|
||||
* get:
|
||||
* summary: Get a reminderMail by ID
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: Numeric ID of the reminderMail to get
|
||||
* security:
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - reminder-mails
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: ReminderMail was not found
|
||||
* patch:
|
||||
* summary: Edit an existing reminderMail
|
||||
* consumes:
|
||||
* - application/json
|
||||
* parameters:
|
||||
* - in: body
|
||||
* name: reminderMail
|
||||
* description: The reminderMail to edit
|
||||
* schema:
|
||||
* type: object
|
||||
* $ref: '#/components/schemas/ReminderMail'
|
||||
* required: true
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: Numeric ID of the reminderMail to edit
|
||||
* security:
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - reminder-mails
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, reminderMail edited successfuly
|
||||
* model: ReminderMail
|
||||
* 400:
|
||||
* description: Bad request. ReminderMail body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* delete:
|
||||
* summary: Remove an existing reminderMail
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: Numeric ID of the reminderMail to delete
|
||||
* security:
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - reminder-mails
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, reminderMail removed successfuly
|
||||
* model: ReminderMail
|
||||
* 400:
|
||||
* description: Bad request. ReminderMail id is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
export async function reminderMailById(req: NextApiRequest, res: NextApiResponse<ReminderMailResponse>) {
|
||||
const { method, query, body } = req;
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaReminderMailBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.reminderMail
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaReminderMailPublic.parse(data))
|
||||
.then((reminder_mail) => res.status(200).json({ reminder_mail }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `ReminderMail with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
|
||||
case "PATCH":
|
||||
if (!safeBody.success) throw new Error("Invalid request body");
|
||||
await prisma.reminderMail
|
||||
.update({
|
||||
where: { id: safeQuery.data.id },
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((reminderMail) => schemaReminderMailPublic.parse(reminderMail))
|
||||
.then((reminder_mail) => res.status(200).json({ reminder_mail }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `ReminderMail with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
|
||||
case "DELETE":
|
||||
await prisma.reminderMail
|
||||
.delete({ where: { id: safeQuery.data.id } })
|
||||
.then(() =>
|
||||
res.status(200).json({ message: `ReminderMail with id: ${safeQuery.data.id} deleted successfully` })
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `ReminderMail with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(reminderMailById));
|
||||
@@ -1,76 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import { ReminderMailResponse, ReminderMailsResponse } from "@lib/types";
|
||||
import {
|
||||
schemaReminderMailBodyParams,
|
||||
schemaReminderMailPublic,
|
||||
withValidReminderMail,
|
||||
} from "@lib/validations/reminder-mail";
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /v1/reminder-mails:
|
||||
* get:
|
||||
* summary: Get all reminder mails
|
||||
* security:
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - reminder-mails
|
||||
* responses:
|
||||
* 200:
|
||||
* description: OK
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
* 404:
|
||||
* description: No reminder mails were found
|
||||
* post:
|
||||
* summary: Creates a new reminder mail
|
||||
* security:
|
||||
* - ApiKeyAuth: []
|
||||
* tags:
|
||||
* - reminder-mails
|
||||
* responses:
|
||||
* 201:
|
||||
* description: OK, reminder mail created
|
||||
* model: ReminderMail
|
||||
* 400:
|
||||
* description: Bad request. ReminderMail body is invalid.
|
||||
* 401:
|
||||
* description: Authorization information is missing or invalid.
|
||||
*/
|
||||
async function createOrlistAllReminderMails(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<ReminderMailsResponse | ReminderMailResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
if (method === "GET") {
|
||||
const data = await prisma.reminderMail.findMany();
|
||||
const reminder_mails = data.map((reminderMail) => schemaReminderMailPublic.parse(reminderMail));
|
||||
if (reminder_mails) res.status(200).json({ reminder_mails });
|
||||
else
|
||||
(error: Error) =>
|
||||
res.status(404).json({
|
||||
message: "No ReminderMails were found",
|
||||
error,
|
||||
});
|
||||
} else if (method === "POST") {
|
||||
const safe = schemaReminderMailBodyParams.safeParse(req.body);
|
||||
if (!safe.success) throw new Error("Invalid request body");
|
||||
|
||||
const data = await prisma.reminderMail.create({ data: safe.data });
|
||||
const reminder_mail = schemaReminderMailPublic.parse(data);
|
||||
|
||||
if (reminder_mail) res.status(201).json({ reminder_mail, message: "reminder mail created successfully" });
|
||||
else
|
||||
(error: Error) =>
|
||||
res.status(400).json({
|
||||
message: "could not create new reminder mail",
|
||||
error,
|
||||
});
|
||||
} else res.status(405).json({ message: `Method ${method} not allowed` });
|
||||
}
|
||||
|
||||
export default withMiddleware("HTTP_GET_OR_POST")(withValidReminderMail(createOrlistAllReminderMails));
|
||||
+52
-37
@@ -90,46 +90,61 @@ export async function scheduleById(req: NextApiRequest, res: NextApiResponse<Sch
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaScheduleBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
const userId = req.userId;
|
||||
const userSchedules = await prisma.schedule.findMany({ where: { userId } });
|
||||
const userScheduleIds = userSchedules.map((schedule) => schedule.id);
|
||||
if (!userScheduleIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.schedule
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaSchedulePublic.parse(data))
|
||||
.then((schedule) => res.status(200).json({ schedule }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `Schedule with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.schedule
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaSchedulePublic.parse(data))
|
||||
.then((schedule) => res.status(200).json({ schedule }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `Schedule with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "PATCH":
|
||||
if (!safeBody.success) {
|
||||
throw new Error("Invalid request body");
|
||||
}
|
||||
await prisma.schedule
|
||||
.update({ where: { id: safeQuery.data.id }, data: safeBody.data })
|
||||
.then((data) => schemaSchedulePublic.parse(data))
|
||||
.then((schedule) => res.status(200).json({ schedule }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `Schedule with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "PATCH":
|
||||
if (!safeBody.success) throw new Error("Invalid request body");
|
||||
await prisma.schedule
|
||||
.update({
|
||||
where: { id: safeQuery.data.id },
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((data) => schemaSchedulePublic.parse(data))
|
||||
.then((schedule) => res.status(200).json({ schedule }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `Schedule with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "DELETE":
|
||||
await prisma.schedule
|
||||
.delete({ where: { id: safeQuery.data.id } })
|
||||
.then(() =>
|
||||
res.status(200).json({
|
||||
message: `Schedule with id: ${safeQuery.data.id} deleted successfully`,
|
||||
})
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `Schedule with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "DELETE":
|
||||
await prisma.schedule
|
||||
.delete({ where: { id: safeQuery.data.id } })
|
||||
.then(() =>
|
||||
res.status(200).json({ message: `Schedule with id: ${safeQuery.data.id} deleted successfully` })
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `Schedule with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,8 +42,10 @@ async function createOrlistAllSchedules(
|
||||
res: NextApiResponse<SchedulesResponse | ScheduleResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = req.userId;
|
||||
|
||||
if (method === "GET") {
|
||||
const data = await prisma.schedule.findMany();
|
||||
const data = await prisma.schedule.findMany({ where: { userId } });
|
||||
const schedules = data.map((schedule) => schemaSchedulePublic.parse(schedule));
|
||||
if (schedules) res.status(200).json({ schedules });
|
||||
else
|
||||
@@ -55,8 +57,7 @@ async function createOrlistAllSchedules(
|
||||
} else if (method === "POST") {
|
||||
const safe = schemaScheduleBodyParams.safeParse(req.body);
|
||||
if (!safe.success) throw new Error("Invalid request body");
|
||||
|
||||
const data = await prisma.schedule.create({ data: safe.data });
|
||||
const data = await prisma.schedule.create({ data: { ...safe.data, userId } });
|
||||
const schedule = schemaSchedulePublic.parse(data);
|
||||
|
||||
if (schedule) res.status(201).json({ schedule, message: "Schedule created successfully" });
|
||||
|
||||
@@ -130,71 +130,85 @@ export async function selectedCalendarById(
|
||||
const safeBody = schemaSelectedCalendarBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
// This is how we set the userId and externalId in the query for managing compoundId.
|
||||
const [userId, integration, externalId] = safeQuery.data.id.split("_");
|
||||
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.selectedCalendar
|
||||
.findUnique({
|
||||
where: {
|
||||
userId_integration_externalId: {
|
||||
userId: parseInt(userId),
|
||||
integration: integration,
|
||||
externalId: externalId,
|
||||
const [paramUserId, integration, externalId] = safeQuery.data.id.split("_");
|
||||
const userId = req.userId;
|
||||
if (userId !== parseInt(paramUserId)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.selectedCalendar
|
||||
.findUnique({
|
||||
where: {
|
||||
userId_integration_externalId: {
|
||||
userId: userId,
|
||||
integration: integration,
|
||||
externalId: externalId,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
.then((selectedCalendar) => schemaSelectedCalendarPublic.parse(selectedCalendar))
|
||||
.then((selected_calendar) => res.status(200).json({ selected_calendar }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `SelectedCalendar with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
})
|
||||
.then((selectedCalendar) => schemaSelectedCalendarPublic.parse(selectedCalendar))
|
||||
.then((selected_calendar) => res.status(200).json({ selected_calendar }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `SelectedCalendar with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "PATCH":
|
||||
if (!safeBody.success) throw new Error("Invalid request body");
|
||||
await prisma.selectedCalendar
|
||||
.update({
|
||||
where: {
|
||||
userId_integration_externalId: {
|
||||
userId: parseInt(userId),
|
||||
integration: integration,
|
||||
externalId: externalId,
|
||||
case "PATCH":
|
||||
if (!safeBody.success) {
|
||||
throw new Error("Invalid request body");
|
||||
}
|
||||
await prisma.selectedCalendar
|
||||
.update({
|
||||
where: {
|
||||
userId_integration_externalId: {
|
||||
userId: userId,
|
||||
integration: integration,
|
||||
externalId: externalId,
|
||||
},
|
||||
},
|
||||
},
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((selectedCalendar) => schemaSelectedCalendarPublic.parse(selectedCalendar))
|
||||
.then((selected_calendar) => res.status(200).json({ selected_calendar }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `SelectedCalendar with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((selectedCalendar) => schemaSelectedCalendarPublic.parse(selectedCalendar))
|
||||
.then((selected_calendar) => res.status(200).json({ selected_calendar }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `SelectedCalendar with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "DELETE":
|
||||
await prisma.selectedCalendar
|
||||
.delete({
|
||||
where: {
|
||||
userId_integration_externalId: {
|
||||
userId: parseInt(userId),
|
||||
integration: integration,
|
||||
externalId: externalId,
|
||||
case "DELETE":
|
||||
await prisma.selectedCalendar
|
||||
.delete({
|
||||
where: {
|
||||
userId_integration_externalId: {
|
||||
userId: userId,
|
||||
integration: integration,
|
||||
externalId: externalId,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
.then(() =>
|
||||
res
|
||||
.status(200)
|
||||
.json({ message: `SelectedCalendar with id: ${safeQuery.data.id} deleted successfully` })
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `SelectedCalendar with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
})
|
||||
.then(() =>
|
||||
res.status(200).json({
|
||||
message: `SelectedCalendar with id: ${safeQuery.data.id} deleted successfully`,
|
||||
})
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `SelectedCalendar with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import { SelectedCalendarResponse, SelectedCalendarsResponse } from "@lib/types"
|
||||
import {
|
||||
schemaSelectedCalendarBodyParams,
|
||||
schemaSelectedCalendarPublic,
|
||||
withValidSelectedCalendar,
|
||||
} from "@lib/validations/selected-calendar";
|
||||
|
||||
/**
|
||||
@@ -46,8 +45,10 @@ async function createOrlistAllSelectedCalendars(
|
||||
res: NextApiResponse<SelectedCalendarsResponse | SelectedCalendarResponse>
|
||||
) {
|
||||
const { method } = req;
|
||||
const userId = req.userId;
|
||||
|
||||
if (method === "GET") {
|
||||
const data = await prisma.selectedCalendar.findMany();
|
||||
const data = await prisma.selectedCalendar.findMany({ where: { userId } });
|
||||
const selected_calendars = data.map((selected_calendar) =>
|
||||
schemaSelectedCalendarPublic.parse(selected_calendar)
|
||||
);
|
||||
@@ -61,8 +62,10 @@ async function createOrlistAllSelectedCalendars(
|
||||
} else if (method === "POST") {
|
||||
const safe = schemaSelectedCalendarBodyParams.safeParse(req.body);
|
||||
if (!safe.success) throw new Error("Invalid request body");
|
||||
|
||||
const data = await prisma.selectedCalendar.create({ data: safe.data });
|
||||
// Create new selectedCalendar connecting it to current userId
|
||||
const data = await prisma.selectedCalendar.create({
|
||||
data: { ...safe.data, user: { connect: { id: userId } } },
|
||||
});
|
||||
const selected_calendar = schemaSelectedCalendarPublic.parse(data);
|
||||
|
||||
if (selected_calendar)
|
||||
@@ -76,6 +79,4 @@ async function createOrlistAllSelectedCalendars(
|
||||
} else res.status(405).json({ message: `Method ${method} not allowed` });
|
||||
}
|
||||
|
||||
export default withMiddleware("HTTP_GET_OR_POST")(
|
||||
withValidSelectedCalendar(createOrlistAllSelectedCalendars)
|
||||
);
|
||||
export default withMiddleware("HTTP_GET_OR_POST")(createOrlistAllSelectedCalendars);
|
||||
+51
-38
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import type { TeamResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import {
|
||||
schemaQueryIdParseInt,
|
||||
withValidQueryIdTransformParseInt,
|
||||
@@ -91,51 +90,65 @@ export async function teamById(req: NextApiRequest, res: NextApiResponse<TeamRes
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaTeamBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
const userId = getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
const userWithMemberships = await prisma.membership.findMany({
|
||||
where: { userId: userId },
|
||||
});
|
||||
//FIXME: This is a hack to get the teamId from the user's membership
|
||||
console.log(userWithMemberships);
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.team
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaTeamPublic.parse(data))
|
||||
.then((team) => res.status(200).json({ team }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `Team with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
const userTeamIds = userWithMemberships.map((membership) => membership.teamId);
|
||||
if (!userTeamIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.team
|
||||
.findUnique({ where: { id: safeQuery.data.id } })
|
||||
.then((data) => schemaTeamPublic.parse(data))
|
||||
.then((team) => res.status(200).json({ team }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `Team with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "PATCH":
|
||||
if (!safeBody.success) throw new Error("Invalid request body");
|
||||
await prisma.team
|
||||
.update({
|
||||
where: { id: safeQuery.data.id },
|
||||
data: safeBody.data,
|
||||
})
|
||||
.then((team) => schemaTeamPublic.parse(team))
|
||||
.then((team) => res.status(200).json({ team }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `Team with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "PATCH":
|
||||
if (!safeBody.success) {
|
||||
throw new Error("Invalid request body");
|
||||
}
|
||||
await prisma.team
|
||||
.update({ where: { id: safeQuery.data.id }, data: safeBody.data })
|
||||
.then((team) => schemaTeamPublic.parse(team))
|
||||
.then((team) => res.status(200).json({ team }))
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `Team with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
case "DELETE":
|
||||
await prisma.team
|
||||
.delete({ where: { id: safeQuery.data.id } })
|
||||
.then(() =>
|
||||
res.status(200).json({ message: `Team with id: ${safeQuery.data.id} deleted successfully` })
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({ message: `Team with id: ${safeQuery.data.id} not found`, error })
|
||||
);
|
||||
break;
|
||||
case "DELETE":
|
||||
await prisma.team
|
||||
.delete({ where: { id: safeQuery.data.id } })
|
||||
.then(() =>
|
||||
res.status(200).json({
|
||||
message: `Team with id: ${safeQuery.data.id} deleted successfully`,
|
||||
})
|
||||
)
|
||||
.catch((error: Error) =>
|
||||
res.status(404).json({
|
||||
message: `Team with id: ${safeQuery.data.id} not found`,
|
||||
error,
|
||||
})
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
default:
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import { TeamResponse, TeamsResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import { schemaMembershipPublic } from "@lib/validations/membership";
|
||||
import { schemaTeamBodyParams, schemaTeamPublic, withValidTeam } from "@lib/validations/team";
|
||||
|
||||
/**
|
||||
@@ -40,7 +40,7 @@ import { schemaTeamBodyParams, schemaTeamPublic, withValidTeam } from "@lib/vali
|
||||
*/
|
||||
async function createOrlistAllTeams(req: NextApiRequest, res: NextApiResponse<TeamsResponse | TeamResponse>) {
|
||||
const { method } = req;
|
||||
const userId = getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
if (method === "GET") {
|
||||
const userWithMemberships = await prisma.membership.findMany({
|
||||
where: { userId: userId },
|
||||
@@ -55,17 +55,23 @@ async function createOrlistAllTeams(req: NextApiRequest, res: NextApiResponse<Te
|
||||
error,
|
||||
});
|
||||
} else if (method === "POST") {
|
||||
// FIXME: add userId as owner of the team
|
||||
const safe = schemaTeamBodyParams.safeParse(req.body);
|
||||
if (!safe.success) throw new Error("Invalid request body");
|
||||
const team = await prisma.team.create({ data: safe.data });
|
||||
const membership = await prisma.membership.create({
|
||||
data: { userId, teamId: team.id, role: "ADMIN" },
|
||||
});
|
||||
console.log(membership);
|
||||
// We're also creating the relation membership of team ownership in this call.
|
||||
const membership = await prisma.membership
|
||||
.create({
|
||||
data: { userId, teamId: team.id, role: "OWNER", accepted: true },
|
||||
})
|
||||
.then((membership) => schemaMembershipPublic.parse(membership));
|
||||
const data = schemaTeamPublic.parse(team);
|
||||
|
||||
if (data) res.status(201).json({ team: data, message: "Team created successfully" });
|
||||
// We are also returning the new ownership relation as owner besides team.
|
||||
if (data)
|
||||
res.status(201).json({
|
||||
team: data,
|
||||
owner: membership,
|
||||
message: "Team created successfully, we also made you the owner of this team",
|
||||
});
|
||||
else
|
||||
(error: Error) =>
|
||||
res.status(400).json({
|
||||
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import type { UserResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import {
|
||||
schemaQueryIdParseInt,
|
||||
withValidQueryIdTransformParseInt,
|
||||
@@ -91,8 +90,9 @@ export async function userById(req: NextApiRequest, res: NextApiResponse<UserRes
|
||||
const safeQuery = schemaQueryIdParseInt.safeParse(query);
|
||||
const safeBody = schemaUserBodyParams.safeParse(body);
|
||||
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
|
||||
const userId = getCalcomUserId(res);
|
||||
if (safeQuery.data.id === userId) {
|
||||
const userId = req.userId;
|
||||
if (safeQuery.data.id !== userId) res.status(401).json({ message: "Unauthorized" });
|
||||
else {
|
||||
switch (method) {
|
||||
case "GET":
|
||||
await prisma.user
|
||||
@@ -133,7 +133,7 @@ export async function userById(req: NextApiRequest, res: NextApiResponse<UserRes
|
||||
res.status(405).json({ message: "Method not allowed" });
|
||||
break;
|
||||
}
|
||||
} else res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
}
|
||||
|
||||
export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(userById));
|
||||
@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { withMiddleware } from "@lib/helpers/withMiddleware";
|
||||
import { UsersResponse } from "@lib/types";
|
||||
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
|
||||
import { schemaUserPublic } from "@lib/validations/user";
|
||||
|
||||
/**
|
||||
@@ -25,7 +24,7 @@ import { schemaUserPublic } from "@lib/validations/user";
|
||||
* description: No users were found
|
||||
*/
|
||||
async function allUsers(req: NextApiRequest, res: NextApiResponse<UsersResponse>) {
|
||||
const userId = getCalcomUserId(res);
|
||||
const userId = req.userId;
|
||||
const data = await prisma.user.findMany({
|
||||
where: {
|
||||
id: userId,
|
||||
|
||||
+9
-13
@@ -1,23 +1,19 @@
|
||||
{
|
||||
"extends": "@calcom/tsconfig/base.json",
|
||||
"exclude": ["node_modules", "templates"],
|
||||
"extends": "@calcom/tsconfig/nextjs.json",
|
||||
"compilerOptions": {
|
||||
"strictNullChecks": true,
|
||||
"baseUrl": ".",
|
||||
|
||||
"target": "es5",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"noEmit": true,
|
||||
"incremental": true,
|
||||
"module": "esnext",
|
||||
"resolveJsonModule": true,
|
||||
"jsx": "preserve",
|
||||
"paths": {
|
||||
"@api/*": ["pages/api/*"],
|
||||
"@lib/*": ["lib/*"],
|
||||
"@/*": ["*"]
|
||||
}
|
||||
},
|
||||
"include": ["./**/*.ts*"]
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"../../packages/types/*.d.ts",
|
||||
"../../packages/types/next-auth.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx"
|
||||
],
|
||||
"exclude": ["node_modules", "templates"]
|
||||
}
|
||||
Reference in new issue
Block a user