បន្ទាប់ពីបានបញ្ចូលទិន្នន័យនៃការផ្សាយទៅក្នុងមូលដ្ឋានទិន្នន័យ MongoDB រួចហើយ យើងអាចស្រង់យកទិន្នន័យទាំងនោះមកបង្ហាញនៅលើផ្នែកខាងក្រោមនៃទំព័រគ្រប់គ្រង ដោយសរសេរកូដនៅក្នុងឯកសារ index.astro ដូចខាងក្រោម៖
<!--src/pages/admin/index.astro-->
---
import Base from "../../layouts/admin/Base.astro"
import Post from "../../layouts/admin/Post.astro"
const { userAuth, prisma, setting } = Astro.locals
if(!userAuth?.userId){ return Astro.redirect('/login') }
import post from "../../data/post.js"
const total = await post.count({prisma})
const items = await post.getPosts({prisma}, setting.adminItems)
const posts = items.map((post)=>{post.date = new Date(post.date).toLocaleDateString('it-IT')
return post })
---
<Base pageTitle="ទំព័រគ្រប់គ្រង" total={total} items={posts} type="post">
<Post/>
</Base>
// src/data/post.js
class Post{
async count(req, query={}){
return await req.prisma.post.count(query)
}
async create(req){
const categories = req.body.categories
let Categories = []
if(categories.includes(',')){
let str = categories.replace(/\s+/g, "")
Categories = str.split(',')
}else{
Categories = [categories]
}
const new_post = {
title: req.body.title,
content: req.body.content,
categories: Categories,
thumb: req.body.thumb,
date: req.body.datetime,
videos: req.body.videos,
userid: req.userAuth.userId,
}
await req.prisma.post.create({ data: new_post })
}
async getPosts(req, amount){
return await req.prisma.post.findMany({
take: amount,
orderBy: [{ date: "desc" }, { id: "desc" }]
})
}
async getPost(req){
return await req.prisma.post.findUnique({ where: {id: req.params.id }})
}
}
export default new Post()
<!--src/layouts/admin/Bottom.astro-->
---
const { total=0, items=[], type='post' } = Astro.props
---
<section class="max-w-5xl mx-auto md:px-0 px-2">
<div class="text-center bg-teal-100 mt-2 py-2">
ទាំងអស់មានចំនួនៈ {total}
</div>
<ul id="item-listing" class="grid md:grid-cols-2 grid-cols-1 gap-2 py-2 text-gray-600">
{items.map((item, i)=>(
<li class="bg-teal-100 grid grid-cols-[20%_60%_15%] gap-x-2 items-center group">
<a class="relative pt-[56.25%] overflow-hidden" href=`/${type}/${item.id}`>
<img class="absolute top-0 left-0 w-full min-h-full"
src={item.thumb}
/>
{item.videos &&
<img class="absolute top-1/2 left-1/2 min-h-auto w-1/4 -translate-x-1/2 -translate-y-1/2"
src="/images/play.png"
/>
}
</a>
<div class="truncate">
<a href=`/${type}/${item.id}`>
{item.title}
</a>
<div>{item.date}</div>
</div>
<div class="flex flex-row">
<a class="block w-1/2" href=`/api/${type}/edit/${item.id}`>
<img class="invisible group-hover:visible" src="/images/edit.png" />
</a>
<a id="" class="delete block w-1/2" href=`/api/${type}/delete/${item.id}`>
<img class="invisible group-hover:visible" src="/images/delete.png" />
</a>
</div>
</li>
))}
<script>
$('#item-listing .delete').on('click', function () {
return confirm('តើពិតជាចង់លុប?')
})
</script>
</ul>
<div class="bg-teal-100 py-2 mb-5">
<img class="mx-auto hover:opacity-75 cursor-pointer" src="/images/load-more.png" />
</div>
</section>