codebydante commited on
Commit
9ab4019
·
1 Parent(s): cd37a19

Separate CodeByDante database to read exclusively from code-by-dante project

Browse files
Files changed (1) hide show
  1. services/firebase.ts +79 -59
services/firebase.ts CHANGED
@@ -13,20 +13,18 @@ import {
13
  } from 'firebase/firestore';
14
  import { DataItem } from '../types';
15
 
16
- // Configuration provided by user
17
  const firebaseConfig = {
18
- apiKey: "AIzaSyAH3jvbe0_QLzIuuv5kTMK8246HNvohvfE",
19
- authDomain: "twistedbrody-9d163.firebaseapp.com",
20
- projectId: "twistedbrody-9d163",
21
- storageBucket: "twistedbrody-9d163.firebasestorage.app",
22
- messagingSenderId: "733213514129",
23
- appId: "1:733213514129:web:e9694684f5c3994ed06230",
24
- measurementId: "G-N8TQ7MY42W"
25
  };
26
 
27
  const app = initializeApp(firebaseConfig);
28
  const db = getFirestore(app);
29
- const COLLECTION_NAME = 'neonvault_items';
30
 
31
  /**
32
  * Helper function to remove fields with 'undefined' values from an object.
@@ -43,52 +41,72 @@ const cleanData = (data: any) => {
43
  };
44
 
45
  export const subscribeToItems = (callback: (items: DataItem[]) => void) => {
46
- const colRef = collection(db, COLLECTION_NAME);
47
-
48
- return onSnapshot(colRef, (snapshot) => {
49
- const items = snapshot.docs.map(doc => {
 
 
 
 
 
 
 
 
 
50
  const data = doc.data();
51
-
52
- // Migrate old blocks without type to have 'text' type
53
- let blocks = data.blocks;
54
- if (blocks && Array.isArray(blocks)) {
55
- blocks = blocks.map((block: any) => ({
56
- ...block,
57
- type: block.type || 'text'
58
- }));
59
- }
60
-
61
- const createdTime = data.createdAt?.toMillis ? data.createdAt.toMillis() : (typeof data.createdAt === 'number' ? data.createdAt : Date.now());
62
- const updatedTime = data.updatedAt?.toMillis ? data.updatedAt.toMillis() : (typeof data.updatedAt === 'number' ? data.updatedAt : createdTime);
63
-
64
  return {
65
  id: doc.id,
66
- ...data,
67
- blocks,
68
- createdAt: createdTime,
69
- updatedAt: updatedTime,
 
 
 
 
70
  } as DataItem;
71
  });
 
 
72
 
73
- // Sort descending by createdAt in JS safely
74
- items.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- callback(items);
77
- }, (error) => {
78
- console.error("Error reading from Firestore:", error);
79
- // Return empty array on error so UI unblocks instead of staying black
80
- callback([]);
81
- });
82
  };
83
 
 
 
84
  export const addItem = async (item: Omit<DataItem, 'id' | 'createdAt'>): Promise<string> => {
85
  try {
86
- // Sanitize the item to ensure no undefined values are sent
87
  const itemToSave = cleanData(item);
88
-
89
- const docRef = await addDoc(collection(db, COLLECTION_NAME), {
90
  ...itemToSave,
91
- createdAt: serverTimestamp() // Use server timestamp for consistency
92
  });
93
  return docRef.id;
94
  } catch (e) {
@@ -99,13 +117,10 @@ export const addItem = async (item: Omit<DataItem, 'id' | 'createdAt'>): Promise
99
 
100
  export const updateItem = async (id: string, item: Partial<DataItem>) => {
101
  try {
102
- const docRef = doc(db, COLLECTION_NAME, id);
103
- // Remove id and createdAt from the update payload to prevent overwriting logic
104
  const { id: _, createdAt: __, ...updateData } = item;
105
-
106
- // Sanitize the data
107
  const sanitizedUpdateData = cleanData(updateData);
108
-
109
  await updateDoc(docRef, {
110
  ...sanitizedUpdateData,
111
  updatedAt: serverTimestamp()
@@ -117,9 +132,10 @@ export const updateItem = async (id: string, item: Partial<DataItem>) => {
117
  };
118
 
119
  // Soft delete (moves item to trash bin)
120
- export const deleteItem = async (id: string) => {
121
  try {
122
- const docRef = doc(db, COLLECTION_NAME, id);
 
123
  await updateDoc(docRef, {
124
  isDeleted: true,
125
  deletedAt: Date.now()
@@ -131,9 +147,10 @@ export const deleteItem = async (id: string) => {
131
  };
132
 
133
  // Restore item from trash bin
134
- export const restoreItem = async (id: string) => {
135
  try {
136
- const docRef = doc(db, COLLECTION_NAME, id);
 
137
  await updateDoc(docRef, {
138
  isDeleted: false,
139
  deletedAt: null
@@ -144,26 +161,29 @@ export const restoreItem = async (id: string) => {
144
  }
145
  };
146
 
147
- // Restore multiple items
148
- export const restoreAllItems = async (ids: string[]) => {
149
  try {
150
- await Promise.all(ids.map(id => restoreItem(id)));
 
151
  } catch (e) {
152
- console.error("Error restoring all items: ", e);
153
  throw e;
154
  }
155
  };
156
 
157
- // Permanently delete document from Firestore
158
- export const permanentlyDeleteItem = async (id: string) => {
159
  try {
160
- await deleteDoc(doc(db, COLLECTION_NAME, id));
161
  } catch (e) {
162
- console.error("Error permanently deleting document: ", e);
163
  throw e;
164
  }
165
  };
166
 
 
 
167
  // Permanently empty trash bin
168
  export const emptyTrash = async (ids: string[]) => {
169
  try {
 
13
  } from 'firebase/firestore';
14
  import { DataItem } from '../types';
15
 
16
+ // Configuration for project code-by-dante
17
  const firebaseConfig = {
18
+ apiKey: "AIzaSyBv55pNiZ_3zXkulC_qWzzbzuenql570gM",
19
+ authDomain: "code-by-dante.firebaseapp.com",
20
+ projectId: "code-by-dante",
21
+ storageBucket: "code-by-dante.firebasestorage.app",
22
+ messagingSenderId: "752222250917",
23
+ appId: "1:752222250917:web:6f7eb8b4abba2efc2daa4c"
 
24
  };
25
 
26
  const app = initializeApp(firebaseConfig);
27
  const db = getFirestore(app);
 
28
 
29
  /**
30
  * Helper function to remove fields with 'undefined' values from an object.
 
41
  };
42
 
43
  export const subscribeToItems = (callback: (items: DataItem[]) => void) => {
44
+ let foldersData: DataItem[] = [];
45
+ let voicesData: DataItem[] = [];
46
+
47
+ const updateAll = () => {
48
+ const combinedMap = new Map<string, DataItem>();
49
+ foldersData.forEach(item => combinedMap.set(item.id, item));
50
+ voicesData.forEach(item => combinedMap.set(item.id, item));
51
+ callback(Array.from(combinedMap.values()));
52
+ };
53
+
54
+ // Subscribe to folders in code-by-dante
55
+ const unsubFolders = onSnapshot(collection(db, 'folders'), (snapshot) => {
56
+ foldersData = snapshot.docs.map(doc => {
57
  const data = doc.data();
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  return {
59
  id: doc.id,
60
+ title: data.name || data.title || 'Carpeta',
61
+ summary: 'Carpeta',
62
+ content: '',
63
+ isFolder: true,
64
+ parentId: data.parentId || null,
65
+ tags: [],
66
+ categories: [],
67
+ createdAt: data.createdAt?.toMillis ? data.createdAt.toMillis() : Date.now(),
68
  } as DataItem;
69
  });
70
+ updateAll();
71
+ }, (err) => console.error("Error reading folders:", err));
72
 
73
+ // Subscribe to voices in code-by-dante
74
+ const unsubVoices = onSnapshot(collection(db, 'voices'), (snapshot) => {
75
+ voicesData = snapshot.docs.map(doc => {
76
+ const data = doc.data();
77
+ return {
78
+ id: doc.id,
79
+ title: data.title || 'Voz',
80
+ summary: '',
81
+ content: '',
82
+ visitUrl: data.url || data.visitUrl || '',
83
+ downloadUrl: data.downloadUrl || '',
84
+ isFolder: false,
85
+ parentId: data.folderId || data.parentId || null,
86
+ tags: data.tags || [],
87
+ categories: data.categories || [],
88
+ linkGroups: data.linkGroups || [],
89
+ createdAt: data.createdAt?.toMillis ? data.createdAt.toMillis() : Date.now(),
90
+ } as DataItem;
91
+ });
92
+ updateAll();
93
+ }, (err) => console.error("Error reading voices:", err));
94
 
95
+ return () => {
96
+ unsubFolders();
97
+ unsubVoices();
98
+ };
 
 
99
  };
100
 
101
+ const getColName = (item?: Partial<DataItem>) => item?.isFolder ? 'folders' : 'voices';
102
+
103
  export const addItem = async (item: Omit<DataItem, 'id' | 'createdAt'>): Promise<string> => {
104
  try {
 
105
  const itemToSave = cleanData(item);
106
+ const targetCol = getColName(item);
107
+ const docRef = await addDoc(collection(db, targetCol), {
108
  ...itemToSave,
109
+ createdAt: serverTimestamp()
110
  });
111
  return docRef.id;
112
  } catch (e) {
 
117
 
118
  export const updateItem = async (id: string, item: Partial<DataItem>) => {
119
  try {
120
+ const targetCol = getColName(item);
121
+ const docRef = doc(db, targetCol, id);
122
  const { id: _, createdAt: __, ...updateData } = item;
 
 
123
  const sanitizedUpdateData = cleanData(updateData);
 
124
  await updateDoc(docRef, {
125
  ...sanitizedUpdateData,
126
  updatedAt: serverTimestamp()
 
132
  };
133
 
134
  // Soft delete (moves item to trash bin)
135
+ export const deleteItem = async (id: string, isFolder?: boolean) => {
136
  try {
137
+ const targetCol = isFolder ? 'folders' : 'voices';
138
+ const docRef = doc(db, targetCol, id);
139
  await updateDoc(docRef, {
140
  isDeleted: true,
141
  deletedAt: Date.now()
 
147
  };
148
 
149
  // Restore item from trash bin
150
+ export const restoreItem = async (id: string, isFolder?: boolean) => {
151
  try {
152
+ const targetCol = isFolder ? 'folders' : 'voices';
153
+ const docRef = doc(db, targetCol, id);
154
  await updateDoc(docRef, {
155
  isDeleted: false,
156
  deletedAt: null
 
161
  }
162
  };
163
 
164
+ // Permanently delete item
165
+ export const permanentlyDeleteItem = async (id: string, isFolder?: boolean) => {
166
  try {
167
+ const targetCol = isFolder ? 'folders' : 'voices';
168
+ await deleteDoc(doc(db, targetCol, id));
169
  } catch (e) {
170
+ console.error("Error permanently deleting document: ", e);
171
  throw e;
172
  }
173
  };
174
 
175
+ // Restore multiple items
176
+ export const restoreAllItems = async (items: {id: string, isFolder: boolean}[]) => {
177
  try {
178
+ await Promise.all(items.map(item => restoreItem(item.id, item.isFolder)));
179
  } catch (e) {
180
+ console.error("Error restoring all items: ", e);
181
  throw e;
182
  }
183
  };
184
 
185
+
186
+
187
  // Permanently empty trash bin
188
  export const emptyTrash = async (ids: string[]) => {
189
  try {