Docs Express

npm init -y
npm i express @types/express typescript ts-node-dev prisma @prisma/client
npx tsc --init
"dev": "ts-node-dev --respawn src/app.ts",
npm install -D prisma
npx prisma init
npm install @prisma/client

npx prisma generate
npx prisma migrate dev --name init
npx prisma studio
// schema.prisma

model wedding {
  id        Int       @id @default(autoincrement())
  name      String
  pasangan  String    @unique
  paket     Int       @default(0)
  createdAt DateTime  @default(now())
}
DATABASE_URL="postgresql://postgres:uuaauaua123@localhost:5432/weddingcuy?schema=public"
// src/app.ts
import express from "express";
import { router as authRoutes } from "./routes/auth";

const app = express();
app.use(express.json());

app.use(authRoutes);

app.get('/', (req, res) => {
  res.send('Hello World!')
})

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
// src/routes/auth.ts

import { Router } from "express";
import {
    testing,
} from "../controllers/auth";

const router = Router();

router.get("/test", testing);

export { router };
// src/controllers/auth.ts

import { Request, Response } from "express";

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" 
      });
    }
  };

export {
    testing,
};
// src/controllers/allwedding.ts


// Get
import { PrismaClient } from '../../generated/prisma'
import { Request, Response } from 'express'

const prisma = new PrismaClient()

export const getAllWedding = async (req: Request, res: Response) => {
  try {
    const weddings = await prisma.wedding.findMany()
    res.json(weddings)
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' })
  }
}

// POST
export const createWedding = async (req: Request, res: Response) => {
  try {
    const { name, pasangan, paket } = req.body
    const wedding = await prisma.wedding.create({
      data: {
        name,
        pasangan,
        paket,
      },
    })
    res.status(201).json(wedding)
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' })
  }
}
// src/routes/allwedding.ts

import { Router } from 'express'
import { getAllWedding, createWedding } from '../controllers/allwedding'

const router = Router()

router.get('/allwedding', getAllWedding)

router.post('/allwedding', createWedding)

export default router
// App.ts

import express from "express";
import { router as authRoutes } from "./routes/auth";
import allWeddingRouter from "./routes/allwedding";

const app = express();
app.use(express.json());

app.use(authRoutes);
app.use(allWeddingRouter);

app.get('/', (req, res) => {
  res.send('Hello World!')
})

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
npm install express-rate-limit

Rate limiter :

// routes/allwedding.ts

import rateLimit from 'express-rate-limit'

const router = Router()

const limiter = rateLimit({
  windowMs: 1 * 60 * 1000,
  max: 10,
  message: { error: 'Too many requests, please try again later.' },
})

router.use(limiter)

Pagination :

// controllers/allwedding.ts

export const getAllWedding = async (req: Request, res: Response) => {
  try {
    const page = parseInt(req.query.page as string) || 1
    const limit = parseInt(req.query.limit as string) || 2
    const skip = (page - 1) * limit

    const [weddings, total] = await Promise.all([
      prisma.wedding.findMany({
        skip,
        take: limit,
      }),
      prisma.wedding.count(),
    ])

    res.json({
      data: weddings,
      total,
      page,
      totalPages: Math.ceil(total / limit),
    })
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' })
  }
}
http://localhost:3000/allwedding?page=1&limit=2
const existing = await prisma.wedding.findUnique(
        { 
            where: { pasangan } 
        }
    )

    if (existing) {
      return res.status(400).json({ error: 'Pasangan sudah terdaftar' })
    }

Last updated