Controller

import { Request, Response } from "express";
import { PrismaClient } from "../generated/prisma";

const prisma = new PrismaClient();

const testing = async (req: Request, res: Response) => {
    try {
      res.status(200).json({ 
        message: "Server berhasil connect" 
      });
    } catch (error) {
      console.error(error);
      res.status(500).json({ 
        error, 
        message: "Server tidak terhubung" 
      });
    }
  };

const getProducts = async (req: Request, res: Response) => {
    try {
      const products = await prisma.product.findMany();
      // const { sort = 'desc', sortBy = 'price' } = req.query;
        
        // const products = await prisma.product.findMany({
        //     orderBy: {
        //         [(sortBy as string)]: sort === 'desc' ? 'asc' : 'desc'
        //     }
        // });
      res.status(200).json({
        status: "success",
        data: products
      });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        status: "error",
        message: "Internal server error"
      });
    }
  };
  

const createProduct = async (req: Request, res: Response) => {
    try {
      const { name, price, stock } = req.body;
      
      const product = await prisma.product.create({
        data: {
          name,
          price,
          stock
        }
      });
  
      res.status(201).json({
        status: "success",
        data: product
      });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        status: "error", 
        message: "Internal server error"
      });
    }
  };

export {
    testing,
    getProducts,
    createProduct,
};

Last updated