Skip to content

Commit

Permalink
Merge branch '06-19-feat_seperate_user_config' of github.com:aamiraza…
Browse files Browse the repository at this point in the history
…d/homelab-connector into 06-19-feat_seperate_user_config
  • Loading branch information
aamirazad committed Jun 19, 2024
2 parents 02bf487 + 3f77bf4 commit bb2ccd8
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 63 deletions.
64 changes: 25 additions & 39 deletions src/app/actions.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,20 @@
"use server";

import { db } from "@/server/db";
import { users } from "@/server/db/schema";
import { UsersTableType, users } from "@/server/db/schema";
import type { PaperlessDocumentsType } from "@/types";
import { auth } from "@clerk/nextjs/server";

export async function setFullUserName(name: string) {
const { userId } = auth();

if (!userId) {
throw new Error("Not authenticated");
}

try {
await db
.insert(users)
.values({ fullName: name, userId: userId })
.onConflictDoUpdate({ target: users.userId, set: { fullName: name } });
} catch {
throw new Error("Database error");
}
interface User {
userId: string;
fullName?: string;
paperlessURL?: string;
paperlessToken?: string;
}

export async function setPaperlessURL(url: string) {
export async function setUserProperty<K extends keyof User>(
propertyName: K,
value: UsersTableType[K],
) {
const { userId } = auth();

if (!userId) {
Expand All @@ -32,48 +24,42 @@ export async function setPaperlessURL(url: string) {
try {
await db
.insert(users)
.values({ paperlessURL: url, userId: userId })
.onConflictDoUpdate({ target: users.userId, set: { paperlessURL: url } });
.values({ [propertyName]: value, userId: userId })
.onConflictDoUpdate({
target: users.userId,
set: { [propertyName]: value },
});
} catch {
throw new Error("Database error");
}
}

export async function setPaperlessToken(token: string) {
export async function getUserData() {
const { userId } = auth();

if (!userId) {
throw new Error("Not authenticated");
}

try {
await db
.insert(users)
.values({ paperlessToken: token, userId: userId })
.onConflictDoUpdate({
target: users.userId,
set: { paperlessToken: token },
});
} catch {
throw new Error("Database error");
}
const userData = await db.query.users.findFirst({
where: (model, { eq }) => eq(model.userId, userId),
});

return userData;
}

export async function getPaperlessDocuments(query: string) {
const user = auth();
const { userId } = auth();

if (!user.userId)
return Response.json({ error: "Unauthorized" }, { status: 401 });
if (!userId) return Response.json({ error: "Unauthorized" }, { status: 401 });

const userData = await db.query.users.findFirst({
where: (model, { eq }) => eq(model.userId, user.userId),
});
const userData = await getUserData();

if (!query || query == "null" || query.length < 3 || !userData)
return Response.json({ error: "Bad Request" }, { status: 400 });

const response = await fetch(
`${userData.paperlessURL}/api/search/?query=${query}` + query,
`${userData.paperlessURL}/api/search/?query=${query}`,
{
method: "GET",
headers: {
Expand Down
13 changes: 5 additions & 8 deletions src/app/paperless/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ function DocumentsSearch() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const givenQuery = searchParams.get("query") || "";
// 1. Define your form.
const givenQuery = searchParams.get("query") ?? "";
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
Expand All @@ -55,10 +54,8 @@ function DocumentsSearch() {
);

function onSubmit(values: z.infer<typeof formSchema>) {
if (values["query"])
router.replace(
pathname + "?" + createQueryString("query", values["query"]),
);
if (values.query)
router.replace(pathname + "?" + createQueryString("query", values.query));
}

return (
Expand Down Expand Up @@ -86,8 +83,8 @@ function DocumentsSearch() {

function DocumentsPage() {
const searchParams = useSearchParams();
const query = searchParams.get("query") || "";
const query = searchParams.get("query") ?? "";

const QueryResult = useQuery({
queryKey: ["key", query],
queryFn: async () => {
Expand Down
29 changes: 13 additions & 16 deletions src/app/settings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,12 @@ import { Input } from "@/components/ui/input";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { Dispatch, SetStateAction, useState } from "react";
import type { Dispatch, SetStateAction } from "react";
import { useState } from "react";
import { useUser } from "@clerk/nextjs";
import { redirect, usePathname } from "next/navigation";
import LoadingSpinner from "@/components/loading-spinner";
import {
setFullUserName,
setPaperlessToken,
setPaperlessURL,
} from "../actions";
import { setUserProperty } from "../actions";
import { Toaster } from "@/components/ui/sonner";
import { toast } from "sonner";

Expand Down Expand Up @@ -56,7 +53,7 @@ function FullName({
async function onSubmit(values: z.infer<typeof formSchema>) {
setActiveTab((prevTab) => prevTab + 1); // Increment activeTab
try {
await setFullUserName(values["FullName"], user!.id);
await setUserProperty("fullName", values.FullName);
// Operation succeeded, show success toast
toast("Your name preferences was saved");
// Optionally, move to a new tab or take another action to indicate success
Expand Down Expand Up @@ -120,13 +117,13 @@ function PaperlessURL({
}

async function onSubmit(values: z.infer<typeof formSchema>) {
if (values["URL"] == "") {
if (values.URL == "") {
setActiveTab((prevTab) => prevTab + 2); // Skip api key form
} else {
setActiveTab((prevTab) => prevTab + 1); // Increment activeTab
}
try {
await setPaperlessURL(values["URL"], user!.id);
await setUserProperty("paperlessURL", values.URL);
// Operation succeeded, show success toast
toast("Your paperless URL preferences was saved");
// Optionally, move to a new tab or take another action to indicate success
Expand Down Expand Up @@ -193,7 +190,7 @@ function PaperlessToken({
setActiveTab((prevTab) => prevTab + 1); // Increment activeTab

try {
await setPaperlessToken(values["token"], user!.id);
await setUserProperty("paperlessToken", values.token);
// Operation succeeded, show success toast
toast("Your paperless token preferences was saved");
} catch {
Expand Down Expand Up @@ -221,8 +218,8 @@ function PaperlessToken({
<Input {...field} />
</FormControl>
<FormDescription>
You can create (or re-create) an API token by opening the "My
Profile" link in the user dropdown found in the web UI and
You can create (or re-create) an API token by opening the &quot;My
Profile&quot; link in the user dropdown found in the web UI and
clicking the circular arrow button.
</FormDescription>
</FormItem>
Expand Down Expand Up @@ -271,10 +268,10 @@ export default function SettingsPage() {
const [activeTab, setActiveTab] = useState(0);

const formElements = [
<FullName setActiveTab={setActiveTab} />,
<PaperlessURL setActiveTab={setActiveTab} />,
<PaperlessToken setActiveTab={setActiveTab} />,
<Done />,
<FullName key="fullname" setActiveTab={setActiveTab} />,
<PaperlessURL key="paperlessurl" setActiveTab={setActiveTab} />,
<PaperlessToken key="paperlesstoken" setActiveTab={setActiveTab} />,
<Done key="done" />,
];
return (
<>
Expand Down
2 changes: 2 additions & 0 deletions src/server/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,5 @@ export const users = createTable("users", {
paperlessURL: varchar("paperlessURL", { length: 256 }),
paperlessToken: varchar("paperlessToken", { length: 256 }),
});

export type UsersTableType = typeof users.$inferSelect;

0 comments on commit bb2ccd8

Please sign in to comment.