Skip to content

Commit

Permalink
Adding some required folder structure
Browse files Browse the repository at this point in the history
  • Loading branch information
Isztof committed Sep 10, 2023
1 parent f62b417 commit 7f161c7
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 8 deletions.
Empty file.
Empty file.
1 change: 0 additions & 1 deletion app/(map)/map/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const page = async ({}) => {

const session = await getServerSession(authOptions)
return (
<div>
<div style={{backgroundColor: "whitesmoke"}}>
<h1>My Page</h1>
<pre> {JSON.stringify(session)}</pre>
Expand Down
72 changes: 72 additions & 0 deletions app/api/friends/add/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { fetchRedis } from '@/helpers/redis'
import { authOptions } from "@/lib/auth"
import { db } from '@/lib/db'
import { addFriendValidator } from "@/lib/validations/add-friend"
import { getServerSession } from "next-auth"
import {z} from "zod"

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)

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

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)

if(!session) {
return new Response('Unauthorized', {status: 401})
}


//const data = await RESTResponse.json() as {result: string}


if(idToAdd === session.user.id) {
return new Response('You cannot add yourself as a friend', {
status:400,
})
}

//check if user is already added
const isAlreadyAddded = await (fetchRedis('sismember', `user:${idToAdd}:incoming_friend_requests`, session.user.id)) as 0 | 1

if (isAlreadyAddded) {
return new Response('Already added this user', {status: 400})
}
//const idToAdd = data.result

//check if user is already in the friends list
const isAlreadyFriends = (await fetchRedis(
'sismember', `user:${session.user.id}:friends`, // we are checking in the friends list of the user who is already logged in whtether the id to add already exists
idToAdd
)) as 0 | 1

if (isAlreadyFriends) {
return new Response('Already Friends with this user')
}

//valid request, send friend request

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

return new Response("OK")

} catch (error) {
if(error instanceof z.ZodError) {
return new Response('Invalid request payload')
}
return new Response('Invalid request payload', {status: 422})
}
}
3 changes: 0 additions & 3 deletions app/api/hello/route.ts

This file was deleted.

2 changes: 1 addition & 1 deletion components/ui/AddFriendButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const AddFriendButton: FC<AddFriendButtonProps> = ({}) => {
const addFriend = async (email: string) => {
try {
const validatedEmail = addFriendValidator.parse({email})
await axios.post('/api/fiends/add', {
await axios.post('/api/friends/add', {
email: validatedEmail,
})
setShowSuccessState(true)
Expand Down
Empty file.
7 changes: 7 additions & 0 deletions helpers/get-friends-by-user-id.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { fetchRedis } from "./redis"

export const getFriendsByUserId = async (userId: string) => {
//retrieve friends for current user
//const friendIds = fetchRedis('smembers', `user:${userId}:friends`) as string[]

}
23 changes: 23 additions & 0 deletions helpers/redis.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const upstashRedisRestUrl = process.env.UPSTASH_REDIS_REST_URL
const authToken = process.env.USTASH_REDIS_REST_TOKEN

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

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

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

if(!response.ok) {
throw new Error(`Error executing Redis command: ${response.statusText}`)
}
const data = await response.json()
return data.result
}
3 changes: 0 additions & 3 deletions lib/validations/add-friend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,3 @@ export const addFriendValidator = z.object({
email: z.string().email(),
})

const random = {
idk: 'asd',
}

0 comments on commit 7f161c7

Please sign in to comment.