From 7cc24a5149248aff12f68aa946f23f9bd053998f Mon Sep 17 00:00:00 2001
From: rifqi <18221070@std.stei.itb.ac.id>
Date: Sat, 25 Nov 2023 15:49:03 +0700
Subject: [PATCH] =?UTF-8?q?=F0=9F=8C=9FFEAT=20:=20Penambahan=20Controller?=
 =?UTF-8?q?=20Student?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 src/controllers/studController.ts | 151 ++++++++++++++++++++++++++++++
 src/index.ts                      |   6 +-
 src/models.ts                     |  12 +++
 3 files changed, 168 insertions(+), 1 deletion(-)
 create mode 100644 src/models.ts

diff --git a/src/controllers/studController.ts b/src/controllers/studController.ts
index e69de29..802f800 100644
--- a/src/controllers/studController.ts
+++ b/src/controllers/studController.ts
@@ -0,0 +1,151 @@
+import express, { Express } from "express"
+import { PrismaClient, Student } from '@prisma/client'
+const route = express.Router(); 
+const prisma = new PrismaClient()
+import { apiResponse } from "../models";
+import { error } from "console";
+
+const corsOptions = {
+    origin: 'http://localhost:5173',
+    credentials: true,
+    optionsSuccessStatus: 200
+  }
+
+route.get('/', async (req,res)=>{
+    var response : apiResponse<Student[]>; 
+    try {
+        const students = await prisma.student.findMany()
+        response = {
+            status : "valid",
+            message : "GET data berhasil",
+            data : students
+        }
+    } catch {
+        response = {
+            status : "invalid",
+            message : "GET data gagal",
+            data : null
+        }
+    }
+    res.json(response)
+})
+
+//Get student using id
+route.get('/:id', async (req,res)=>{
+    const id = Number(req.params.id)
+    try{
+        const student = await prisma.student.findFirstOrThrow(
+            {
+                where: { idStudent: id}
+            }
+        )
+        res.json(student)
+    }catch(error){
+        res.json("Siswa tidak ditemukan!")
+    }
+})
+
+//Get student using name
+route.get('/:name', async (req,res)=>{
+    const name = String(req.params.name)
+    try{
+        const student = await prisma.student.findFirstOrThrow(
+            {
+                where: { namaSiswa: name}
+            }
+        )
+        res.json(student)
+    }catch(error){
+        res.json("Siswa tidak ditemukan!")
+    }
+})
+
+route.post('/', async (req, res)=>{
+    const { namaSiswa,umurSiswa,noTelpSiswa,status,kelasSiswa,alamatSiswa } = req.body
+    var response : apiResponse<Student>; 
+    try {
+        if (namaSiswa == ""){
+            throw error
+        }
+        const CreateStudent = await prisma.student.create({
+            data : {
+                namaSiswa,
+                umurSiswa,
+                noTelpSiswa,
+                status,
+                kelasSiswa,
+                alamatSiswa
+            }
+        })
+        response = {
+            status : "valid",
+            message : "POST data berhasil",
+            data : CreateStudent
+        }
+    } catch (error){
+        console.log("Error creating student:", (error as Error).message);
+        response = {
+            status : "invalid",
+            message : "POST data gagal",
+            data : null
+        }
+    }
+    res.json(response)
+})
+
+route.put('/:id', async (req, res)=>{
+    const id = Number(req.params.id)
+    const { namaSiswa,umurSiswa,noTelpSiswa,status,kelasSiswa,alamatSiswa } = req.body
+    try {
+        if (namaSiswa == "" || umurSiswa == "" || noTelpSiswa == "" || alamatSiswa == "" || status ==""){
+            throw error
+        }
+        const updateStudent = await prisma.student.update({
+            where: {
+                idStudent : id
+            },
+            data : {
+                namaSiswa,
+                umurSiswa, 
+                noTelpSiswa,
+                status,
+                kelasSiswa, 
+                alamatSiswa
+            }
+        })
+        res.json(updateStudent)
+    } catch {
+        res.json("Gagal Update User")
+    }
+})
+
+route.delete('/:id', async (req, res)=>{
+    const id = Number(req.params.id)
+    var response : apiResponse<Student>; 
+    try {
+        const deleteStudent = await prisma.student.delete({
+            where : {
+                idStudent : id
+            }
+        })
+        if (!deleteStudent) {
+            // Student with the specified id was not found
+            throw error;
+        }
+        response = {
+            status : "valid",
+            message : "DELETE data berhasil",
+            data : null
+        }
+    } catch (error){
+        console.log("Error deleting student:", (error as Error).message);
+        response = {
+            status : "invalid",
+            message : "DELETE data gagal",
+            data : null
+        }
+    }
+    res.json(response)
+})
+
+export default route; 
\ No newline at end of file
diff --git a/src/index.ts b/src/index.ts
index 4e4f061..f22f8cc 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -6,6 +6,8 @@ import authRoutes from './controllers/authController';
 import vehicleRoutes from './controllers/vehicleController';
 import vehicleTypeRoutes from './controllers/vehicleTypeController';
 import drivingClassRoutes from './controllers/drivingClassController';
+import studentRoutes from './controllers/studController';
+
 const cors = require('cors');
 const corsOptions = {
     origin: 'http://localhost:5173',
@@ -13,6 +15,7 @@ const corsOptions = {
     optionsSuccessStatus: 200
   }
   
+app.use(cors(corsOptions));
 
 app.listen(port, () =>{
     console.log(`Server is running on port : ${port}`)
@@ -23,4 +26,5 @@ app.use('/user', userRoutes)
 app.use('/auth', authRoutes)
 app.use('/vehicle', vehicleRoutes)
 app.use('/vehicleType', vehicleTypeRoutes)
-app.use('/drivingClass', drivingClassRoutes)
\ No newline at end of file
+app.use('/drivingClass', drivingClassRoutes)
+app.use('/student', studentRoutes)
\ No newline at end of file
diff --git a/src/models.ts b/src/models.ts
new file mode 100644
index 0000000..c8b510c
--- /dev/null
+++ b/src/models.ts
@@ -0,0 +1,12 @@
+export type apiResponse<T> = {
+    status : "valid" | "invalid"
+    message : String
+    data : T | null
+}
+
+export type loginData<T> = {
+    status : "valid" | "invalid"
+    message : String
+    data : T | null
+    role : String
+}
\ No newline at end of file
-- 
GitLab