0
List Documents
One script reply has been approved by the moderators Verified
Created by paulys8ty1 682 days ago Viewed 4216 times
0
Submitted by adam186 Deno
Verified 358 days ago
1
import { initializeApp } from "npm:firebase@9.20.0/app";
2
import {
3
  collection,
4
  endAt,
5
  getDocs,
6
  getFirestore,
7
  limit as limitItems,
8
  orderBy,
9
  query,
10
  QueryConstraint,
11
  startAt,
12
} from "npm:firebase/firestore/lite";
13

14
/**
15
 * @param order_by Name of the field to order by.
16
 *
17
 * @param start_at Can only be used if `order_by` is present,
18
 * because it'll filter based on the value of that field.
19
 *
20
 * @param end_at Can only be used if `order_by` is present,
21
 * because it'll filter based on the value of that field.
22
 */
23
type Firebase = {
24
  apiKey: string;
25
  authDomain: string;
26
  projectId: string;
27
  storageBucket: string;
28
  messagingSenderId: string;
29
  appId: string;
30
  measurementId: string;
31
};
32
export async function main(
33
  auth: Firebase,
34
  collection_id: string,
35
  order_by?: string,
36
  order_direction: "asc" | "desc" = "asc",
37
  start_at?: number | string,
38
  end_at?: number | string,
39
  limit?: number,
40
) {
41
  const app = initializeApp(auth);
42
  const store = getFirestore(app);
43

44
  const colRef = collection(store, collection_id);
45
  const constraints = [
46
    order_by ? orderBy(order_by, order_direction) : undefined,
47
    start_at ? startAt(start_at) : undefined,
48
    end_at ? endAt(end_at) : undefined,
49
    limit ? limitItems(limit) : undefined,
50
  ].filter(Boolean) as QueryConstraint[];
51
  const snapshot = await getDocs(query(colRef, ...constraints));
52
  const list = snapshot.docs.map((doc) => doc.data());
53

54
  return list;
55
}
56