Commit 0d65860a authored by erlendoeien's avatar erlendoeien
Browse files

Add working movies without wishlist

parent 5c7e8eb0
{
"projects": {
"default": "clouds-movies"
}
}
{
"hosting": {
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
import useFilteredMovies from "./useFilteredMovies";
import useMovies from "./useMovies";
import useWishlist from "./useWishlist";
export { useFilteredMovies, useMovies, useWishlist };
import { getDatabase, onValue, push, ref as fbRef } from "@firebase/database";
import { ref, watch, onMounted, onBeforeUnmount, Ref } from "@vue/runtime-dom";
import { getUsername } from "../tools/databaseTools";
import { IListeners, IMovie } from "../types";
import { getAuth } from "@firebase/auth";
import unsubscibeListeners from "../tools/unsubscribeListeners";
export default function useFilteredMovies(
movies: Ref<IMovie[]>,
wishlist: Ref<number[]>
) {
const filteredMovies = ref<IMovie[]>([]);
const listeners: IListeners = { wishlist: () => {} };
const nonWishList = ({ id }: IMovie) => !wishlist.value.includes(id);
const filterMovies = () => {
if (!wishlist.value || wishlist.value.length === 0) return;
filteredMovies.value = movies.value.filter(nonWishList);
};
//TODO: add search query
watch(wishlist, filterMovies);
onBeforeUnmount(() => unsubscibeListeners(listeners));
return { filteredMovies };
}
import { getUsername } from "../tools/databaseTools";
import { getAuth } from "@firebase/auth";
import { ref } from "@vue/reactivity";
import { IListeners, IMovie } from "../types";
import { getDatabase, ref as fbRef } from "@firebase/database";
import { onMounted, onBeforeUnmount, Ref } from "@vue/runtime-dom";
import { onValue } from "firebase/database";
import unsubscibeListeners from "../tools/unsubscribeListeners";
export default function useMovies() {
const movies = ref([] as IMovie[]);
// const wishlist = ref<number[]>([]);
// const username = getUsername(getAuth().currentUser); //.onAuthStateChanged()
// const username = ref("");
const db = getDatabase();
// const wishlistRef = fbRef(db, `users/${username}/wishlist`);
const moviesRef = fbRef(db, "movies-list/");
const listeners: IListeners = { movies: () => {} };
const fetchMovies = () => {
listeners.movies = onValue(
moviesRef,
(snapshot) => {
movies.value = snapshot.val();
},
{ onlyOnce: true }
);
};
onMounted(fetchMovies);
onBeforeUnmount(() => unsubscibeListeners(listeners));
return { movies } as {movies:Ref<IMovie[]>};
}
import { getDatabase, onValue, push, ref as fbRef } from "@firebase/database";
import { ref, watch, onMounted, onBeforeUnmount, Ref } from "@vue/runtime-dom";
import { getUsername } from "../tools/databaseTools";
import { IListeners, IMovie } from "../types";
import { getAuth } from "@firebase/auth";
import unsubscibeListeners from "../tools/unsubscribeListeners";
export default function useWishlist(movies: Ref<IMovie[]>) {
const wishlist = ref<number[]>([]);
const username = getUsername(getAuth().currentUser);
const db = getDatabase();
const wishlistRef = fbRef(db, `users/${username}/wishlist`);
const listeners: IListeners = { wishlist: () => {} };
// Easier to simply overwrite entire wishlist in state
const fetchWishlist = () => {
listeners.wishlist = onValue(wishlistRef, (snapshot) => {
if (snapshot.exists()) {
wishlist.value = Object.values(snapshot.val());
console.log(`New wishlist`);
console.log(snapshot.val());
}
});
};
onMounted(fetchWishlist);
onBeforeUnmount(() => unsubscibeListeners(listeners));
const addWish = (id: number) => {
console.log("ADDED TO WISHLIST");
console.log(id);
push(wishlistRef, id);
};
const deleteWish = (id: number) => {
console.log("IMPLEMENT DELETE WISH")
}
return { wishlist, addWish, deleteWish };
}
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import { initializeApp } from "firebase/app";
import { FirebaseOptions, initializeApp } from "firebase/app";
import { getAuth, User } from "@firebase/auth";
import { getAnalytics } from "firebase/analytics";
import { getDatabase } from "firebase/database";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyDFmp4FBhsaMZfpAcvYdA7MMGGIy3kM80k",
authDomain: "clouds-movies.firebaseapp.com",
projectId: "clouds-movies",
storageBucket: "clouds-movies.appspot.com",
messagingSenderId: "814442811620",
appId: "1:814442811620:web:9369b30eb3594f1b9adcf1",
measurementId: "G-QN8WD1N9KW",
const firebaseConfig: FirebaseOptions = {
apiKey: import.meta.env.VITE_APIKEY as string,
authDomain: import.meta.env.VITE_AUTHDOMAIN as string,
projectId: import.meta.env.VITE_PROJECTID as string,
storageBucket: import.meta.env.VITE_STORAGEBUCKET as string,
messagingSenderId: import.meta.env.VITE_MESSAGINGSENDERID as string,
appId: import.meta.env.VITE_APPID as string,
measurementId: import.meta.env.VITE_MEASUREMENTID as string,
databaseURL: import.meta.env.VITE_DATABASEURL as string,
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
// const analytics = getAnalytics(firebaseApp);
export const getCurrentUser = (): Promise<User | null> => {
const auth = getAuth();
return new Promise((resolve, reject) => {
if (auth.currentUser) {
resolve(auth.currentUser);
}
const unsubscribe = auth.onAuthStateChanged((user) => {
unsubscribe();
resolve(user);
}, reject);
});
};
// export const getCurrentUser = (): Promise<User | null> => {
// const auth = getAuth();
// return new Promise((resolve, reject) => {
// if (auth.currentUser) {
// resolve(auth.currentUser);
// }
// const unsubscribe = auth.onAuthStateChanged((user) => {
// unsubscribe();
// resolve(user);
// }, reject);
// });
// };
const app = createApp(App);
app.use(router);
const app = createApp(App).use(router);
app.mount("#app");
import { createRouter, createWebHistory } from "vue-router";
import getCurrentUser from "../tools/getCurrentUser"
import { getCurrentUser } from "../tools/databaseTools";
const router = createRouter({
history: createWebHistory(),
......@@ -30,7 +30,7 @@ const router = createRouter({
router.beforeEach(async (to, from, next) => {
const requiresAuth = to.matched.some((record) => record.meta.requiresAuth);
const currentUser = await getCurrentUser()
const currentUser = await getCurrentUser();
if (currentUser && to.name === "root") next({ name: "movies" });
else if (requiresAuth && !currentUser) {
next({ name: "root" });
......
import { get, getDatabase, ref } from "@firebase/database";
// const moviesRef = ref(db, "movies-list/");
// const wishlistRef = ref(db, `users/${username}/whislist`);
class MovieService{
public db = getDatabase()
public moviesRef = ref(this.db, "movies-list")
public user = null
// const authListener = onAuth
async getMovies() {
return await get(this.moviesRef)
}
removeListeners() {
//TODO: CLEANUP FUNCTION TO BE CALLED
}
}// const username = await getUsername();
// console.log(username)
\ No newline at end of file
import { getAuth, User } from "@firebase/auth";
export default function getCurrentUser(): Promise<User | null> {
export function getCurrentUser(): Promise<User | null> {
const auth = getAuth();
return new Promise((resolve, reject) => {
if (auth.currentUser) {
......@@ -12,3 +12,15 @@ export default function getCurrentUser(): Promise<User | null> {
}, reject);
});
}
// export async function getUsername(): Promise<string | null | undefined> {
// return (await getCurrentUser())?.displayName
// ?.toLowerCase()
// .split(" ")
// .join("_");
// }
export function getUsername(user: User | null) {
if (!user) return ""
return user.displayName!.toLowerCase().split(" ").join("_")
}
import { IListeners } from "../types";
export default function unsubscibeListeners(listeners: IListeners) {
Object.values(listeners).forEach((unsubFunc) => unsubFunc());
}
import type { Unsubscribe } from "@firebase/util";
export interface IMovie {
id: number;
genre: string;
year: number;
title: string;
}
export interface IListeners {
[key: string]: Unsubscribe;
}
\ No newline at end of file
<template>
<h1>Favorites</h1>
<!-- <div v-if="wishlist.length === 0"> -->
<h3>No movies in wishlist</h3>
<!-- <button @click="redirect">Go to movies</button> -->
<!-- </div> -->
<!-- <div v-else>DISPLAY WISHLIST</div> -->
</template>
<script setup lang="ts">
import { getAuth } from "@firebase/auth";
import {
getDatabase,
ref as fb_ref,
onValue,
get,
set,
child,
} from "firebase/database";
import { onBeforeUnmount, ref } from "vue";
import { useRouter } from "vue-router";
import { getUsername } from "../tools/databaseTools";
import { IMovie } from "../types";
const wishlist = ref<IMovie[]>([]);
const db = getDatabase();
const username = getUsername(getAuth().currentUser); //.onAuthStateChanged()
const wishlistRef = fb_ref(db, `users/${username}`);
// get(whishlistRef).then((snapshot) => {
// if (snapshot.exists())
// })
const redirect = () => useRouter().push({ name: "movies" });
const moviesListener = onValue(wishlistRef, (snapshot) => {
if (!snapshot.exists()) {
console.log("SNAPSHOT DOES NOT EXIST");
// set(wishlistRef, {"wishlist"), {}).catch((e) => console.log(e));
} else {
console.log(`snapshot: ${snapshot.val()}`);
set(wishlistRef, null).catch((e) => console.log(e));
wishlist.value = snapshot.val();
}
});
onBeforeUnmount(() => {
moviesListener();
});
</script>
<template>
<h1>Movies</h1>
<div>
<div v-if="movies.length === 0">
<h3>Loading...</h3>
</div>
<table v-else>
<thead>
<th>Title</th>
<th>Year</th>
<th>Genre</th>
<th>Add to wishlist</th>
</thead>
<tr v-for="movie in filteredMovies" :key="movie.id">
<td>{{ movie.title }}</td>
<td>{{ movie.year }}</td>
<td>{{ movie.genre }}</td>
<td><button @click="addWish(movie.id)">WISHLIST</button></td>
</tr>
</table>
</div>
</template>
<script setup lang="ts">
import { useFilteredMovies, useMovies, useWishlist } from "../hooks";
// const movies = ref<IMovie[]>([]);
// const wishlist = ref<number[]>([]);
// const username = getUsername(getAuth().currentUser); //.onAuthStateChanged()
// const username = ref("");
// const db = getDatabase();
// const wishlistRef = fb_ref(db, `users/${username}/wishlist`);
// const moviesRef = fb_ref(db, "movies-list/");
// const listeners: IListeners = { wishlist: () => {}, movies: () => {} };
const { movies } = useMovies();
const { wishlist } = useWishlist(movies);
const { filteredMovies } = useFilteredMovies(movies, wishlist);
// onMounted(async () => {
// listeners.movies = onValue(
// moviesRef,
// (snapshot) => {
// movies.value = snapshot.val();
// },
// { onlyOnce: true }
// );
// listeners.wishlist = onValue(wishlistRef, (snapshot) => {
// if (snapshot.exists()) {
// wishlist.value = Object.values(snapshot.val());
// console.log(`New wishlist`);
// console.log(snapshot.val());
// }
// });
// });
// const filterMovies = () => {
// if (!wishlist.value || wishlist.value.length === 0) return;
// movies.value = movies.value.filter(({ id }) => !wishlist.value.includes(id));
// };
// watch(wishlist, filterMovies);
// const addToWishlist = (id: number) => {
// console.log("ADDED TO WISHLIST");
// console.log(id);
// push(wishlistRef, id);
// };
// onBeforeUnmount(() => {
// Object.values(listeners).forEach((unsub) => unsub());
// });
</script>
<style></style>
<style>
table,
th,
td {
border: 1px solid black;
padding: 16px;
}
</style>
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()]
})
export default ({ mode }) => {
process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
return defineConfig({
plugins: [vue()],
});
};
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment