how to return an empty array instead of null

I have such a type:
type P {
id String
m Int[]
}
type P {
id String
m Int[]
}
In the database, some items doesn't have field m at all. When I query such items, m is set to null. How to return an empty array instead? It feel weird that Prisma disallows optional lists, so typescript type will be like that: {id: string, m: number: []} but I still have to check that the field m exists before accessing it
3 Replies
Nurul
Nurul3mo ago
Hey @PinkiePie 👋 You can use client extensions to transform the result of the query from a model i.e. if you receive a null, then instead send an empty array in query result. Here's a related example that could be helpful. https://github.com/prisma/prisma-client-extensions/tree/main/transformed-fields
GitHub
prisma-client-extensions/transformed-fields at main · prisma/prisma...
Examples of Prisma Client extensions. Contribute to prisma/prisma-client-extensions development by creating an account on GitHub.
Nurul
Nurul3mo ago
However, it looks like you are using composite Type, right?
PinkiePie
PinkiePie3mo ago
@Nurul (Prisma) yep, i use composite types, so I had to do the thing you proposed for every model which uses my type. it works, and it achieved the desired outcome, but it feels like a dirty workaround anyway. prisma doesn't have optional lists. Why then it returns me a null instead of an empty array? That's a misleading DX. Prisma should either allow optional lists in the schema, so m Int[]? will produce number[] | null type, and force me to check the array before accessing it, or it should return an empty array by default instead of null. Currently, the field m can be nullable on the database level (for example if I pass it undefined during create operation, but the generated TS type shows like it can be never optional. So, I will have to add the check if the field m everywhere, but the devs after me would try to remove it as "unnecessary" check (type in TS and schema clearly shows that it's a mandatory field). So, your solution works as a temporary fix, but for sure it's something wrong on Prisma's side. Either return [] by default instead of null, or allow us to mark lists as optional in schema, so we will generate correct TS types