Next.js application using TypeScript and Prisma, you can create an API route to handle the retrieval of brands with optional search functionality.

Jun 04, 202434 mins read

icon-1979139-1280.jpg

1. Define Prisma Schema
Ensure your Prisma schema includes a model for Brand.

// schema.prisma
model Brand {
  id        Int     @id @default(autoincrement())
  name      String
  // Add other fields if necessary
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

 

2. Create Controller Function
Implement a controller function to handle fetching brands with optional search functionality. Place this in a file like controllers/brandController.ts.

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

const prisma = new PrismaClient();

export async function getAllBrands(search: string | null) {
  const where = search ? { name: { contains: search, mode: 'insensitive' } } : {};

  return prisma.brand.findMany({
    where,
    orderBy: { name: 'asc' },
    take: 15,
  });
}

 

3. Set up API Route
Create an API route to handle the GET request for fetching brands with optional search functionality. Place this in pages/api/brands.ts.

// pages/api/brands.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { getAllBrands } from '@/app/server/controllers/brandController';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { search = null } = req.query;

  try {
    const brands = await getAllBrands(search as string);
    res.status(200).json({ brands });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}

 

Summary
Controller: The getAllBrands function in controllers/brandController.ts handles fetching brands with optional search functionality.
API Route: The API route in pages/api/brands.ts handles the GET request for fetching brands with optional search functionality.
This setup ensures that your Next.js application can handle retrieving brands with optional search functionality while maintaining a clean MVC structure. Adjust the code as needed to fit your specific requirements.

Next.js application using TypeScript and Prisma, you can create an API route to handle the creation of a brand

1. Define Prisma Schema
Ensure your Prisma schema includes a model for Brand.

// schema.prisma
model Brand {
  id                Int      @id @default(autoincrement())
  name              String
  slug              String   @unique
  meta_title        String?
  meta_description  String?
  logo              String?
  // Add other fields if necessary
  createdAt         DateTime @default(now())
  updatedAt         DateTime @updatedAt
}

model BrandTranslation {
  id         Int      @id @default(autoincrement())
  lang       String
  name       String
  brand_id   Int
  brand      Brand    @relation(fields: [brand_id], references: [id])
  // Add other fields if necessary
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt
}

 

2. Create Controller Function
Implement a controller function to handle the creation of a brand. Place this in a file like controllers/brandController.ts.

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

const prisma = new PrismaClient();

export async function createBrand(name: string, metaTitle: string, metaDescription: string, slug: string | null, logo: string | null) {
  const brand = await prisma.brand.create({
    data: {
      name,
      slug: slug || `${name.replace(/\s+/g, '-').replace(/[^A-Za-z0-9\-]/g, '')}-${Math.random().toString(36).substring(7)}`,
      meta_title: metaTitle,
      meta_description: metaDescription,
      logo,
    },
  });

  await prisma.brandTranslation.create({
    data: {
      lang: process.env.DEFAULT_LANGUAGE || 'en',
      name,
      brand_id: brand.id,
    },
  });

  return brand;
}

 

3. Set up API Route
Create an API route to handle the POST request for creating a brand. Place this in pages/api/brands.ts.

// pages/api/brands.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { createBrand } from '@/app/server/controllers/brandController';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const { name, metaTitle, metaDescription, slug, logo } = req.body;

    try {
      const brand = await createBrand(name, metaTitle, metaDescription, slug, logo);
      res.status(201).json({ brand });
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

 

Summary
Controller: The createBrand function in controllers/brandController.ts handles the creation of a brand and its translation.
API Route: The API route in pages/api/brands.ts handles the POST request for creating a brand.
This setup ensures that your Next.js application can handle creating a brand while maintaining a clean MVC structure. Adjust the code as needed to fit your specific requirements.

Next.js application using TypeScript and Prisma, you can create an API route to handle the updating of a brand

1. Define Prisma Schema
Ensure your Prisma schema includes models for Brand and BrandTranslation.

// schema.prisma
model Brand {
  id                Int       @id @default(autoincrement())
  name              String
  slug              String    @unique
  meta_title        String?
  meta_description  String?
  logo              String?
  // Add other fields if necessary
  createdAt         DateTime  @default(now())
  updatedAt         DateTime  @updatedAt

  translations      BrandTranslation[]
}

model BrandTranslation {
  id         Int      @id @default(autoincrement())
  lang       String
  name       String
  brand_id   Int
  brand      Brand    @relation(fields: [brand_id], references: [id])

  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt
}

 

2. Create Controller Function
Implement a controller function to handle the updating of a brand. Place this in a file like controllers/brandController.ts.

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

const prisma = new PrismaClient();

export async function updateBrand(id: number, name: string, metaTitle: string, metaDescription: string, slug: string | null, logo: string | null, lang: string) {
  const brand = await prisma.brand.update({
    where: { id },
    data: {
      name,
      meta_title: metaTitle,
      meta_description: metaDescription,
      slug: slug || `${name.replace(/\s+/g, '-').replace(/[^A-Za-z0-9\-]/g, '')}-${Math.random().toString(36).substring(7)}`,
      logo,
      translations: {
        upsert: {
          where: { lang_brand_id: { lang, brand_id: id } },
          update: { name },
          create: { lang, name },
        },
      },
    },
  });

  return brand;
}

 

3. Set up API Route
Create an API route to handle the PUT request for updating a brand. Place this in pages/api/brands/[id].ts.

// pages/api/brands/[id].ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { updateBrand } from '@/app/server/controllers/brandController';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { id } = req.query;

  if (req.method === 'PUT') {
    const { name, metaTitle, metaDescription, slug, logo, lang } = req.body;

    try {
      const brand = await updateBrand(Number(id), name, metaTitle, metaDescription, slug, logo, lang);
      res.status(200).json({ brand });
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
  } else {
    res.setHeader('Allow', ['PUT']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

 

Summary
Controller: The updateBrand function in controllers/brandController.ts handles the updating of a brand and its translation.
API Route: The API route in pages/api/brands/[id].ts handles the PUT request for updating a brand.
This setup ensures that your Next.js application can handle updating a brand while maintaining a clean MVC structure. Adjust the code as needed to fit your specific requirements.

Next.js application using TypeScript and Prisma, you can create an API route to handle the deletion of a brand

1. Create Controller Function
Implement a controller function to handle the deletion of a brand. Place this in a file like controllers/brandController.ts.

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

const prisma = new PrismaClient();

export async function deleteBrand(id: number) {
  // Delete products associated with the brand
  await prisma.product.deleteMany({ where: { brandId: id } });

  // Delete brand translations
  await prisma.brandTranslation.deleteMany({ where: { brandId: id } });

  // Delete the brand
  await prisma.brand.delete({ where: { id } });
}

 

2. Set up API Route
Create an API route to handle the DELETE request for deleting a brand. Place this in pages/api/brands/[id].ts.

// pages/api/brands/[id].ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { deleteBrand } from '@/app/server/controllers/brandController';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { id } = req.query;

  if (req.method === 'DELETE') {
    try {
      await deleteBrand(Number(id));
      res.status(204).end();
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
  } else {
    res.setHeader('Allow', ['DELETE']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

 

Summary
Controller: The deleteBrand function in controllers/brandController.ts handles the deletion of a brand, its translations, and associated products.
API Route: The API route in pages/api/brands/[id].ts handles the DELETE request for deleting a brand.
This setup ensures that your Next.js application can handle deleting a brand while maintaining a clean MVC structure. Adjust the code as needed to fit your specific requirements.

Share
Newsletter

Subscribe our newsletter