Search code examples
javascriptnext.jsroutes

2 PUT api request in same file in NEXT js


I need advice how to solve when I need for one route 2x PUT request. I need to add and remove two kinds of inputs, but I can remove one or the other. I can't figure out a way to set route.js to be able to add and remove both kinds of inputs.

export async function PUT(request) {
const id = request.nextUrl.searchParams.get("id");
const result = await CargoDetails.findOneAndUpdate(
{
   $and: [{ _id: id }],
 },
 {
   $push: { defaultValues: { count: "", long: "", width: "", 
 weight: "", high: "" },
   },
 },{ new: true }
);
return NextResponse.json({ result }, { status: 200 });
}
 export async function PUT(request) {
 const id = request.nextUrl.searchParams.get("id");
 const result = await CargoDetails.findOneAndUpdate(
   {
     $and: [{ _id: id }],
   },
   {
     $push: {
       exwork: { cost: "" },
     },
   },
   { new: true }
 );

 return NextResponse.json({ result }, { status: 200 });
 }

Below you can see my Model for better idea:

const cargoDetailsSchema = new Schema(
  {
    defaultValues: { type: [formFields], default: undefined },
    exwork: { type: [exValue], default: undefined },
    client: String,
    sdl: String,
    price: Number,
    transport: String,
    menaFrom: String,
    menaTo: String,
  },

  { timestamps: true }
);

const CargoDetails =
  models?.CargoDetails || 
model("CargoDetails",cargoDetailsSchema);

export default CargoDetails;

defaultValues and exwork have their own plus and minus button for add and remove function. I know that that maybe is it not possible to do it this way. I'd be grateful for any advice. .


Solution

  • add an action type to request query. something like this

    export async function PUT(request) {
     const id = request.nextUrl.searchParams.get("id");
     const action = request.nextUrl.searchParams.get("action");
     let result;
    
     if (action === "actionA") {
      result = await CargoDetails.findOneAndUpdate(
       {
        $and: [{ _id: id }],
       },
       {
        $push: {
         defaultValues: { count: "", long: "", width: "", weight: "", high: "" },
        },
       },
       { new: true },
      );
     } else if (action === "actionB") {
      result = await CargoDetails.findOneAndUpdate(
       {
        $and: [{ _id: id }],
       },
       {
        $push: {
         exwork: { cost: "" },
        },
       },
       { new: true },
      );
     } else return NextResponse.json({ message:"Action not defined!" }, { status: 400 });
    
     return NextResponse.json({ result }, { status: 200 });
    }