Skip to content

Commit

Permalink
chore: kv
Browse files Browse the repository at this point in the history
  • Loading branch information
arshad-yaseen committed Dec 1, 2023
1 parent 3821a42 commit f675017
Show file tree
Hide file tree
Showing 44 changed files with 530 additions and 538 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
NEXT_PUBLIC_APP_URL=http://localhost:3000
NEXTAUTH_URL=http://localhost:3000
USER_SESSION_KEY=markdx-user-session

# Database (MySQL - Planetscale)
DATABASE_URL="mysql://root:root@localhost:3306/markdx?schema=public"

OPENAI_API_KEY=
OPENAI_MODEL=gpt-4-1106-preview

# openssl rand -base64 32 : Run this in your command line and paste here the generated secret
NEXTAUTH_SECRET=
CRYPTO_SECRET_KEY=

# Required 👆🏻
# Optional 👇🏻
Expand Down
2 changes: 1 addition & 1 deletion app/(dashboard)/dashboard/billing/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const metadata = {
}

export default async function BillingPage() {
const user = await getCurrentUser()
const { sessionUser: user } = await getCurrentUser()

if (!user) {
redirect(authOptions?.pages?.signIn || "/login")
Expand Down
2 changes: 1 addition & 1 deletion app/(dashboard)/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { DashboardShell } from "@/components/dashboard/shell"
import { Icons } from "@/components/icons"

async function Dashboard() {
const user = (await getCurrentUser()) as any
const { sessionUser: user } = await getCurrentUser()

if (!user) {
redirect(authOptions?.pages?.signIn || "/login")
Expand Down
2 changes: 1 addition & 1 deletion app/(dashboard)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const metadata = {
}

async function DashboardLayout({ children }: DashboardLayout) {
const user = await getCurrentUser()
const { sessionUser: user } = await getCurrentUser()

if (!user) {
return notFound()
Expand Down
39 changes: 11 additions & 28 deletions app/(editor)/edit/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import {
monacoInstanceState,
} from "@/atoms/editor"
import { handleShortCut } from "@/utils/editor"
import { GET } from "@/utils/http.utils"
import { useAtom, useAtomValue } from "jotai"

import { editorCode } from "types"
import { defaultEditorContent } from "@/config/editor"
import AIToolsSection from "@/components/editor/ai-tools-section"
import EditorSection from "@/components/editor/editor-section"
import MarkdownNotFound from "@/components/editor/markdown-not-found"
import PreviewSection from "@/components/editor/preview-section"

type prevCodeType = {
Expand All @@ -22,29 +22,26 @@ type prevCodeType = {
content: string
}

type Markdown = {
markdownPost: {
postCodes: editorCode[]
}
isEligibleForAI: boolean
}

export default function page({ params }: { params: { id: string } }) {
const [editorCodes, setEditorCodes] = useAtom(editorCodesState)
const editorActiveSection = useAtomValue(editorActiveSectionState)
const [markdownCode, setMarkdownCode] = useState("")
const monacoInstance = useAtomValue(monacoInstanceState)
const [markdownNotFoundDialogOpen, setMarkdownNotFoundDialogOpen] =
useState(false)
const [isEligibleForAI, setIsEligibleForAI] = useState(true)

const markdownId = params.id

const getMarkdownPost = async (markdownId: string) => {
const response = await fetch(`/api/posts/${markdownId}`, {
method: "GET",
})
const markdown = await GET<Markdown>(`/api/posts/${markdownId}`)

if (!response?.ok) {
setMarkdownNotFoundDialogOpen(true)
return
}

const resJson = await response.json()
const markdownPost = resJson.markdownPost
const markdownPost = markdown.markdownPost

if (
markdownPost?.postCodes?.length > 0 &&
Expand All @@ -60,16 +57,7 @@ export default function page({ params }: { params: { id: string } }) {
setMarkdownCode(code.content)
})

// Check if the user is eligible for AI - make a request to the API
const response = await fetch(`/api/user/eligible-for-ai`, {
method: "GET",
next: {
revalidate: 0,
},
cache: "no-store",
})
const resJson = await response.json()
setIsEligibleForAI(resJson.isEligibleForAI)
setIsEligibleForAI(markdown.isEligibleForAI)
} else {
const defaultCode = [defaultEditorContent] as editorCode[]

Expand Down Expand Up @@ -125,11 +113,6 @@ export default function page({ params }: { params: { id: string } }) {
<PreviewSection
code={editorCodes.map((code: editorCode) => code.content).join("\n\n")}
/>
{markdownNotFoundDialogOpen && (
<MarkdownNotFound
markdownNotFoundDialogOpen={markdownNotFoundDialogOpen}
/>
)}
</div>
)
}
2 changes: 1 addition & 1 deletion app/(home)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface MarketingLayoutProps {
export default async function MarketingLayout({
children,
}: MarketingLayoutProps) {
const user = await getCurrentUser()
const { sessionUser: user } = await getCurrentUser()

return (
<div className="flex min-h-screen flex-col">
Expand Down
28 changes: 18 additions & 10 deletions app/api/chat/route.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { ServerResponse } from "@/server/utils"
import { OpenAIBody } from "@/types"
import { OpenAIStream, StreamingTextResponse } from "ai"
import OpenAI from "openai"

import { env } from "@/env.mjs"

import { OpenAIStream, StreamingTextResponse } from 'ai';

import { ServerResponse } from "@/server/utils"
import { getCurrentUser } from "@/lib/session"
import { kvget, kvset } from "@/lib/kv"
import { openai } from "@/lib/openai"
import { getCurrentUser } from "@/lib/session"

if (!env.OPENAI_API_KEY) {
throw new Error("Missing env var from OpenAI")
Expand All @@ -16,9 +15,9 @@ if (!env.OPENAI_API_KEY) {
export async function POST(req: Request): Promise<Response> {
// Parse the request body.
const body: OpenAIBody = (await req.json()) as OpenAIBody
const userId = (await getCurrentUser())?.id
const { sessionUser: user } = await getCurrentUser()

if(!userId) {
if (!user?.id) {
return ServerResponse.unauthorized()
}

Expand All @@ -32,7 +31,16 @@ export async function POST(req: Request): Promise<Response> {
stream: true,
}

const response = await openai.chat.completions.create(payload);
const stream = OpenAIStream(response);
return new StreamingTextResponse(stream);
const response = await openai.chat.completions.create(payload)
const user_ai_run_count = await kvget(user.id, "ai_run_count")

// Count the number of times the user has used the AI.
kvset(
user.id,
"ai_run_count",
user_ai_run_count ? Number(user_ai_run_count) + 1 : 1
)

const stream = OpenAIStream(response)
return new StreamingTextResponse(stream)
}
Loading

1 comment on commit f675017

@vercel
Copy link

@vercel vercel bot commented on f675017 Dec 1, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.