import { Text, Fieldset, Spacer, Link } from "@geist-ui/core" import { Post, User } from "@lib/types" import Cookies from "js-cookie" import { useEffect, useState } from "react" import useSWR from "swr" import styles from "./admin.module.css" import PostModal from "./post-modal-link" export const adminFetcher = (url: string) => fetch(url, { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Bearer ${Cookies.get("drift-token")}` } }).then((res) => res.json()) const Admin = () => { const { data: posts, error: postsError } = useSWR( "/server-api/admin/posts", adminFetcher ) const { data: users, error: usersError } = useSWR( "/server-api/admin/users", adminFetcher ) const [postSizes, setPostSizes] = useState<{ [key: string]: number }>({}) const byteToMB = (bytes: number) => Math.round((bytes / 1024 / 1024) * 100) / 100 useEffect(() => { if (posts) { // sum the sizes of each file per post const sizes = posts.reduce((acc, post) => { const size = post.files?.reduce((acc, file) => acc + file.html.length, 0) || 0 return { ...acc, [post.id]: byteToMB(size) } }, {}) setPostSizes(sizes) } }, [posts]) return (
Administration
Users {users && {users.length} users} {!users && Loading...} {usersError && An error occured} {users && ( {users?.map((user) => ( ))}
Username Posts Created Role
{user.username} {user.posts?.length} {new Date(user.createdAt).toLocaleDateString()}{" "} {new Date(user.createdAt).toLocaleTimeString()} {user.role}
)}
Posts {posts && {posts.length} posts} {!posts && Loading...} {postsError && An error occured} {posts && ( {posts?.map((post) => ( ))}
Title Visibility Created Author Size
{post.visibility} {new Date(post.createdAt).toLocaleDateString()}{" "} {new Date(post.createdAt).toLocaleTimeString()} {post.users?.length ? ( post.users[0].username ) : ( Deleted )} {postSizes[post.id] ? `${postSizes[post.id]} MB` : ""}
)} {Object.keys(postSizes).length && (
Total size:{" "} {Object.values(postSizes).reduce((prev, curr) => prev + curr)} MB
)}
) } export default Admin