mirror of
https://github.com/formbricks/formbricks.git
synced 2026-04-22 11:29:22 -05:00
140aee749b
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com> Co-authored-by: Matthias Nannt <mail@matthiasnannt.com> Co-authored-by: Dhruwang <dhruwangjariwala18@gmail.com> Co-authored-by: Victor Santos <victor@formbricks.com> Co-authored-by: victorvhs017 <115753265+victorvhs017@users.noreply.github.com>
50 lines
1.5 KiB
TypeScript
50 lines
1.5 KiB
TypeScript
import { apiKeyCache } from "@/lib/cache/api-key";
|
|
import { Prisma } from "@prisma/client";
|
|
import { cache as reactCache } from "react";
|
|
import { prisma } from "@formbricks/database";
|
|
import { cache } from "@formbricks/lib/cache";
|
|
import { getHash } from "@formbricks/lib/crypto";
|
|
import { validateInputs } from "@formbricks/lib/utils/validate";
|
|
import { ZString } from "@formbricks/types/common";
|
|
import { DatabaseError, InvalidInputError, ResourceNotFoundError } from "@formbricks/types/errors";
|
|
|
|
export const getEnvironmentIdFromApiKey = reactCache(async (apiKey: string): Promise<string | null> => {
|
|
const hashedKey = getHash(apiKey);
|
|
return cache(
|
|
async () => {
|
|
validateInputs([apiKey, ZString]);
|
|
|
|
if (!apiKey) {
|
|
throw new InvalidInputError("API key cannot be null or undefined.");
|
|
}
|
|
|
|
try {
|
|
const apiKeyData = await prisma.apiKey.findUnique({
|
|
where: {
|
|
hashedKey,
|
|
},
|
|
select: {
|
|
environmentId: true,
|
|
},
|
|
});
|
|
|
|
if (!apiKeyData) {
|
|
throw new ResourceNotFoundError("apiKey", apiKey);
|
|
}
|
|
|
|
return apiKeyData.environmentId;
|
|
} catch (error) {
|
|
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
|
throw new DatabaseError(error.message);
|
|
}
|
|
|
|
throw error;
|
|
}
|
|
},
|
|
[`management-api-getEnvironmentIdFromApiKey-${apiKey}`],
|
|
{
|
|
tags: [apiKeyCache.tag.byHashedKey(hashedKey)],
|
|
}
|
|
)();
|
|
});
|