Next.js TypeScript application using Prisma and following the MVC pattern with routes, you'll need to set up the backend API endpoints to fetch and fi

Jun 04, 202410 mins read

untitled-1024-683px-7.jpg
  1. Set up Prisma Models: Define the Category model in Prisma.
  2. Create Controller: Implement a controller to handle the logic for fetching and filtering categories.
  3. Set up API Routes: Define API routes to handle requests for fetching categories.
  4. Fetch Data in Next.js: Use Next.js data fetching methods to fetch categories data from the backend API.

Let's break down each step:

1. Set up Prisma Models
Define the Category model in your Prisma schema file (schema.prisma):

// schema.prisma
model Category {
  id         Int      @id @default(autoincrement())
  name       String
  orderLevel Int
}

 

2. Create Controller
Implement a controller to handle fetching and filtering categories. Place this in controllers/categoryController.ts:

// controllers/categoryController.ts
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function getCategories(search?: string) {
  let categories = await prisma.category.findMany({
    orderBy: { orderLevel: 'desc' },
  });

  if (search) {
    categories = categories.filter(category => category.name.includes(search));
  }

  return categories;
}

 

3. Set up API Routes
Define API routes to handle requests for fetching categories. Place this in pages/api/categories/index.ts:

// pages/api/categories/index.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { getCategories } from '@/app/server/controllers/categoryController';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    const { search } = req.query;
    const categories = await getCategories(search as string);
    res.status(200).json({ categories });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

 

4. Fetch Data in Next.js
Fetch categories data from the backend API in your Next.js page/component:

// pages/categories/index.tsx
import { useState, useEffect } from 'react';
import axios from 'axios';

export default function CategoriesPage() {
  const [categories, setCategories] = useState([]);
  const [search, setSearch] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('/api/categories', {
          params: { search }
        });
        setCategories(response.data.categories);
      } catch (error) {
        console.error('Error fetching categories:', error);
      }
    };

    fetchData();
  }, [search]);

  return (
    <div>
      {/* Render categories data here */}
    </div>
  );
}

 

Summary
Prisma Models: Define the Category model in Prisma.
Controller: Implement a controller to handle fetching and filtering categories.
API Routes: Define API routes to handle requests for fetching categories.
Next.js Page: Fetch categories data from the backend API in your Next.js page/component.
Make sure to adjust the code according to your specific requirements and project structure.

Share
Newsletter

Subscribe our newsletter