Skip to content

Commit

Permalink
perf(api): search user id only if needed (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jayllyz authored Apr 14, 2024
1 parent 01a9db9 commit a794957
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 51 deletions.
1 change: 0 additions & 1 deletion apps/api/src/handlers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { getCookie, setCookie } from 'hono/cookie';
import { HTTPException } from 'hono/http-exception';
import { supabase } from '../libs/supabase.js';
import { zodErrorHook } from '../libs/zodError.js';
import authMiddleware from '../middlewares/auth.js';
import { loginUser, refreshTokens, signupUser } from '../routes/auth.js';

export const auth = new OpenAPIHono({
Expand Down
48 changes: 9 additions & 39 deletions apps/api/src/handlers/blog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,8 @@ import {
updateComment,
updatePost,
} from '../routes/blog.js';

type Variables = {
user: {
id: number;
};
};
import { getUserId } from '../utils/context.js';
import type { Variables } from '../validators/general.js';

export const blog = new OpenAPIHono<{ Variables: Variables }>({
defaultHook: zodErrorHook,
Expand Down Expand Up @@ -47,23 +43,9 @@ blog.openapi(getPost, async (c) => {

blog.openapi(createPost, async (c) => {
const { title, content } = c.req.valid('json');
const user = c.get('user')?.id;

if (!user) {
return c.json({ error: 'User not found' }, 404);
}
const id_user = await getUserId(c);

const { data: idUser } = await supabase.from('USERS').select('id').eq('id_auth', user).single();

if (!idUser) {
return c.json({ error: 'User not found' }, 404);
}

const { data, error } = await supabase
.from('POSTS')
.insert({ title, content, id_user: idUser?.id })
.select()
.single();
const { data, error } = await supabase.from('POSTS').insert({ title, content, id_user }).select().single();

if (error || !data) {
return c.json({ error: error?.message || 'Failed to create post' }, 500);
Expand Down Expand Up @@ -98,20 +80,12 @@ blog.openapi(deletePost, async (c) => {
blog.openapi(commentOnPost, async (c) => {
const { id } = c.req.valid('param');
const { content } = c.req.valid('json');
const user = c.get('user')?.id;
const id_user = await getUserId(c);

if (!user) {
return c.json({ error: 'User not found' }, 404);
}

const { data, error } = await supabase
.from('COMMENTS')
.insert({ content, id_post: id, id_user: user })
.select()
.single();
const { data, error } = await supabase.from('COMMENTS').insert({ content, id_post: id, id_user }).select().single();

if (error || !data) {
return c.json({ error: 'Failed to create comment' }, 400);
return c.json({ error: 'Post not found' }, 404);
}

return c.json(data, 201);
Expand All @@ -131,15 +105,11 @@ blog.openapi(getComments, async (c) => {
blog.openapi(createResponse, async (c) => {
const { id_post, id_comment } = c.req.valid('param');
const { content } = c.req.valid('json');
const user = c.get('user')?.id;

if (!user) {
return c.json({ error: 'User not found' }, 404);
}
const id_user = await getUserId(c);

const { data, error } = await supabase
.from('COMMENTS')
.insert({ content, id_post, id_response: id_comment, id_user: user })
.insert({ content, id_post, id_response: id_comment, id_user })
.select()
.single();

Expand Down
13 changes: 2 additions & 11 deletions apps/api/src/middlewares/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,8 @@ const authMiddleware: MiddlewareHandler = async (c, next) => {
const { data, error } = await supabase.auth.getUser(access_token);

if (data?.user) {
const { data: idUser } = await supabase.from('USERS').select('id').eq('id_auth', data.user.id).single();

if (!idUser) throw new HTTPException(404, { message: 'User not found' });

c.set('user', {
id: idUser?.id,
id_auth: data.user.id,
email: data.user.email,
updated_at: data.user.updated_at,
created_at: data.user.created_at,
Expand All @@ -30,15 +26,10 @@ const authMiddleware: MiddlewareHandler = async (c, next) => {
});

if (refreshError) throw new HTTPException(403, { message: 'Error while refreshing token' });
if (!refreshed.user) throw new HTTPException(403, { message: 'No user found' });

const { data: idUser } = await supabase.from('USERS').select('id').eq('id_auth', refreshed.user.id).single();

if (!idUser) throw new HTTPException(404, { message: 'User not found' });

if (refreshed.user) {
c.set('user', {
id: idUser?.id,
id_auth: refreshed.user.id,
email: refreshed.user.email,
updated_at: refreshed.user.updated_at,
created_at: refreshed.user.created_at,
Expand Down
13 changes: 13 additions & 0 deletions apps/api/src/utils/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { Context } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { supabase } from '../libs/supabase.js';

export async function getUserId(c: Context): Promise<number> {
const id_auth = c.get('user')?.id_auth;

const { data: user } = await supabase.from('USERS').select('id').eq('id_auth', id_auth).single();

if (!user) throw new HTTPException(404, { message: 'User not found' });

return user.id;
}
9 changes: 9 additions & 0 deletions apps/api/src/validators/general.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { z } from 'zod';

export type Variables = {
user: {
id_auth: number;
email: string;
updated_at: string;
created_at: string;
};
};

export const serverErrorSchema = {
description: 'Internal server error',
content: {
Expand Down

0 comments on commit a794957

Please sign in to comment.