Files
sistem-desa-mandiri/src/app/api/mobile/banner/route.ts
amel 228b6f944f upd: api mobile
Deskripsi:
- api create banner upload gambar

No Issues
2025-05-14 17:37:43 +08:00

88 lines
3.2 KiB
TypeScript

import { DIR, funUploadFile, funViewDir, prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import { createLogUser } from "@/module/user";
import { NextResponse } from "next/server";
// GET ALL BANNER
export async function GET(request: Request) {
try {
const { searchParams } = new URL(request.url)
const userMobile = searchParams.get("user")
if (userMobile == "null" || userMobile == undefined || userMobile == "") {
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
}
const user = await funGetUserById({ id: userMobile })
const data = await prisma.bannerImage.findMany({
where: {
isActive: true,
idVillage: user.idVillage
},
orderBy: {
createdAt: 'desc'
}
});
return NextResponse.json({ success: true, message: "Berhasil mendapatkan banner", data }, { status: 200 });
} catch (error) {
console.error(error);
return NextResponse.json({ success: false, message: "Gagal mendapatkan data banner, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
}
}
// CREATE BANNER
export async function POST(request: Request) {
try {
console.log('masuklas')
console.log(request)
const body = await request.formData()
const fileAwal = body.get("file");
const file = JSON.parse(fileAwal as string)
const fileFix = file as File
const fileCoba = new File([fileFix], fileFix.name, { type: fileFix.type});
const data = body.get("data");
console.log(body, fileCoba)
const { title, user } = JSON.parse(data as string)
if (user == "null" || user == undefined || user == "") {
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
}
const userLogin = await funGetUserById({ id: user })
const fExt = fileCoba.name.split(".").pop()
const fName = fileCoba.name.replace("." + fExt, "")
const newFile = new File([fileCoba], fileCoba.name, { type: fileCoba.type });
const ini = funViewDir({ dirId: DIR.user })
const upload = await funUploadFile({ file: fileCoba, dirId: DIR.banner })
if (upload.success) {
const create = await prisma.bannerImage.create({
data: {
title: title,
idVillage: userLogin.idVillage,
extension: String(fExt),
image: upload.data.id
}
})
// create log user
const log = await createLogUser({ act: 'CREATE', desc: 'User menambah data banner baru', table: 'bannerImage', data: String(userLogin.id) })
return Response.json({ success: true, message: 'Sukses menambah data banner' }, { status: 200 });
} else {
return Response.json({ success: false, message: 'Gagal menambah data banner' }, { status: 200 });
}
} catch (error) {
console.error(error);
return NextResponse.json({ success: false, message: "Gagal menambahkan banner, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
}
}