tambahannya

This commit is contained in:
bipproduction
2025-02-19 17:41:56 +08:00
parent 0d4a8329d7
commit 9bde6a2a06
74 changed files with 1079 additions and 186 deletions

View File

@@ -0,0 +1,20 @@
import fs from "fs/promises";
import path from "path";
async function imgDel({
name,
UPLOAD_DIR_IMAGE,
}: {
name: string;
UPLOAD_DIR_IMAGE: string;
}) {
try {
await fs.unlink(path.join(UPLOAD_DIR_IMAGE, name));
return "ok";
} catch (error) {
console.log(error);
return "error";
}
}
export default imgDel;

View File

@@ -0,0 +1,61 @@
import fs from "fs/promises";
import path from "path";
import sharp from "sharp";
async function img({
name,
UPLOAD_DIR_IMAGE,
ROOT,
size,
}: {
name: string;
UPLOAD_DIR_IMAGE: string;
ROOT: string;
size?: number; // Ukuran opsional (tidak ada default)
}) {
const completeName = path.basename(name); // Nama file lengkap
const ext = path.extname(name).toLowerCase(); // Ekstensi file dalam huruf kecil
// const fileNameWithoutExt = path.basename(name, ext); // Nama file tanpa ekstensi
// Default image jika terjadi kesalahan
const noImage = path.join(ROOT, "public/no-image.jpg");
// Validasi ekstensi file
if (![".jpg", ".jpeg", ".png"].includes(ext)) {
console.warn(`Ekstensi file tidak didukung: ${ext}`);
return new Response(await fs.readFile(noImage), {
headers: { "Content-Type": "image/jpeg" },
});
}
try {
// Path ke file asli
const filePath = path.join(UPLOAD_DIR_IMAGE, completeName);
// Periksa apakah file ada
await fs.stat(filePath);
// Metadata gambar asli
const metadata = await sharp(filePath).metadata();
// Proses resize menggunakan sharp
const resizedImageBuffer = await sharp(filePath)
.resize(size || metadata.width) // Gunakan size jika diberikan, jika tidak gunakan width asli
.toBuffer();
return new Response(resizedImageBuffer, {
headers: {
"Cache-Control": "public, max-age=3600, stale-while-revalidate=600",
"Content-Type": "image/jpeg",
},
});
} catch (error) {
console.error(`Gagal memproses file: ${name}`, error);
// Jika file tidak ditemukan atau gagal diproses, kembalikan default image
return new Response(await fs.readFile(noImage), {
headers: { "Content-Type": "image/jpeg" },
});
}
}
export default img;

View File

@@ -0,0 +1,30 @@
import fs from "fs/promises";
async function imgs({
search = "",
page = 1,
count = 20,
UPLOAD_DIR_IMAGE,
}: {
search?: string;
page?: number;
count?: number;
UPLOAD_DIR_IMAGE: string;
}) {
const files = await fs.readdir(UPLOAD_DIR_IMAGE);
return files
.filter(
(file) =>
file.endsWith(".jpg") || file.endsWith(".png") || file.endsWith(".jpeg")
)
.filter((file) => file.includes(search))
.slice((page - 1) * count, page * count)
.map((file) => ({
name: file,
url: `/api/img/${file}`,
total: files.length,
}));
}
export default imgs;

View File

@@ -0,0 +1,12 @@
export async function uplCsvSingle({
fileName,
file,
}: {
fileName: string;
file: File;
}) {
const textFile = await file.text();
console.log(fileName, textFile);
return "ok";
}

View File

@@ -0,0 +1,16 @@
async function uplCsv({ files }: { files: File[] }) {
if (!Array.isArray(files) || files.length === 0) {
throw new Error("Tidak ada file yang diunggah");
}
for (const file of files) {
const textFile = await file.text();
const fileName = file.name;
console.log(textFile, fileName);
}
return "ok";
}
export default uplCsv;

View File

@@ -0,0 +1,32 @@
import { nanoid } from "nanoid";
import fs from "fs/promises";
import path from "path";
import _ from "lodash";
export async function uplImgSingle({
fileName,
file,
UPLOAD_DIR_IMAGE,
}: {
fileName: string;
file: File;
UPLOAD_DIR_IMAGE: string;
}) {
if (!fileName || typeof fileName !== "string" || fileName.trim() === "") {
console.warn(`Nama file tidak valid: ${fileName}`);
fileName = nanoid() + ".jpg";
}
const ext = path.extname(fileName).toLowerCase();
const fileNameWithoutExt = path.basename(fileName, ext);
const fileNameKebabCase = _.kebabCase(fileNameWithoutExt) + ext;
try {
const buffer = Buffer.from(await file.arrayBuffer());
const filePath = path.join(UPLOAD_DIR_IMAGE, fileNameKebabCase);
await fs.writeFile(filePath, buffer);
return filePath;
} catch (error) {
console.log(error);
return "error";
}
}

View File

