Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create user session hook #730

Merged
merged 3 commits into from
Nov 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions frontend/jest.config.mjs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import nextJest from 'next/jest.js'

const createJestConfig = nextJest({
dir: './',
dir: './'
})

const config = {
testEnvironment: 'jsdom',
testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'],
setupFilesAfterEnv: ['./jest.setup.ts'],
moduleNameMapper: {
'@/(.*)': '<rootDir>/src/$1'
}
}

export default createJestConfig(config)
export default createJestConfig(config)
15 changes: 7 additions & 8 deletions frontend/src/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import NextAuth, { NextAuthOptions } from 'next-auth'
import KeycloakProvider from 'next-auth/providers/keycloak'

import { fetchFactory } from '@/infra/lib/apiClient'
import { getCurrentUser } from '@/infra/user/getCurrentUser'

export const authOptions: NextAuthOptions = {
providers: [
Expand All @@ -19,21 +20,19 @@ export const authOptions: NextAuthOptions = {
},
async session({ session, token }) {
session.accessToken = token.accessToken
session.user = { ...session.user, ...token.user }
return session
},
async jwt({ token, account, profile }) {
if (account && profile) {
token.accessToken = account.access_token
token.id = profile.id

const headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${token.accessToken}`
}
const response = await fetch(`${process.env.API_BASE}/v1/users/me`, { headers: { ...headers } })
const result = await response.json()
const apiClient = fetchFactory({ baseURL: process.env.API_BASE!, token: token.accessToken })

const user = await getCurrentUser(apiClient)

token.user = result
token.user = user
}
return token
}
Expand Down
5 changes: 2 additions & 3 deletions frontend/src/app/tasks/TaskForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@ import { TimePicker } from './components/TimePicker'
type TaskFormProps = {
projects: Array<Project>
taskTypes: Array<TaskType>
userId: number
}

export const TaskForm = ({ projects, taskTypes, userId }: TaskFormProps) => {
export const TaskForm = ({ projects, taskTypes }: TaskFormProps) => {
const {
task,
handleChange,
Expand All @@ -32,7 +31,7 @@ export const TaskForm = ({ projects, taskTypes, userId }: TaskFormProps) => {
selectStartTime,
handleSubmit,
formRef
} = useTaskForm({ userId })
} = useTaskForm()

return (
<Stack
Expand Down
10 changes: 3 additions & 7 deletions frontend/src/app/tasks/TaskList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,9 @@ import Box from '@mui/joy/Box'
import { useGetTasks, useDeleteTask } from './hooks/useTask'
import { TaskBox } from './components/Task'

type TaskListProps = {
userId: number
}

export const TaskList = ({ userId }: TaskListProps) => {
const tasks = useGetTasks(userId)
const { deleteTask } = useDeleteTask(userId)
export const TaskList = () => {
const tasks = useGetTasks()
const { deleteTask } = useDeleteTask()

return (
<Box
Expand Down
7 changes: 5 additions & 2 deletions frontend/src/app/tasks/__tests__/TaskForm.test.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { TaskForm } from '../TaskForm'
import { screen, renderWithUser, act } from '@/test-utils/test-utils'
import { useAddTask, useGetTasks } from '../hooks/useTask'
import { useGetCurrentUser } from '@/hooks/useGetCurrentUser/useGetCurrentUser'

jest.mock('../hooks/useTask')
jest.mock('@/hooks/useGetCurrentUser/useGetCurrentUser')

const setupTaskForm = () => {
const projects = [
Expand All @@ -25,15 +27,16 @@ const setupTaskForm = () => {
{ name: 'mock task type 2', slug: 'mock-test-2', active: true }
]

return renderWithUser(<TaskForm userId={0} projects={projects} taskTypes={taskTypes} />, {
return renderWithUser(<TaskForm projects={projects} taskTypes={taskTypes} />, {
advanceTimers: jest.advanceTimersByTime
})
}

describe('TasksPage', () => {
describe('TaskForm', () => {
beforeEach(() => {
;(useAddTask as jest.Mock).mockReturnValue({ addTask: () => {} })
;(useGetTasks as jest.Mock).mockReturnValue([])
;(useGetCurrentUser as jest.Mock).mockReturnValue({ id: 0 })

jest.useFakeTimers()
jest.spyOn(global, 'setInterval')
Expand Down
10 changes: 7 additions & 3 deletions frontend/src/app/tasks/hooks/useTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import { getTasks } from '@/infra/task/getTasks'
import { deleteTask } from '@/infra/task/deleteTask'
import { useClientFetch } from '@/infra/lib/useClientFetch'
import { format } from 'date-fns'
import { useGetCurrentUser } from '@/hooks/useGetCurrentUser/useGetCurrentUser'

export const useGetTasks = (userId: number) => {
export const useGetTasks = () => {
const apiClient = useClientFetch()
const { id: userId } = useGetCurrentUser()
const today = format(new Date(), 'yyyy-MM-dd')

const { data } = useQuery({
Expand All @@ -20,10 +22,11 @@ export const useGetTasks = (userId: number) => {
return data
}

export const useAddTask = (userId: number) => {
export const useAddTask = () => {
const apiClient = useClientFetch()
const queryClient = useQueryClient()
const { showError, showSuccess } = useAlert()
const { id: userId } = useGetCurrentUser()

const { mutate } = useMutation((task: TaskIntent) => createTask(task, apiClient), {
onSuccess: () => {
Expand All @@ -38,9 +41,10 @@ export const useAddTask = (userId: number) => {
return { addTask: mutate }
}

export const useDeleteTask = (userId: number) => {
export const useDeleteTask = () => {
const apiClient = useClientFetch()
const queryClient = useQueryClient()
const { id: userId } = useGetCurrentUser()
const { showError, showSuccess } = useAlert()

const { mutate } = useMutation((taskId: number) => deleteTask(taskId, apiClient), {
Expand Down
8 changes: 5 additions & 3 deletions frontend/src/app/tasks/hooks/useTaskForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import { useEffect, useRef, useCallback } from 'react'
import { useAddTask, useGetTasks } from './useTask'
import { TaskIntent, getOverlappingTasks } from '@/domain/Task'
import { useAlert } from '@/ui/Alert/useAlert'
import { useGetCurrentUser } from '@/hooks/useGetCurrentUser/useGetCurrentUser'

export const useTaskForm = ({ userId }: { userId: TaskIntent['userId'] }) => {
export const useTaskForm = () => {
const formRef = useRef<HTMLFormElement>(null)
const { addTask } = useAddTask(userId)
const { id: userId } = useGetCurrentUser()
const { addTask } = useAddTask()
const { showError } = useAlert()
const tasks = useGetTasks(userId)
const tasks = useGetTasks()

const { startTimer, stopTimer, seconds, minutes, hours, isTimerRunning } = useTimer()
const { formState, handleChange, resetForm } = useForm<TaskIntent>({
Expand Down
14 changes: 4 additions & 10 deletions frontend/src/app/tasks/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,16 @@ import { TaskList } from './TaskList'
import { TaskForm } from './TaskForm'
import { getProjects } from '@/infra/project/getProjects'
import { getTaskTypes } from '@/infra/taskType/getTaskTypes'
import { getCurrentUser } from '@/infra/user/getCurrentUser'
import { serverFetch } from '@/infra/lib/serverFetch'

const getPageData = async () => {
const apiClient = await serverFetch()

return await Promise.all([
getProjects(apiClient),
getTaskTypes(apiClient),
getCurrentUser(apiClient)
])
return await Promise.all([getProjects(apiClient), getTaskTypes(apiClient)])
}


export default async function Tasks() {
const [projects, taskTypes, currentUser] = await getPageData()
const [projects, taskTypes] = await getPageData()

return (
<Box
Expand All @@ -31,8 +25,8 @@ export default async function Tasks() {
padding: { xs: '0 8px', sm: 0 }
}}
>
<TaskForm projects={projects} taskTypes={taskTypes} userId={currentUser.id} />
<TaskList userId={currentUser.id} />
<TaskForm projects={projects} taskTypes={taskTypes} />
<TaskList />
</Box>
)
}
9 changes: 9 additions & 0 deletions frontend/src/hooks/useGetCurrentUser/useGetCurrentUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { useSession } from 'next-auth/react'

export const useGetCurrentUser = () => {
const { data } = useSession({
required: true
})

return data!.user
}
18 changes: 2 additions & 16 deletions frontend/src/infra/user/getCurrentUser.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,12 @@
import { User } from '@/domain/User'
import { ApiClient } from '../lib/apiClient'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/app/api/auth/[...nextauth]/route'

export const getCurrentUser = async (apiClient: ApiClient): Promise<User> => {
const [session, response] = await Promise.all([
getServerSession(authOptions),
apiClient('/v1/users/me')
])

if (!session) {
throw new Error('Failed to fetch Session')
}
const response = await apiClient('/v1/users/me')

if (!response.ok) {
throw new Error('Failed to fetch Current User')
}

const user = await response.json()

return {
...session.user,
...user
}
return await response.json()
}
4 changes: 1 addition & 3 deletions frontend/src/types/next-auth.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ declare module 'next-auth' {
*/
interface Session {
accessToken?: string
user: {
id?: string
} & DefaultSession['user']
user: User & DefaultSession['user']
}

/**
Expand Down