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

Jun 04, 202438 mins read

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

1. Define Prisma Schema
Ensure your Prisma schema includes models for Carrier, CarrierRange, and CarrierRangePrice.

// schema.prisma
model Carrier {
  id            Int       @id @default(autoincrement())
  name          String
  transit_time  Int
  logo          String?
  free_shipping Boolean
  ranges        CarrierRange[]
  // Add other fields if necessary
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
}

model CarrierRange {
  id            Int               @id @default(autoincrement())
  carrier       Carrier           @relation(fields: [carrierId], references: [id])
  carrierId     Int
  billing_type  String
  delimiter1    Int
  delimiter2    Int
  prices        CarrierRangePrice[]
  // Add other fields if necessary
  createdAt     DateTime          @default(now())
  updatedAt     DateTime          @updatedAt
}

model CarrierRangePrice {
  id               Int            @id @default(autoincrement())
  carrier          Carrier        @relation(fields: [carrierId], references: [id])
  carrierId        Int
  carrierRange     CarrierRange   @relation(fields: [carrierRangeId], references: [id])
  carrierRangeId   Int
  zone             Int
  price            Float
  // 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 carriers. Place this in a file like controllers/carrierController.ts.

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

const prisma = new PrismaClient();

export async function createCarrier(carrierData: any) {
  const { carrier_name, transit_time, logo, shipping_type, delimiter1, delimiter2, billing_type, zones, carrier_price } = carrierData;

  const freeShipping = shipping_type ? true : false;

  const carrier = await prisma.carrier.create({
    data: {
      name: carrier_name,
      transit_time,
      logo,
      free_shipping: freeShipping,
      ranges: {
        createMany: {
          data: delimiter1.map((_, i) => ({
            billing_type,
            delimiter1: delimiter1[i],
            delimiter2: delimiter2[i],
            prices: {
              createMany: {
                data: zones.map((zone: any) => ({
                  zone_id: zone,
                  price: carrier_price[zone][i]
                }))
              }
            }
          }))
        }
      }
    },
    include: {
      ranges: {
        include: {
          prices: true
        }
      }
    }
  });

  return carrier;
}

 

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

// pages/api/carriers.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { createCarrier } from '@/app/server/controllers/carrierController';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    try {
      const carrier = await createCarrier(req.body);
      res.status(201).json({ carrier });
    } 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 createCarrier function in controllers/carrierController.ts handles the creation of carriers and their associated ranges and prices.
API Route: The API route in pages/api/carriers.ts handles the POST request for creating carriers.
This setup ensures that your Next.js application can handle creating carriers 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 carriers

1. Update Controller Function
Update the controller function to handle the updating of carriers. Place this in a file like controllers/carrierController.ts.

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

const prisma = new PrismaClient();

export async function updateCarrier(id: number, carrierData: any) {
  const { carrier_name, transit_time, logo, shipping_type, delimiter1, delimiter2, billing_type, zones, carrier_price } = carrierData;

  const freeShipping = shipping_type ? true : false;

  // Find the existing carrier
  const existingCarrier = await prisma.carrier.findUnique({ where: { id } });

  if (!existingCarrier) {
    throw new Error('Carrier not found');
  }

  // Update the carrier
  const updatedCarrier = await prisma.carrier.update({
    where: { id },
    data: {
      name: carrier_name,
      transit_time,
      logo,
      free_shipping: freeShipping,
      ranges: {
        // Delete existing ranges and prices
        deleteMany: {}
      }
    },
    include: {
      ranges: {
        include: {
          prices: true
        }
      }
    }
  });

  // Add new ranges and prices if it's not free shipping
  if (!freeShipping) {
    for (let i = 0; i < delimiter1.length; i++) {
      const newCarrierRange = await prisma.carrierRange.create({
        data: {
          carrierId: id,
          billing_type,
          delimiter1: delimiter1[i],
          delimiter2: delimiter2[i],
          prices: {
            createMany: {
              data: zones.map((zone: any) => ({
                zone_id: zone,
                price: carrier_price[zone][i]
              }))
            }
          }
        }
      });
    }
  }

  return updatedCarrier;
}

 

2. Set up API Route
Update the API route to handle the PUT request for updating carriers. Place this in pages/api/carriers/[id].ts.

// pages/api/carriers/[id].ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { updateCarrier } from '@/app/server/controllers/carrierController';

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

  if (req.method === 'PUT') {
    try {
      const updatedCarrier = await updateCarrier(Number(id), req.body);
      res.status(200).json({ carrier: updatedCarrier });
    } 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 updateCarrier function in controllers/carrierController.ts handles the updating of carriers and their associated ranges and prices.
API Route: The API route in pages/api/carriers/[id].ts handles the PUT request for updating carriers.
This setup ensures that your Next.js application can handle updating carriers 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 carriers

1. Update Controller Function
Update the controller function to handle the deletion of carriers. Place this in a file like controllers/carrierController.ts.

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

const prisma = new PrismaClient();

export async function deleteCarrier(id: number) {
  // Find the existing carrier
  const existingCarrier = await prisma.carrier.findUnique({ where: { id } });

  if (!existingCarrier) {
    throw new Error('Carrier not found');
  }

  // Delete carrier ranges and prices
  await prisma.carrierRange.deleteMany({ where: { carrierId: id } });
  await prisma.carrierRangePrice.deleteMany({ where: { carrierId: id } });

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

  return;
}

 

2. Set up API Route
Update the API route to handle the DELETE request for deleting carriers. Place this in pages/api/carriers/[id].ts.

// pages/api/carriers/[id].ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { deleteCarrier } from '@/app/server/controllers/carrierController';

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

  if (req.method === 'DELETE') {
    try {
      await deleteCarrier(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 deleteCarrier function in controllers/carrierController.ts handles the deletion of carriers, their ranges, and prices.
API Route: The API route in pages/api/carriers/[id].ts handles the DELETE request for deleting carriers.
This setup ensures that your Next.js application can handle deleting carriers 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 updating the status of carriers

1. Update Controller Function
Update the controller function to handle updating the status of carriers. Place this in a file like controllers/carrierController.ts.

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

const prisma = new PrismaClient();

export async function updateCarrierStatus(id: number, status: boolean) {
  // Find the existing carrier
  const existingCarrier = await prisma.carrier.findUnique({ where: { id } });

  if (!existingCarrier) {
    throw new Error('Carrier not found');
  }

  // Update the status
  const updatedCarrier = await prisma.carrier.update({
    where: { id },
    data: { status }
  });

  return updatedCarrier;
}

 

2. Set up API Route
Create an API route to handle the POST request for updating the status of carriers. Place this in pages/api/carriers/status.ts.

// pages/api/carriers/status.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { updateCarrierStatus } from '@/app/server/controllers/carrierController';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    try {
      const { id, status } = req.body;
      const updatedCarrier = await updateCarrierStatus(id, status);
      res.status(200).json({ carrier: updatedCarrier });
    } 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 updateCarrierStatus function in controllers/carrierController.ts handles updating the status of carriers.
API Route: The API route in pages/api/carriers/status.ts handles the POST request for updating carrier status.
This setup ensures that your Next.js application can handle updating carrier status while maintaining a clean MVC structure. Adjust the code as needed to fit your specific requirements.

 

 

Share
Newsletter

Subscribe our newsletter