cal.pub0.org/lib/helpers/customPrisma.ts

54 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-06-08 16:52:25 +00:00
import { hash } from "bcryptjs";
import cache from "memory-cache";
import { NextMiddleware } from "next-api-middleware";
2022-06-14 17:48:47 +00:00
import { PRISMA_CLIENT_CACHING_TIME } from "@calcom/api/lib/constants";
2022-06-21 21:02:43 +00:00
// import prismaAdmin from "@calcom/console/modules/common/utils/prisma";
2022-06-22 03:49:24 +00:00
import { CONSOLE_URL } from "@calcom/lib/constants";
2022-06-08 16:52:25 +00:00
import { prisma, customPrisma } from "@calcom/prisma";
// This replaces the prisma client for the cusotm one if the key is valid
2022-06-08 16:52:25 +00:00
export const customPrismaClient: NextMiddleware = async (req, res, next) => {
const {
query: { key },
}: { query: { key?: string } } = req;
2022-06-08 16:52:25 +00:00
// If no custom api Id is provided, attach to request the regular cal.com prisma client.
if (!key) {
2022-06-08 16:52:25 +00:00
req.prisma = prisma;
await next();
} else {
// If we have a key, we check if the deployment matching the key, has a databaseUrl value set.
2022-06-22 03:49:24 +00:00
const databaseUrl = await fetch(
`${process.env.NEXT_PUBLIC_CONSOLE_URL || CONSOLE_URL}/api/deployments/database?key=${key}`
2022-06-22 03:49:24 +00:00
)
2022-06-21 21:02:43 +00:00
.then((res) => res.json())
.then((res) => res.databaseUrl);
if (!databaseUrl) {
res.status(400).json({ error: "no databaseUrl set up at your instance yet" });
return;
}
// FIXME: Add some checks for the databaseUrl to make sure it is valid. (e.g. not a localhost)
2022-06-21 21:02:43 +00:00
const hashedUrl = await hash(databaseUrl, 12);
2022-06-08 16:52:25 +00:00
const cachedPrisma = cache.get(hashedUrl);
/* We cache each cusotm prisma client for 24h to avoid too many requests to the database. */
2022-06-08 16:52:25 +00:00
if (!cachedPrisma) {
cache.put(
hashedUrl,
2022-06-21 21:02:43 +00:00
customPrisma({ datasources: { db: { url: databaseUrl } } }),
2022-06-08 16:52:25 +00:00
PRISMA_CLIENT_CACHING_TIME // Cache the prisma client for 24 hours
);
}
2022-06-22 03:49:24 +00:00
req.prisma = customPrisma({ datasources: { db: { url: databaseUrl } } });
/* @note:
In order to skip verifyApiKey for customPrisma requests,
we pass isAdmin true, and userId 0, if we detect them later,
we skip verifyApiKey logic and pass onto next middleware instead.
*/
req.isAdmin = true;
req.userId = 0;
2022-06-08 16:52:25 +00:00
}
await next();
};