lundi 8 novembre 2021

JS Design Patterns - Interface to perform different tasks

I have different methods in my app to fetch users:

1. Fetch international users
2. Fetch users from same region
3. Fetch users from same city

Currently, I have implemented 1 method for each one:

 const fetchIntenationalUsers = async (limit = 10) => {
   const result = await db.collection("users").limit(limit).get();
   ...
   return parseUsers(result);
 }

 const fetchSameRegionUsers = async (region, limit = 10) => {
   const result = await db.collection("users").where("region", "==", region).limit(limit).get();
   ...
   return parseUsers(result);
 }

 const fetchSameCityUsers = async (city, limit = 10) => {
   const result = await db.collection("users").where("city", "==", city).limit(limit).get();
   ...
   return parseUsers(result);
 }

I have thought to create a generalized method like:

const fetchUsers = (queryType = "international", location = {}, limit = 10) => {
   const queries = {
      "international": db.collection("users"),
      "region": db.collection("users").where("region", "==", location.region),
      "city": db.collection("users").where("city", "==", location.city),
   };

   const result = await queries[queryType].limit(limit).get();

   ...

   return parseUsers(result);
} 

But I am not sure if this is an anti-pattern or a design pattern. Any other approach?

Aucun commentaire:

Enregistrer un commentaire