Skip to content

Commit

Permalink
Finally solving the issue with the fetchRedis helper function, implem…
Browse files Browse the repository at this point in the history
…enting the layout.tsx file
  • Loading branch information
Isztof committed Sep 11, 2023
1 parent 06e27d9 commit 6d064af
Show file tree
Hide file tree
Showing 10 changed files with 167 additions and 12 deletions.
89 changes: 84 additions & 5 deletions app/(dashboard)/dashboard/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,88 @@
import { FC } from 'react'
import { authOptions } from '@/lib/auth'
import { getServerSession } from 'next-auth'
import { notFound } from 'next/navigation'
import Link from 'next/link';
import { FC, ReactNode } from 'react'
import Image from 'next/image';
import SignOutButton from '@/components/ui/SignOutButton';

interface ProvidersProps {}

const Providers: FC<ProvidersProps> = ({}) => {
return <div>Providers</div>
interface LayoutProps {
children: ReactNode
}

export default Providers
interface SidebarOption {
id: number
name: string
href: string
//Icon: Icon
}
const sidebarOptions: SidebarOption[] = [
{
id: 1,
name: 'Add friend',
href: '/dashboard/add',
}
]

const Layout = async ({children}: LayoutProps) => {
const session = await getServerSession(authOptions)
if(!session) notFound()
return <div className='w-full flex h-screen'>
<div className='flex h-full w-full max-w-xs grow flex-col gap-y-5 overflow-y-auto border-r border-gray-200 bg-white px-6 '>
<Link href='/dashboard' className='flex h-16 shirnk-0 items-center'></Link>

<div className='text-xs font-semibold leading-6 text-gray-400'>
Your chats
</div>
<nav className='flex flex-1 flex-col'>
<ul role='list' className='flex flex-1 flex-col gap-y-7'>
<li>
//chats that the user has
</li>
<li>
<div className='text-xs font-semibold leading-6 text-gray-400'>
Overview
</div>
<ul role='list' className='-mx-2 mt-2 space-y-1'>
{sidebarOptions.map((option) => {
return (
<li key={option.id}>
<Link href={option.href} className='text-gray-700 hover:text-blue-50 group flex gap-3 rounded-md p-2 text-sm leading-semibold'>
<span className='text-gray-400 border-gray-200 group-hover:border-blue-600 group-hover:text-blue-600 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg border-text-[0.625rem] font-medium bg-white'>
logo
</span>
<span className='truncate'>{option.name}</span>
</Link>
</li>
)
})}
</ul>
</li>
<li className='-mx-6 mt-auto flex items-center'>
<div className='flex flex-1 items-center gap-x-4 px-6 py-3 tex-sm font-semibold leading-6 text-gray-900'>
<div className='relative h-8 w-8 bg-gray-50'>
<Image fill
referrerPolicy='no-referrer'
className='rounded-full'
src={session.user.image || ''}
alt='Your profile picture'
/>
</div>
<span className='sr-only'>Your profile</span>
<div className='flex flex-col'>
<span aria-hidden='true' className=''>{session.user.name}</span>
<span className='text-xs text-zinc-400' aria-hidden='true'>{ session.user.email}</span>
</div>
</div>
<SignOutButton /*className='h-full aspect-square'/*//>
</li>
</ul>
</nav>
</div>
{children}
</div>
}

export default Layout

12 changes: 9 additions & 3 deletions app/api/friends/add/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,30 @@ import { fetchRedis } from '@/helpers/redis'
import { authOptions } from "@/lib/auth"
import { db } from '@/lib/db'
import { addFriendValidator } from "@/lib/validations/add-friend"
import { log } from 'console'
import { getServerSession } from "next-auth"
import {z} from "zod"
import fetchUserByEmail from '@/app/helpers/fetchUsersByEmail';

export async function POST(req: Request) {
try {
const body = await req.json()

const {email: emailToAdd} = addFriendValidator.parse(body.email) // if this parse fails a z error is going to be thrown

console.log("The email being passed is: " + emailToAdd)
console.log("The email that is passed is: " + emailToAdd)

const idToAdd = (await fetchRedis('get', `user:email:${emailToAdd}`)) as string

//const idToAdd = await fetchUserByEmail(emailToAdd);


console.log(`The id that is passed is: ${idToAdd}`)

if(!idToAdd) {
return new Response('This person does not exist', {status: 400} )
}



const session = await getServerSession(authOptions)

Expand Down Expand Up @@ -58,7 +62,8 @@ export async function POST(req: Request) {
}

//valid request, send friend request

console.log("A request will be sent ");

db.sadd(`user${idToAdd}:incoming_friend_requests`, session.user.id)

return new Response("OK")
Expand All @@ -67,6 +72,7 @@ export async function POST(req: Request) {
if(error instanceof z.ZodError) {
return new Response('Invalid request payload')
}
console.log(error);
return new Response('Invalid request payload', {status: 422})
}
}
19 changes: 19 additions & 0 deletions app/helpers/fetchUsersByEmail.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { fetchRedis } from '@/helpers/redis';
import { Redis } from '@upstash/redis';

async function fetchUserByEmail(email: string) {

const redis = new Redis({ url: 'https://fast-raptor-39621.upstash.io', token: 'AZrFASQgODJiNDRjNjgtNmFiOS00ODljLWE3MGYtZDY5Mzk3MzMzMzg4MjZlYjZiYTExZTczNDkxZTliMmI5NWM5MWRhZmEzMmM=' });

const key = `user:email:${email}`;

try {
const id = await redis.get(key) as string
return id;
} catch (error) {
console.error('Error fetching user by email:', error);
throw error;
}
}

export default fetchUserByEmail;
16 changes: 16 additions & 0 deletions components/Icons.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*import { LucideProps, UserPlus } from 'lucide-react'
export const Icons = {
Logo: (props: LucideProps) => (
<svg {...props} viewBox='0 0 2000 2000'>
<path
fill='currentColor'
d='m1976.678 964.142-1921.534-852.468c-14.802-6.571-32.107-3.37-43.577 8.046-11.477 11.413-14.763 28.703-8.28 43.532l365.839 836.751-365.839 836.749c-6.483 14.831-3.197 32.119 8.28 43.532 7.508 7.467 17.511 11.417 27.677 11.417 5.37 0 10.785-1.103 15.9-3.371l1921.533-852.466c14.18-6.292 23.322-20.349 23.322-35.861.001-15.514-9.141-29.571-23.321-35.861zm-1861.042-739.791 1664.615 738.489h-1341.737zm321.069 816.954h1334.219l-1655.287 734.35z'
/>
</svg>
),
UserPlus
}
export type Icon = keyof typeof Icons // turning the icons into Logo literals or userplus literals
*/
12 changes: 12 additions & 0 deletions components/ui/SignOutButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"use client"

import { FC } from 'react'

interface SignOutButtonProps {}

const SignOutButton: FC<SignOutButtonProps> = ({}) => {
//continue 2:49:16
return <div>Providers</div>
}

export default SignOutButton
10 changes: 6 additions & 4 deletions helpers/redis.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
const upstashRedisRestUrl = process.env.UPSTASH_REDIS_REST_URL
const authToken = process.env.USTASH_REDIS_REST_TOKEN
const authToken = process.env.UPSTASH_REDIS_REST_TOKEN as string

console.log('upstashRedisRestUrl:', upstashRedisRestUrl);
console.log('authToken:', authToken);

type Command = 'zrange' | 'sismember' | 'get' | 'smembers'

export async function fetchRedis(
command: Command,
...args: (string | number) [
]
...args: (string | number) []
) {
const commandUrl = `${upstashRedisRestUrl}/${command}/${args.join('/')}`

const response = await fetch(commandUrl, {
headers: {Authorization: `Bearer${process.env.UPSTASH_REDIS_REST_TOKEN}` },
headers: {Authorization: `Bearer ${authToken}` },
cache: 'no-store',
})

Expand Down
8 changes: 8 additions & 0 deletions lucide-react.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
declare module 'lucide-react' {
export interface IconProps {
size?: string | number;
color?: string;
}

export const IconName: React.FC<IconProps>;
}
3 changes: 3 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ const nextConfig = {
env: {
UPSTASH_REDIS_REST_URL: localEnv.UPSTASH_REDIS_REST_URL,
UPSTASH_REDIS_REST_TOKEN: localEnv.UPSTASH_REDIS_REST_TOKEN,
},
images: {
domains: ['avatars.githubusercontent.com']
}
}

Expand Down
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"axios": "^1.5.0",
"class-variance-authority": "^0.7.0",
"dotenv": "^16.3.1",
"lucide-react": "^0.276.0",
"next": "^13.4.4",
"next-auth": "^4.23.1",
"react": "18.2.0",
Expand Down

0 comments on commit 6d064af

Please sign in to comment.