To create a reusable function and to allow easy replacement of database backends, I'd like to write a simple abstraction layer for Google Firestore.
However, there's the problem that I can't programmatically daisy-chain where
conditions. Is there a way to pass in an array of where
conditions and pass them to Firestore when executing the query somehow?
This is my current approach, but it doesn't work. The conditions are simply ignore and the first result is returned.
export const getOne = async (
req: any,
entity: string,
select: string[] = [],
where: any[] = [],
) => {
// Get entity reference from firestore.
const entityRef = req.firebaseServer.firestore().collection(entity);
// Select fields.
const query = entityRef.select(...select);
// Add where conditions.
where.forEach((condition) => {
query.where(...condition);
});
// Limit to 1 result.
query.limit(1);
// Run query.
return await query.get();
};
Example call:
return await getOne(
req,
'item',
['title', 'language', 'uuid'],
[
['categoryId', '==', req.params.categoryId],
['language', '==', req.params.lang],
],
);