Skip to content

Commit

Permalink
Edit Tenant Models : add images_tenant
Browse files Browse the repository at this point in the history
  • Loading branch information
RobyYasirAmri committed Jun 11, 2024
1 parent 574ba0c commit 929d731
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE `Tenants` ADD COLUMN `image` VARCHAR(191) NULL;
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ model Tenants {
id Int @id @default(autoincrement())
user_id Int
name_tenants String
image String?
address_tenants String
location_lat Float
location_lng Float
Expand Down
83 changes: 77 additions & 6 deletions src/controllers/tenantController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,62 @@ const { PrismaClient } = require("@prisma/client");
import { TenantModels } from "../models/Models";
import { UsersModels } from "../models/Models";
import axios from "axios";
import { Storage } from "@google-cloud/storage";
import crypto from "crypto";
import logger from "../middlewares/logger";

const prisma = new PrismaClient();

// UPLOAD IMAGES TO GCS

const storage = new Storage();
const bucketName = process.env.GCS_BUCKET_NAME;

const uploadImageToGCS = async (file, folderName) => {
const bucket = storage.bucket(bucketName);
const fileName = `${folderName}/${crypto.randomBytes(16).toString("hex")}-${file.originalname}`;
const blob = bucket.file(fileName);

return new Promise((resolve, reject) => {
const blobStream = blob.createWriteStream({
resumable: false,
contentType: file.mimetype,
});

blobStream.on("finish", () => {
const publicUrl = `https://storage.googleapis.com/${bucket.name}/${blob.name}`;
resolve(publicUrl);
});

blobStream.on("error", (err) => {
reject(err);
});

blobStream.end(file.buffer);
});
};

// Delete folder from GCS
const deleteFolderFromGCS = async (folderName) => {
try {
const [files] = await storage.bucket(bucketName).getFiles({
prefix: folderName,
});

if (files.length === 0) {
logger.info(`No files found in folder ${folderName} to delete`);
return;
}

const deletePromises = files.map(file => file.delete());
await Promise.all(deletePromises);
logger.info(`Deleted folder ${folderName} from GCS`);
} catch (error) {
logger.error(`Error deleting folder from GCS: ${error.message}`);
throw new Error('Failed to delete folder from GCS');
}
};

// Membuat tenant baru
export const createTenant = async (req, res) => {
try {
Expand Down Expand Up @@ -61,11 +114,18 @@ export const createTenant = async (req, res) => {
const formattedAddress = locationData.formatted_address;
const { lat, lng } = locationData.geometry.location;

let imageUrl = null;
if (req.file) {
const folderName = `tenants/${name_tenants}/images_tenant`;
imageUrl = await uploadImageToGCS(req.file, folderName);
}

// Buat tenant baru
const tenant = await TenantModels.create({
data: {
user_id,
name_tenants,
image: imageUrl,
address_tenants: formattedAddress, // Store the formatted address
location_lat: lat, // Add latitude field
location_lng: lng, // Add longitude field
Expand Down Expand Up @@ -183,16 +243,24 @@ export const updateTenant = async (req, res) => {
const formattedAddress = locationData.formatted_address;
const { lat, lng } = locationData.geometry.location;

let updatedData = {
name_tenants,
address_tenants: formattedAddress,
location_lat: lat,
location_lng: lng,
};

if (req.file) {
const folderName = `tenants/${name_tenants}/images_tenant`;
const imageUrl = await uploadImageToGCS(req.file, folderName);
updatedData.image = imageUrl;
}

const tenant = await TenantModels.update({
where: {
id: parseInt(id),
},
data: {
name_tenants,
address_tenants: formattedAddress, // Store the formatted address
location_lat: lat, // Add latitude field
location_lng: lng, // Add longitude field
},
data: updatedData,
});

res.status(200).json({
Expand Down Expand Up @@ -226,6 +294,9 @@ export const deleteTenant = async (req, res) => {
});
}

// Delete tenant's image folder in GCS
await deleteFolderFromGCS(`tenants/${tenant.name_tenants}/images_tenant`);

await TenantModels.delete({
where: {
id: parseInt(id),
Expand Down
21 changes: 19 additions & 2 deletions src/routes/tenantRoutes.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
const express = require("express");
const tenant_controllers = express.Router();
const authCheck = require("../middlewares/AuthCheck");
import multer from "multer";

// Filter file untuk memastikan hanya gambar yang diizinkan
const imageFilter = (req, file, cb) => {
if (!file.mimetype.match(/^image\/(jpeg|png|gif|webp)$/)) {
console.error("Only image files are allowed!");
return cb(new Error("Only image files are allowed!"), false);
}
cb(null, true);
};

// Mengijinkan upload gambar dengan batasan 5MB
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
fileFilter: imageFilter,
});

import { createTenant, getAllTenants, getTenantById, updateTenant, deleteTenant } from "../controllers/tenantController"; // Sesuaikan dengan path controller Anda

tenant_controllers.post("/tenants", authCheck, createTenant);
tenant_controllers.post("/tenants", upload.single('image'), authCheck, createTenant);
tenant_controllers.get("/tenants", authCheck, getAllTenants);
tenant_controllers.get("/tenants/:id", authCheck, getTenantById);
tenant_controllers.patch("/tenants/:id", authCheck, updateTenant);
tenant_controllers.patch("/tenants/:id", upload.single('image'), authCheck, updateTenant);
tenant_controllers.delete("/tenants/:id", authCheck, deleteTenant);

export default tenant_controllers;

0 comments on commit 929d731

Please sign in to comment.