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

50 lines
1.6 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-20 00:29:18 +00:00
import prismaAdmin from "@calcom/console/modules/common/utils/prisma";
2022-06-13 22:32:07 +00:00
import { asStringOrUndefined } from "@calcom/lib/asStringOrNull";
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 {
const id = asStringOrUndefined(key);
2022-06-08 16:52:25 +00:00
// If we have a key, we check if it is valid.
const deployment = await prismaAdmin.deployment.findUnique({
where: { key },
2022-06-08 16:52:25 +00:00
});
if (!deployment) {
2022-06-08 16:52:25 +00:00
res.status(400).json({ error: "Invalid custom credentials id" });
return;
}
const credentials = deployment.databaseUrl;
if (!credentials) {
res.status(400).json({ error: "no databaseUrl set up at your instance yet" });
return;
}
2022-06-08 16:52:25 +00:00
const hashedUrl = await hash(credentials, 12);
const cachedPrisma = cache.get(hashedUrl);
if (!cachedPrisma) {
cache.put(
hashedUrl,
customPrisma({ datasources: { db: { url: credentials } } }),
PRISMA_CLIENT_CACHING_TIME // Cache the prisma client for 24 hours
);
}
req.prisma = cachedPrisma;
}
await next();
};