Skip to content

Commit

Permalink
Add pagination to logs
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmed0saber committed May 14, 2024
1 parent 59353da commit 66e5e0a
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 18 deletions.
47 changes: 35 additions & 12 deletions app/admin/logs/page.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,51 @@
'use client'

import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import styles from './style.module.css'
import { getSession, removeSession } from '@/utils/session-storage'

export default function page() {
const [logs, setLogs] = useState([])
const [isLoading, setIsLoading] = useState(true)
const [isDone, setIsDone] = useState(false)
const skip = useRef(0)
const user = useRef(getSession({ key: "current-user", defaultValue: null }))
const router = useRouter()

useEffect(() => {
getLogs()
}, [])
const controller = new AbortController()
if (!user.current) {
return router.push("/admin")
}

const getLogs = async () => {
const user = getSession({ key: "current-user", defaultValue: null })
getLogs({ signal: controller.signal })

if (!user) {
return router.push("/admin")
return () => {
controller.abort({ message: "Component Unmounted!" })
}
}, [])

const username = user.username
const password = user.password
const getLogs = async ({ signal }) => {
setIsLoading(true)

try {
const res = await fetch("/api/admin/logs", {
const res = await fetch(`/api/admin/logs?skip=${skip.current}`, {
signal,
headers: {
"Authorization": `Basic ${username}:${password}`
"Authorization": `Basic ${user.current.username}:${user.current.password}`
}
})

if (res.ok) {
const data = await res.json()
setLogs(data)
if (data.logs.length === 0) {
setIsDone(true)
return
}

setLogs(prev => [...prev, ...data.logs])
skip.current = data.skip
} else {
if (res.status === 401) {
console.error("Authorization failed: Invalid username or password")
Expand All @@ -44,6 +57,8 @@ export default function page() {
}
} catch (error) {
console.error("Fetch error:", error.message)
} finally {
setIsLoading(false)
}
}

Expand Down Expand Up @@ -76,6 +91,14 @@ export default function page() {
</div>
))}
</div>
{isLoading | logs.length === 0 | isDone ? null : (
<button
className='btn-dark mt-3'
onClick={getLogs}
>
تحميل المزيد
</button>
)}
</section>
</main>
)
Expand Down
2 changes: 1 addition & 1 deletion app/admin/logs/style.module.css
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
.logsContainer {
margin-top: 12px;
display: flex;
flex-direction: column-reverse;
flex-direction: column;
gap: 12px;
}

Expand Down
7 changes: 4 additions & 3 deletions app/api/admin/logs/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import { getLogs } from "../../utils/database/logs"

export const dynamic = 'force-dynamic'

export async function GET() {
const logs = await getLogs()
export async function GET(req) {
const skip = parseInt(req.nextUrl.searchParams.get("skip"))
const logs = await getLogs({ skip })

return new Response(
JSON.stringify(logs),
JSON.stringify({ logs, skip: skip + 3 }),
{ status: 200, headers: { "Content-Type": "application/json" } }
)
}
5 changes: 3 additions & 2 deletions app/api/utils/database/logs.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ const addLog = async (log) => {
.insertOne(log)
}

const getLogs = async () => {
const getLogs = async ({ skip } = { skip: 0 }) => {
const recorded_logs = await databaseConnection
.collection(process.env.LOGGING_MODEL)
.find({}, { projection: { _id: 0 } })
.find({}, { projection: { _id: 0 }, limit: 3, skip })
.sort({ _id: -1 })
.toArray()

return recorded_logs
Expand Down
4 changes: 4 additions & 0 deletions utils/session-storage.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
const getSession = ({ key, defaultValue } = {}) => {
if (typeof window === "undefined") {
return null
}

const storedSession = sessionStorage.getItem(key)
if (storedSession) {
return JSON.parse(storedSession)
Expand Down

0 comments on commit 66e5e0a

Please sign in to comment.