From 9479e62c415dc3710f0e5a4b5003e0cd99137d9d Mon Sep 17 00:00:00 2001 From: Lukas Lanzner Date: Mon, 2 Dec 2024 20:47:00 +0100 Subject: [PATCH] feat(friends): implement POST `/user/friends` endpoint for sending friend requests, and moved types file --- server/api/v1/user/friends/index.get.ts | 2 +- server/api/v1/user/friends/index.post.ts | 38 +++++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/server/api/v1/user/friends/index.get.ts b/server/api/v1/user/friends/index.get.ts index 69e8b52..9356818 100644 --- a/server/api/v1/user/friends/index.get.ts +++ b/server/api/v1/user/friends/index.get.ts @@ -1,5 +1,5 @@ import {serverSupabaseServiceRole, serverSupabaseUser} from "#supabase/server"; -import type {FriendError, GetFriendParam, GetFriendsResponse} from "~/types/api/responses/user.friends.response"; +import type {FriendError, GetFriendParam, GetFriendsResponse} from "~/types/api/user.friends"; // Not relative to userid because you should always only be able to see your own friends // User id can be grabbed from the access token diff --git a/server/api/v1/user/friends/index.post.ts b/server/api/v1/user/friends/index.post.ts index 2ab0ba0..fe7bed2 100644 --- a/server/api/v1/user/friends/index.post.ts +++ b/server/api/v1/user/friends/index.post.ts @@ -1 +1,37 @@ -// send friend invite \ No newline at end of file +// send friend invite +import {z} from 'zod' +import {serverSupabaseServiceRole, serverSupabaseUser} from "#supabase/server"; +import type {SendFriendRequestParam} from "~/types/api/user.friends"; + +const userSchema = z.object({ + receiver_id: z.string().uuid() +}) + +export default defineEventHandler(async (event) => { + // validate post-request body + const result = await readValidatedBody(event, body => userSchema.safeParse(body)) + if (!result.success) { + setResponseStatus(event, 400); + return {error: result.error.issues}; + } + + // Require user to be authenticated + const user = await serverSupabaseUser(event); + if (!user?.id) { + setResponseStatus(event, 401); + return {error: 'unauthenticated'}; + } + + // Send request + const client = serverSupabaseServiceRole(event); + const param: SendFriendRequestParam = {sender_id: user.id, receiver_id: result.data.receiver_id}; + const {error} = await client.rpc('send_friend_request', param as never); + + // Handle errors + if (error) { + setResponseStatus(event, 500); + return {error: error.message}; + } + + return {}; +}); \ No newline at end of file