Ensuring Filtering if variable is undefined

I have an application that is a multi-tenant app where we always filter by TenantId , so for example we do queries like this:
var contacts = await db.contacts.findMany({
where: {
tenantId: tenantId,
}
});
var contacts = await db.contacts.findMany({
where: {
tenantId: tenantId,
}
});
While obviously I need to check the tenantId but from a general question, when a a variable sometimes is undefined, it completely ignores that part of query. Some of this is just the nature of how JS objects are built. But I am curious if there is a way to guarantee that the where statement never ignores a variable. I think this is where most query builder alternatives handle by passing variables into a method.
Basically I am curious if there is ways to guarantee that no filter leaks because of a value being undefined.
4 Replies
JTB
JTB2w ago
Default Values or Preconditions Like:
var contacts = await db.contacts.findMany({
where: {
tenantId: {
equals: tenantId || '' // Default to an empty string if tenantId is undefined
},
}
});

Explicit Checks Before Query Execution / Validation :

if (typeof tenantId !== 'undefined') {
var contacts = await db.contacts.findMany({
where: {
tenantId: tenantId,
}
});
} else {
// Handle the case where tenantId is undefined
}
var contacts = await db.contacts.findMany({
where: {
tenantId: {
equals: tenantId || '' // Default to an empty string if tenantId is undefined
},
}
});

Explicit Checks Before Query Execution / Validation :

if (typeof tenantId !== 'undefined') {
var contacts = await db.contacts.findMany({
where: {
tenantId: tenantId,
}
});
} else {
// Handle the case where tenantId is undefined
}
You should never have a variable with an unknown type. That would be a bad "style" and the code should be revised.
moosthuizen
moosthuizen2w ago
Either of these will work. 2nd option seems better because undefined case should be logged somewhere.
JTB
JTB2w ago
I would even say that it should be built in such a way that an undefined never reaches this point. But I agree with you, if we have to "live" with it, I would also use the second one and throw back a throw new error.
Jonathan
Jonathan2w ago
Yeah I agree it is a "we have to live with it" but would be nice if there was a better way sometimes I tend to do the second approach
Want results from more Discord servers?
Add your server
More Posts