-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebaseDB.js
More file actions
181 lines (166 loc) · 5.09 KB
/
firebaseDB.js
File metadata and controls
181 lines (166 loc) · 5.09 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
// Firebase Modules
import { initializeApp } from "firebase/app";
import {
getDatabase,
ref,
push,
set,
get,
child,
onValue,
runTransaction,
} from "firebase/database";
import APIKeys from "./APIKeys.js";
const firebaseConfig = {
apiKey: APIKeys.apiKey,
authDomain: APIKeys.authDomain,
projectId: APIKeys.projectId,
storageBucket: APIKeys.storageBucket,
messagingSenderId: APIKeys.messagingSenderId,
appId: APIKeys.appId,
};
const app = initializeApp(firebaseConfig);
console.log("Firebase App Initialized:", app.name);
//pushes an image to the database with location, link, and time attributes
export const firebasePushData = (latitude, longitude, imageLink) => {
try {
const db = getDatabase(app);
const locationRef = push(ref(db, "/images")); // Images
set(locationRef, {
latitude: latitude,
longitude: longitude,
imageLink: imageLink,
time: new Date().getTime(),
likes: 0,
});
console.log("Data Pushed");
} catch (error) {
console.error("Error pushing data to Firebase:", error);
}
};
//pulls data from the firebase realtime database
export const firebasePullData = async () => {
try {
const db = getDatabase(app);
const imagesRef = ref(db, "images");
const snapshot = await get(imagesRef);
if (snapshot.exists()) {
const imageList = snapshot.val();
// convert to an array
const imageArray = Object.keys(imageList).map((key) => ({
id: key,
...imageList[key],
}));
return imageArray.reverse();
}
return [];
} catch (error) {
console.error("Error pulling from database: ", error);
return [];
}
};
export const getLikes = (imageList) => {
try {
const likesList = [];
Object.keys(imageList).forEach((image) => {
const { likes } = imageList[image]; //extracts likes for each image
likesList.push(likes || 0);
console.log("likes", likes);
});
return likesList;
} catch (error) {
console.error("error getting likes", error);
return [];
}
};
export const addLike = async (imageId) => {
try {
const db = getDatabase(app);
const refUpdate = ref(db, `/images/${imageId}/likes`);
await runTransaction(refUpdate, (currentLikes) => {
if (currentLikes === 0) {
return 1;
} else {
return currentLikes + 1;
}
});
console.log(`added like ${imageId}`);
} catch (error) {
console.error("Error adding like", error);
}
};
export const iterateData = (imageList) => {
try {
Object.keys(imageList).forEach((image) => {
const { imageLink, latitude, longitude, time } = imageList[image]; //extracts values of each attribute for the image
console.log(`ImageID ${image}`); //printing each attribute to console
console.log("imageLink", imageLink);
console.log("lat", latitude);
console.log("long", longitude);
console.log("time", time);
});
} catch (error) {
console.error("Error iterating: ", error);
}
};
export const getLocations = (imageList) => {
try {
const locations = [];
Object.keys(imageList).forEach((image) => {
const { imageLink, latitude, longitude } = imageList[image];
locations.push({
latitude: latitude,
longitude: longitude,
imageLink: imageLink,
}); //push coordinates with the image link to the list as a dict
});
return locations;
} catch (error) {
console.error("Error iterating: ", error);
}
};
export const getBuilding = async (latitude, longitude) => {
if (typeof latitude === "number" && typeof longitude === "number") {
if (
latitude >= -90 &&
latitude <= 90 &&
longitude >= -180 &&
longitude <= 180
) {
const reverseGeocodingUrl = `https://api.geoapify.com/v1/geocode/reverse?lat=${latitude}&lon=${longitude}&apiKey=${APIKeys.geoCodeApiID}`;
console.log("reverse geocoding", reverseGeocodingUrl);
const response = await fetch(reverseGeocodingUrl);
if (!response.ok) {
console.error("Reverse geocoding API call failed:", response.status);
return;
}
const featureCollection = await response.json();
if (featureCollection.features.length === 0) {
console.log("The address is not found");
return;
}
//parses through the address and returns just the building name
const foundAddress = featureCollection.features[0].properties.formatted;
console.log("Address Found:", foundAddress.split(",")[0]);
return foundAddress.split(",")[0];
} else {
console.log("invalid latitude or longitude range.");
}
} else {
console.log("invalid latitude or longitude range.");
}
};
export const getAllBuildings = async (locationList) => {
try {
const buildingNames = await Promise.all(
locationList.map(async (image) => {
const buildingName = await getBuilding(image.latitude, image.longitude);
return buildingName; // collect each building name
})
);
return buildingNames; // return the array of building names
} catch (error) {
console.error("Error getting all buildings:", error);
return [];
}
};