Skip to content

Commit

Permalink
perf: ⚡️ added drizzle and used it in whole project
Browse files Browse the repository at this point in the history
✅ Closes: 178
  • Loading branch information
growupanand committed Feb 9, 2024
1 parent 131c0a7 commit b50d53e
Show file tree
Hide file tree
Showing 45 changed files with 2,380 additions and 303 deletions.
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ node_modules/
.eslintignore
*.png
*.ico
DONT_DELETE_FOLDER
DONT_DELETE_FOLDER
**/*.sql
11 changes: 10 additions & 1 deletion apps/web/src/app/api/form/[formId]/conversation/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,16 @@ export async function POST(
(feature) => feature.name === "Collect form responses",
)?.featureValue ?? 0;

if (totalSubmissionsCount > formSubmissionLimit) {
if (!totalSubmissionsCount) {
console.error("Unable to get total submissions count", {
organizationId: form.organizationId,
});
}

if (
totalSubmissionsCount &&
totalSubmissionsCount > formSubmissionLimit
) {
throw new Error("This form have reached total submissions limit", {
cause: {
statusCode: 403,
Expand Down
57 changes: 27 additions & 30 deletions apps/web/src/app/api/webhook/route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
/* eslint-disable no-case-declarations */

import { NextRequest, NextResponse } from "next/server";
import type { WebhookEvent } from "@clerk/clerk-sdk-node";
import { prisma } from "@convoform/db";
import { type WebhookEvent } from "@clerk/clerk-sdk-node";
import {
db,
eq,
insertUserSchema,
organization,
organizationMember,
user,
} from "@convoform/db";

