Hello Everyone, I am curious to know if there is a...
# orm-help
m
Hello Everyone, I am curious to know if there is a better way to construct a dynamic OrderWhereInput in the snippet below?
Copy code
async function handler(req: NextApiRequest, res: NextApiResponse<Response>) {
  await verifyUserToken(req, res)

  const automobileQuery = req.query.automobile.toString().split(',')

  if (automobileQuery.length > 2) {
    throw new CustomError(
      400,
      'automobile URL parameter expects a maximum of two values'
    )
  }

  let values: VehicleType[] | undefined

  if (automobileQuery.includes('BIKE')) {
    if (values === undefined) values = []
    values.push(VehicleType.BIKE)
  }
  if (automobileQuery.includes('CAR')) {
    if (values === undefined) values = []
    values.push(VehicleType.CAR)
  }

  let vehicleType = undefined

  let orders = await prisma.order.findMany({
    where: {
      vendorId: null,
      trackingStatus: 'READY_FOR_PICKUP',
      vehicleType: { in: values },
    },
  })

  return res.json({
    status: true,
    data: { orders },
  })
}
j
Copy code
const validVehiclesTypes: Record<string, VehicleType> = {
  BIKE: VehicleType.BIKE,
  CAR: VehicleType.CAR,
}
const values: VehicleType[] = automobileQuery
  .map((vehicle) => validVehicleTypes[vehicle])
  .filter(Boolean)
You could do that with a single
reduce
or
flatMap
, but this seemed a little more clear.
m
Thank you @Jason Kleinberg. I am a little bit confused with the
.filter(Boolean)
. Prisma expects undefined in order to omit a condition in the where object. Can I use a ternary operator to check for the size of values and return undefined if its zero?
j
You can. If you use
reduce
or
flatMap
you would use the ternary With
filter
when the mapped value is undefined, it will be turned into
false
and filtered out.
👍🏾 1