Use findMany or Select with Partial Types?

I'm currently trying to implement a findMany query where I can pass a partial object type (similar to how Prisma allows filtering with partial data) to dynamically construct queries based on the fields provided. Here is an example of what im trying to do
import { DBCredit } from './types';

async findAllTest(data: Partial<DBCredit>): Promise<DBCredit[]> {
try {
const foundCredit = await this.db.query.credits.findMany({
where: { ...data }, // Pass partial data for filtering
});
return foundCredit;
} catch (error) {
console.error('Error fetching credits:', error);
throw error;
}
}
import { DBCredit } from './types';

async findAllTest(data: Partial<DBCredit>): Promise<DBCredit[]> {
try {
const foundCredit = await this.db.query.credits.findMany({
where: { ...data }, // Pass partial data for filtering
});
return foundCredit;
} catch (error) {
console.error('Error fetching credits:', error);
throw error;
}
}
Is there a way to dynamically filter based on partial object input (like Partial<T>)? If not, what would be the recommended approach for handling such use cases? Are there docs or examples you could point me to?
1 Reply
wemsamuel
wemsamuelOP3mo ago
work around:
async findAll(data: Partial<DBCredit>): Promise<DBCredit[]> {
const conditions = Object.entries(data)
.filter(([_, value]) => value !== undefined)
.map(([key, value]) => eq(credits[key as keyof DBCredit], value as any));

const result = await this.db
.select()
.from(credits)
.where(and(...conditions));

return result;
}
async findAll(data: Partial<DBCredit>): Promise<DBCredit[]> {
const conditions = Object.entries(data)
.filter(([_, value]) => value !== undefined)
.map(([key, value]) => eq(credits[key as keyof DBCredit], value as any));

const result = await this.db
.select()
.from(credits)
.where(and(...conditions));

return result;
}
Want results from more Discord servers?
Add your server