All files / services hackernews.ts

0% Statements 0/38
0% Branches 0/8
0% Functions 0/16
0% Lines 0/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                                                                                                                                                 
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, onValue, off, get, DatabaseReference } from 'firebase/database';
import { HNItem, HNItemId } from '@/types/hackernews';
 
const firebaseConfig = {
  databaseURL: import.meta.env.VITE_FIREBASE_DATABASE_URL,
};
 
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
 
export const hackernewsAPI = {
  async getNewPostIds(): Promise<HNItemId[]> {
    const postRef = ref(database, 'v0/newstories');
    const snapshot = await get(postRef);
    return snapshot.val() || [];
  },
 
  async getTopPostIds(): Promise<HNItemId[]> {
    const postRef = ref(database, 'v0/topstories');
    const snapshot = await get(postRef);
    return snapshot.val() || [];
  },
 
  async getItem(id: HNItemId): Promise<HNItem | null> {
    const itemRef = ref(database, `v0/item/${id}`);
    const snapshot = await get(itemRef);
    return snapshot.val();
  },
 
  async getItems(ids: HNItemId[]): Promise<HNItem[]> {
    const items = await Promise.all(
      ids.map(async (id) => {
        const itemRef = ref(database, `v0/item/${id}`);
        const snapshot = await get(itemRef);
        return snapshot.val();
      })
    );
    return items.filter((item): item is HNItem => item !== null);
  },
 
  subscribeToNewPosts(callback: (postIds: HNItemId[]) => void): () => void {
    const postRef = ref(database, 'v0/newstories');
    onValue(postRef, (snapshot) => {
      const postIds = snapshot.val() || [];
      callback(postIds);
    });
    return () => off(postRef);
  },
 
  subscribeToTopPosts(callback: (postIds: HNItemId[]) => void): () => void {
    const postRef = ref(database, 'v0/topstories');
    onValue(postRef, (snapshot) => {
      const postIds = snapshot.val() || [];
      callback(postIds);
    });
    return () => off(postRef);
  },
 
  subscribeToItem(id: HNItemId, callback: (item: HNItem | null) => void): () => void {
    const itemRef = ref(database, `v0/item/${id}`);
    onValue(itemRef, (snapshot) => {
      callback(snapshot.val());
    });
    return () => off(itemRef);
  },
 
  unsubscribe(refPath: string): void {
    const dbRef: DatabaseReference = ref(database, refPath);
    off(dbRef);
  },
};