export async function POST(req: NextRequest) {
const reqJson = await req.json();
Expand All @@ -18,15 +25,15 @@ export async function POST(req: NextRequest) {
data.email_addresses.length > 0
? data.email_addresses[0]?.email_address
: "";
const user = {
const newUser = insertUserSchema.parse({
email: email,
firstName: data.first_name,
lastName: data.last_name,
userId: data.id,
imageUrl: data.image_url,
};
await prisma.user.create({
data: user,
});
await db.insert(user).values({
...newUser,
});
console.log("user created successfully in our database");
} catch (e: any) {
Expand All @@ -45,11 +52,7 @@ export async function POST(req: NextRequest) {
console.log("user id not found in event data");
break;
}
await prisma.user.deleteMany({
where: {
userId: userData.id,
},
});
await db.delete(user).where(eq(user.id, userData.id));
console.log("user deleted successfully in our database");
} catch (e: any) {
console.error({
Expand All @@ -69,8 +72,8 @@ export async function POST(req: NextRequest) {
organizationId: orgData.id,
slug: orgData.slug || "",
};
await prisma.organization.create({
data: org,
await db.insert(organization).values({
...org,
});
console.log("organization created successfully in our database");
} catch (e: any) {
Expand All @@ -91,8 +94,8 @@ export async function POST(req: NextRequest) {
userId: orgMembershipData.public_user_data.user_id,
role: orgMembershipData.role,
};
await prisma.organizationMember.create({
data: orgMembership,
await db.insert(organizationMember).values({
...orgMembership,
});
console.log(
"organizationMembership created successfully in our database",
Expand All @@ -114,11 +117,9 @@ export async function POST(req: NextRequest) {
console.log("organizationMembership id not found in event data");
break;
}
await prisma.organizationMember.deleteMany({
where: {
memberId: orgMembershipDeletedData.id,
},
});
await db
.delete(organizationMember)
.where(eq(organizationMember.memberId, orgMembershipDeletedData.id));
console.log(
"organizationMembership deleted successfully in our database",
);
Expand All @@ -139,16 +140,12 @@ export async function POST(req: NextRequest) {
console.log("organization id not found in event data");
break;
}
await prisma.organization.deleteMany({
where: {
organizationId: orgDeletedData.id,
},
});
await prisma.organizationMember.deleteMany({
where: {
organizationId: orgDeletedData.id,
},
});
await db
.delete(organization)
.where(eq(organization.organizationId, orgDeletedData.id));
await db
.delete(organizationMember)
.where(eq(organizationMember.organizationId, orgDeletedData.id));
console.log("organization deleted successfully in our database");
} catch (e: any) {
console.error({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export default function ConversationsSidebar({ formId }: Props) {
const conversations = data ?? [];

useEffect(() => {
if (conversations.length > 0 && !conversationId) {
if (conversations.length > 0 && conversations[0] && !conversationId) {
router.replace(`/forms/${formId}/conversations/${conversations[0].id}`);
}
}, [formId, conversations]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function FormDataCard({ orgId }: { orgId: string }) {
return <DataCardSkeleton />;
}

if (!data) {
if (!data || !data.totalCount) {
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function ResponseDataCard({ orgId }: { orgId: string }) {
return <DataCardSkeleton />;
}

if (!data) {
if (!data || !data.totalCount) {
return null;
}

Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/mainPage/workspace/formList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export default function FormList({ workspaceId, orgId }: Readonly<Props>) {
return <FormListLoading />;
}

console.log({ forms });

return (
<div className="h-full">
{emptyForms && <p className="text-muted-foreground">No form</p>}
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/components/sentryUserInit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function SentryUserInit() {
if (user) {
Sentry.setUser({
userId: user.id,
email: user.emailAddresses[0].emailAddress,
email: user.emailAddresses[0]?.emailAddress,
fullName: `${user.firstName} ${user.lastName}`,
});
}
Expand Down
16 changes: 9 additions & 7 deletions apps/web/src/lib/services/conversation.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Conversation } from "@convoform/db";
import {
CreateMessage,
experimental_StreamData,
Expand Down Expand Up @@ -80,7 +81,7 @@ export class ConversationService extends OpenAIService {
// 3. Conversation name

// 1. Get form field data
let formFieldData = {};
let formFieldData = {} as Record<string, string>;
const formFieldDataJSONString = functionCallPayload.arguments
.formData as string;
try {
Expand All @@ -98,7 +99,7 @@ export class ConversationService extends OpenAIService {
role: "assistant",
content: thankYouMessage,
},
];
] as Record<string, string>[];

// 3. Get conversation name
const conversationName =
Expand Down Expand Up @@ -133,18 +134,19 @@ export class ConversationService extends OpenAIService {
}

async saveConversation(
formFieldsData: Record<string, any>,
formFieldsData: Record<string, string>,
conversationName: string,
transcript: Record<string, any>[],
) {
transcript: Record<string, string>[],
): Promise<Conversation> {
try {
return await api.conversation.create({
const newConversation = {
formId: this.form.id,
organizationId: this.form.organizationId,
name: conversationName,
formFieldsData,
transcript,
});
};
return await api.conversation.create(newConversation);
} catch (error) {
const errorMessage = "Unable to save conversation";
console.error(errorMessage, error);
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/lib/services/generateFormField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class GenerateFormFieldService extends OpenAIService {
message,
]);

const responseJson = openAiResponse.choices[0].message.content;
const responseJson = openAiResponse.choices[0]?.message.content;
if (responseJson) {
try {
nextFieldName = JSON.parse(responseJson).fieldName;
Expand Down
6 changes: 3 additions & 3 deletions apps/web/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
],
"incremental": true,
"resolveJsonModule": true,
"strictNullChecks": true,
"strict": true
},
"include": [
"next-env.d.ts",
Expand All @@ -27,9 +29,7 @@
"**/*.jsx",
".next/types/**/*.ts",
"**/*.mjs",
"tailwind.config.js"
"tailwind.config.js",
],
"exclude": ["node_modules"],
"strictNullChecks": true,
"strict": true
}
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@
"type-check": "dotenv -- turbo run type-check",
"ui:add": "pnpm --filter @convoform/ui ui:add",
"db:generate": "dotenv -e .env.local -- pnpm --filter @convoform/db generate",
"db:generate:staging": "dotenv -e .env.staging -- pnpm --filter @convoform/db generate"
"db:generate:staging": "dotenv -e .env.staging -- pnpm --filter @convoform/db generate",
"drizzle-kit": "dotenv -e .env.local -- pnpm --filter @convoform/db drizzle-kit",
"drizzle:generate-migration": "dotenv -e .env.local -- pnpm --filter @convoform/db drizzle:generate-migration",
"drizzle:apply-migration": "dotenv -e .env.local -- pnpm --filter @convoform/db drizzle:apply-migration"
},
"config": {
"commitizen": {
Expand All @@ -43,9 +46,9 @@
"@convoform/tsconfig": "workspace:*",
"@ianvs/prettier-plugin-sort-imports": "^4.1.1",
"@release-it/conventional-changelog": "^8.0.1",
"@typescript-eslint/parser": "^6.18.0",
"auto-changelog": "^2.4.0",
"dotenv-cli": "^7.3.0",
"@typescript-eslint/parser": "^6.18.0",
"eslint": "^8.56.0",
"eslint-plugin-unused-imports": "^3.0.0",
"git-cz": "^4.9.0",
Expand All @@ -56,4 +59,4 @@
"release-it": "^17.0.1",
"turbo": "^1.12.1"
}
}
}
20 changes: 20 additions & 0 deletions packages/api/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/** @type {import("eslint").Linter.Config} */
module.exports = {
root: true,
extends: ["@convoform/eslint-config/next.js"],
rules: {
"react/react-in-jsx-scope": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-explicit-any": "off",
"unused-imports/no-unused-imports": "error",
"react-hooks/exhaustive-deps": "off",
"import/no-unresolved": "error",
},
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: "latest",
tsconfigRootDir: __dirname,
project: ["./tsconfig.json"],
},
plugins: ["import"],
};
12 changes: 9 additions & 3 deletions packages/api/package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
{
"name": "@convoform/api",
"version": "0.0.0",
"main": "index.ts",
"private": true,
"exports": {
".": "./index.ts"
},
"scripts": {
"type-check": "tsc --noEmit"
"type-check": "tsc --noEmit",
"lint": "eslint ./src/**/*.ts --fix"
},
"dependencies": {
"@clerk/nextjs": "^4.29.5",
Expand All @@ -15,7 +19,9 @@
},
"devDependencies": {
"@types/node": "^20",
"typescript": "^5",
"@typescript-eslint/parser": "^6.18.0",
"typescript": "^5"
"eslint": "^8.56.0",
"eslint-plugin-unused-imports": "^3.0.0"
}
}

0 comments on commit b50d53e

Please sign in to comment.