@@ -0,0 +1,52 @@
import path from "path";
import fs from "fs/promises";
import { nanoid } from "nanoid";
async function uplImg({
files,
UPLOAD_DIR_IMAGE,
}: {
files: File[];
UPLOAD_DIR_IMAGE: string;
}) {
// Validasi input
if (!Array.isArray(files) || files.length === 0) {
throw new Error("Tidak ada file yang diunggah");
}
for (const file of files) {
let fileName = file.name;
// Validasi nama file
if (!fileName || typeof fileName !== "string" || fileName.trim() === "") {
console.warn(`Nama file tidak valid: ${fileName}`);
fileName = nanoid() + ".jpg";
}
// Sanitasi nama file untuk mencegah path traversal
const sanitizedFileName = sanitizeFileName(fileName);
try {
// Konversi file ke buffer
const buffer = Buffer.from(await file.arrayBuffer());
// Tulis file ke direktori uploads
const filePath = path.join(UPLOAD_DIR_IMAGE, sanitizedFileName);
await fs.writeFile(filePath, buffer);
console.log(`File berhasil diunggah: ${sanitizedFileName}`);
} catch (error) {
console.error(`Gagal mengunggah file ${fileName}:`, error);
throw new Error(`Gagal mengunggah file: ${fileName}`);
}
}
return "ok";
}
// Fungsi untuk membersihkan nama file dari karakter yang tidak aman
function sanitizeFileName(fileName: string): string {
return fileName.replace(/[^a-zA-Z0-9._\-]/g, "_");
}
export default uplImg;

View File

@@ -1,32 +1,171 @@
import prisma from "@/lib/prisma";
import cors, { HTTPMethod } from "@elysiajs/cors";
import swagger from "@elysiajs/swagger";
import { Elysia } from "elysia";
import { Elysia, t } from "elysia";
import getPotensi from "./_lib/get-potensi";
import img from "./_lib/img";
import fs from "fs/promises";
import path from "path";
import uplImg from "./_lib/upl-img";
import imgs from "./_lib/imgs";
import uplCsv from "./_lib/upl-csv";
import imgDel from "./_lib/img-del";
import { uplImgSingle } from "./_lib/upl-img-single";
import { uplCsvSingle } from "./_lib/upl-csv-single";
const ROOT = process.cwd();
if (!process.env.WIBU_UPLOAD_DIR)
throw new Error("WIBU_UPLOAD_DIR is not defined");
const UPLOAD_DIR = path.join(ROOT, process.env.WIBU_UPLOAD_DIR);
const UPLOAD_DIR_IMAGE = path.join(UPLOAD_DIR, "image");
// create uploads dir
fs.mkdir(UPLOAD_DIR, {
recursive: true,
}).catch(() => {});
// create image uploads dir
fs.mkdir(UPLOAD_DIR_IMAGE, {
recursive: true,
}).catch(() => {});
const corsConfig = {
origin: "*",
methods: ["GET", "POST", "PATCH", "DELETE", "PUT"] as HTTPMethod[],
allowedHeaders: "*",
exposedHeaders: "*",
maxAge: 5,
credentials: true,
origin: "*",
methods: ["GET", "POST", "PATCH", "DELETE", "PUT"] as HTTPMethod[],
allowedHeaders: "*",
exposedHeaders: "*",
maxAge: 5,
credentials: true,
};
async function layanan() {
const data = await prisma.layanan.findMany();
return { data };
const data = await prisma.layanan.findMany();
return { data };
}
const ApiServer = new Elysia()
.use(swagger({ path: "/api/docs" }))
.use(cors(corsConfig))
.group("/api", app => app
.get("/layanan", layanan)
.get("/potensi", getPotensi)
)
.use(swagger({ path: "/api/docs" }))
.use(cors(corsConfig))
.onError(({ code }) => {
if (code === "NOT_FOUND") {
return {
status: 404,
body: "Route not found :(",
};
}
})
.group("/api", (app) =>
app
.get("/layanan", layanan)
.get("/potensi", getPotensi)
.get(
"/img/:name",
({ params, query }) => {
return img({
name: params.name,
UPLOAD_DIR_IMAGE,
ROOT,
size: query.size,
});
},
{
params: t.Object({
name: t.String(),
}),
query: t.Optional(
t.Object({
size: t.Optional(t.Number()),
})
),
}
)
.delete(
"/img/:name",
({ params }) => {
return imgDel({
name: params.name,
UPLOAD_DIR_IMAGE,
});
},
{
params: t.Object({
name: t.String(),
}),
}
)
.get(
"/imgs",
({ query }) => {
return imgs({
search: query.search,
page: query.page,
count: query.count,
UPLOAD_DIR_IMAGE,
});
},
{
query: t.Optional(
t.Object({
page: t.Number({ default: 1 }),
count: t.Number({ default: 10 }),
search: t.String({ default: "" }),
})
),
}
)
.post(
"/upl-img",
({ body }) => {
console.log(body.title);
return uplImg({ files: body.files, UPLOAD_DIR_IMAGE });
},
{
body: t.Object({
title: t.String(),
files: t.Files({ multiple: true }),
}),
}
)
.post(
"/upl-img-single",
({ body }) => {
return uplImgSingle({
fileName: body.name,
file: body.file,
UPLOAD_DIR_IMAGE,
});
},
{
body: t.Object({
name: t.String(),
file: t.File(),
}),
}
)
.post(
"/upl-csv-single",
({ body }) => {
return uplCsvSingle({ fileName: body.name, file: body.file });
},
{
body: t.Object({
name: t.String(),
file: t.File(),
}),
}
)
.post(
"/upl-csv",
({ body }) => {
return uplCsv({ files: body.files });
},
{
body: t.Object({
files: t.Files(),
}),
}
)
);
export const GET = ApiServer.handle;
export const POST = ApiServer.handle;
@@ -34,5 +173,4 @@ export const PATCH = ApiServer.handle;
export const DELETE = ApiServer.handle;
export const PUT = ApiServer.handle;
export type AppServer = typeof ApiServer
export type AppServer = typeof ApiServer;