score:1

Accepted answer
import {
  query,
  where,
  orderBy,
  limit
} from "firebase/firestore";



type Clause = "where" | "limit" | "orderBy";
type Operator = "==" | "!=" | "<" | ">" | "<=" | ">=";

interface WhereArgs {
  column: string;
  operator: Operator;
  value: string | number;
}

interface OrderByArgs {
  column: string;
  order: "asc" | "desc";
}

interface LimitArgs {
  amount: number;
}

type Command =
  | ({ clause: "where" } & WhereArgs)
  | ({ clause: "orderBy" } & OrderByArgs)
  | ({ clause: "limit" } & LimitArgs);

const options = {
  where: (args: WhereArgs) => {
    const { column, operator, value } = args;
    return where(column, operator, value);
  },
  limit: (args: LimitArgs) => {
    const { amount } = args;
    return limit(amount);
  },
  orderBy: (args: OrderByArgs) => {
    const { column, order } = args;
    return orderBy(column, order);
  }
};

const commands: Array<Extract<Command, { clause: Clause }>> = [
  {
    clause: "where",
    column: "anotherField",
    operator: ">=",
    value: "someValue"
  },
  {
    clause: "where",
    column: "anotherField",
    operator: "==",
    value: "anotherValue"
  },
  {
    clause: "limit",
    amount: 10
  },
  {
    clause: "orderBy",
    column: "timestamp",
    order: "asc"
  }
];

const constraints = [];

for (const command of commands) {
  const { clause, ...rest } = command;
  constraints.push(options[command.clause](rest as any));
}

query(null as any, ...constraints);

score:1

// Do not forget to use ... operator when creating a query.
const q = query(collection(db,'posts'),
   ...convertArrayObjectsToArrayFunctions(qConstrains))

Related Query

More Query from same tag