Do i need parse int all the time in Prisma?

Viewed 371

My prisma model

model Todo {
  id Int @default(autoincrement()) @id
  title String
  content String
  status TodoStatus @default(IN_PROGRESS)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

The api call

app.get("/todos/:id", async (req: Request, res: Response) => {
  const id = parseInt(req.params.id); // this line
  const todo = await prisma.todo.findFirst({
    where: { id },
  });

  res.json(todo);
});

Do I have to always parseInt the id? because by default req.params is a string type, and obviously my Todo primary key is int. I don't see any online resources parsing the int and then only passing to the Prisma query, it feels a bit odd to always parsing the req.params.id to int all the time in every api call.

2 Answers

You can use

prisma.todo.findUnique({
    where: { id: +id }
  });

Note that you have to specify the field you want to find.

You can use Express Query Parser to automatically parse strings to valid types.

This would automatically convert query params to the valid type.

Example:

// without this parser
req.query = {a: 'null', b: 'true', c: {d: 'false', e: '3.14'}}

// with this parser
req.query = {a: null, b: true, c: {d: false, e: 3.14}}
Related