chore: Simplify person service by removing complex getOrCreatePerson function (#1643)

This commit is contained in:
Matti Nannt
2023-11-20 18:22:11 +01:00
committed by GitHub
parent af181eabdc
commit c8c98499ed
11 changed files with 37 additions and 71 deletions
@@ -9,7 +9,11 @@ interface WidgetStatusIndicatorProps {
}
export default async function WidgetStatusIndicator({ environmentId, type }: WidgetStatusIndicatorProps) {
const [environment] = await Promise.all([getEnvironment(environmentId)]);
const environment = await getEnvironment(environmentId);
if (!environment) {
throw new Error("Environment not found");
}
const stati = {
notImplemented: {
@@ -1,7 +1,7 @@
import { getUpdatedState } from "@/app/api/v1/(legacy)/js/sync/lib/sync";
import { responses } from "@/app/lib/api/response";
import { transformErrorToDetails } from "@/app/lib/api/validator";
import { getOrCreatePersonByUserId } from "@formbricks/lib/person/service";
import { createPerson, getPersonByUserId } from "@formbricks/lib/person/service";
import { ZJsPeopleUserIdInput } from "@formbricks/types/js";
import { NextResponse } from "next/server";
@@ -26,9 +26,12 @@ export async function POST(req: Request): Promise<NextResponse> {
const { environmentId, userId } = inputValidation.data;
const personWithUserId = await getOrCreatePersonByUserId(userId, environmentId);
let person = await getPersonByUserId(environmentId, userId);
if (!person) {
person = await createPerson(environmentId, userId);
}
const state = await getUpdatedState(environmentId, personWithUserId.id);
const state = await getUpdatedState(environmentId, person.id);
return responses.successResponse({ ...state }, true);
} catch (error) {
console.error(error);
@@ -4,13 +4,12 @@ import { getLatestActionByPersonId } from "@formbricks/lib/action/service";
import { getActionClasses } from "@formbricks/lib/actionClass/service";
import { IS_FORMBRICKS_CLOUD, PRICING_USERTARGETING_FREE_MTU } from "@formbricks/lib/constants";
import { getEnvironment, updateEnvironment } from "@formbricks/lib/environment/service";
import { getOrCreatePersonByUserId, getPersonByUserId } from "@formbricks/lib/person/service";
import { createPerson, getPersonByUserId } from "@formbricks/lib/person/service";
import { getProductByEnvironmentId } from "@formbricks/lib/product/service";
import { getSyncSurveys } from "@formbricks/lib/survey/service";
import { getMonthlyActiveTeamPeopleCount, getTeamByEnvironmentId } from "@formbricks/lib/team/service";
import { TEnvironment } from "@formbricks/types/environment";
import { TJsState, ZJsPeopleUserIdInput } from "@formbricks/types/js";
import { TPerson } from "@formbricks/types/people";
import { NextResponse } from "next/server";
export async function OPTIONS(): Promise<NextResponse> {
@@ -72,13 +71,15 @@ export async function GET(
isMauLimitReached = !hasUserTargetingSubscription && currentMau >= PRICING_USERTARGETING_FREE_MTU;
}
let person: TPerson | null;
let person = await getPersonByUserId(environmentId, userId);
if (!isMauLimitReached) {
person = await getOrCreatePersonByUserId(userId, environmentId);
if (!person) {
person = await createPerson(environmentId, userId);
}
} else {
person = await getPersonByUserId(userId, environmentId);
const errorMessage = `Monthly Active Users limit in the current plan is reached in ${environmentId}`;
if (!person) {
// if it's a new person and MAU limit is reached, throw an error
throw new Error(errorMessage);
} else {
// check if person has been active this month
@@ -1,6 +1,6 @@
import { responses } from "@/app/lib/api/response";
import { transformErrorToDetails } from "@/app/lib/api/validator";
import { getOrCreatePersonByUserId, updatePerson } from "@formbricks/lib/person/service";
import { getPersonByUserId, updatePerson } from "@formbricks/lib/person/service";
import { ZPersonUpdateInput } from "@formbricks/types/people";
import { NextResponse } from "next/server";
@@ -31,7 +31,7 @@ export async function POST(req: Request, context: Context): Promise<NextResponse
);
}
const person = await getOrCreatePersonByUserId(userId, environmentId);
const person = await getPersonByUserId(environmentId, userId);
if (!person) {
return responses.notFoundResponse("PersonByUserId", userId, true);
+6 -2
View File
@@ -6,7 +6,7 @@ import PinScreen from "@/app/s/[surveyId]/components/PinScreen";
import SurveyInactive from "@/app/s/[surveyId]/components/SurveyInactive";
import { checkValidity } from "@/app/s/[surveyId]/lib/prefilling";
import { REVALIDATION_INTERVAL, WEBAPP_URL } from "@formbricks/lib/constants";
import { getOrCreatePersonByUserId } from "@formbricks/lib/person/service";
import { createPerson, getPersonByUserId } from "@formbricks/lib/person/service";
import { getProductByEnvironmentId } from "@formbricks/lib/product/service";
import { getResponseBySingleUseId } from "@formbricks/lib/response/service";
import { getSurvey } from "@formbricks/lib/survey/service";
@@ -147,7 +147,11 @@ export default async function LinkSurveyPage({ params, searchParams }: LinkSurve
const userId = searchParams.userId;
if (userId) {
await getOrCreatePersonByUserId(userId, survey.environmentId);
// make sure the person exists or get's created
const person = await getPersonByUserId(survey.environmentId, userId);
if (!person) {
await createPerson(survey.environmentId, userId);
}
}
const isSurveyPinProtected = Boolean(!!survey && survey.pin);
+1 -1
View File
@@ -240,7 +240,7 @@ export const createAction = async (data: TActionInput): Promise<TAction> => {
actionType = "automatic";
}
const person = await getPersonByUserId(userId, environmentId);
const person = await getPersonByUserId(environmentId, userId);
if (!person) {
throw new Error("Person not found");
+2 -2
View File
@@ -70,7 +70,7 @@ export const updateDisplay = async (
let person: TPerson | null = null;
if (displayInput.userId) {
person = await getPersonByUserId(displayInput.userId, displayInput.environmentId);
person = await getPersonByUserId(displayInput.environmentId, displayInput.userId);
if (!person) {
throw new ResourceNotFoundError("Person", displayInput.userId);
}
@@ -160,7 +160,7 @@ export const createDisplay = async (displayInput: TDisplayCreateInput): Promise<
try {
let person;
if (displayInput.userId) {
person = await getPersonByUserId(displayInput.userId, displayInput.environmentId);
person = await getPersonByUserId(displayInput.environmentId, displayInput.userId);
}
const display = await prisma.display.create({
data: {
+3 -14
View File
@@ -22,14 +22,13 @@ import { validateInputs } from "../utils/validate";
import { environmentCache } from "./cache";
import { formatEnvironmentDateFields } from "./util";
export const getEnvironment = (environmentId: string) =>
export const getEnvironment = (environmentId: string): Promise<TEnvironment | null> =>
unstable_cache(
async (): Promise<TEnvironment> => {
async () => {
validateInputs([environmentId, ZId]);
let environmentPrisma;
try {
environmentPrisma = await prisma.environment.findUnique({
return await prisma.environment.findUnique({
where: {
id: environmentId,
},
@@ -42,16 +41,6 @@ export const getEnvironment = (environmentId: string) =>
throw error;
}
try {
const environment = ZEnvironment.parse(environmentPrisma);
return environment;
} catch (error) {
if (error instanceof z.ZodError) {
console.error(JSON.stringify(error.errors, null, 2));
}
throw new ValidationError("Data validation of environment failed");
}
},
[`getEnvironment-${environmentId}`],
{
+1 -40
View File
@@ -291,7 +291,7 @@ export const updatePerson = async (personId: string, personInput: TPersonUpdateI
}
};
export const getPersonByUserId = async (userId: string, environmentId: string): Promise<TPerson | null> => {
export const getPersonByUserId = async (environmentId: string, userId: string): Promise<TPerson | null> => {
const personPrisma = await unstable_cache(
async () => {
validateInputs([userId, ZString], [environmentId, ZId]);
@@ -370,45 +370,6 @@ export const getPersonByUserId = async (userId: string, environmentId: string):
return transformPrismaPerson(personPrisma);
};
export const getOrCreatePersonByUserId = async (userId: string, environmentId: string): Promise<TPerson> =>
await unstable_cache(
async () => {
validateInputs([userId, ZString], [environmentId, ZId]);
let person = await getPersonByUserId(userId, environmentId);
if (person) {
return person;
}
// create a new person
const personPrisma = await prisma.person.create({
data: {
environment: {
connect: {
id: environmentId,
},
},
userId,
},
select: selectPerson,
});
personCache.revalidate({
id: personPrisma.id,
environmentId,
userId,
});
return transformPrismaPerson(personPrisma);
},
[`getOrCreatePersonByUserId-${userId}-${environmentId}`],
{
tags: [personCache.tag.byEnvironmentIdAndUserId(environmentId, userId)],
revalidate: SERVICES_REVALIDATION_INTERVAL,
}
)();
export const updatePersonAttribute = async (
personId: string,
attributeClassId: string,
+1 -1
View File
@@ -201,7 +201,7 @@ export const createResponse = async (responseInput: TResponseInput): Promise<TRe
let person: TPerson | null = null;
if (responseInput.userId) {
person = await getPersonByUserId(responseInput.userId, responseInput.environmentId);
person = await getPersonByUserId(responseInput.environmentId, responseInput.userId);
if (!person) {
throw new ResourceNotFoundError("Person", responseInput.userId);
}
+4
View File
@@ -10,6 +10,10 @@ export default async function EnvironmentNotice({ environmentId }: EnvironmentNo
const headersList = headers();
const currentUrl = headersList.get("referer") || headersList.get("x-invoke-path") || "";
const environment = await getEnvironment(environmentId);
if (!environment) {
throw new Error("Environment not found");
}
const environments = await getEnvironments(environment.productId);
const otherEnvironmentId = environments.find((e) => e.id !== environment.id)?.id || "";