Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
2.1 kB
4
Indexable
// import { ref, push, get, set, update, query, equalTo, orderByChild, orderByKey } from 'firebase/database';
import { ref, get, push, update } from 'firebase/database';
import { db } from '../firebase/config';

export const addPost = async (content, username, topicId) => {
  const post = {
    content,
    author: username,
    topicId,
    createdOn: Date.now(),
  };

  const { key } = push(ref(db, 'posts'), post);

  update(ref(db), {
    [`posts/${key}/id`]: key, // add the ID to the post
    [`users/${username}/posts/${key}`]: true, // connect the post with the user
    [`topics/${topicId}/posts/${key}`]: true, // connect the post with the topic
  });

  return key;
};

export const getAllPosts = async () => {
  const snapshot = await get(ref(db, 'posts'));

  if (!snapshot.exists()) {
    return [];
  }

  return Object.keys(snapshot.val()).map((key) => ({ ...snapshot.val()[key], id: key }));
};

export const getPostById = async (postId) => {
  const snapshot = await get(ref(db, `posts/${postId}`));

  return snapshot.val();
};

export const getPostsByIds = async (ids) => {
  const posts = await getAllPosts();

  return posts.filter((p) => ids.includes(p.id));
};

export const deletePost = async (postId, username, topicId) => {
  return update(ref(db), {
    [`topics/${topicId}/posts/${postId}`]: null,
    [`users/${username}/posts/${postId}`]: null,
    [`posts/${postId}`]: null,
  });
};

export const editPost = async (postId, content) => {
  return update(ref(db), {
    [`posts/${postId}/content`]: content,
    [`posts/${postId}/editedOn`]: Date.now(),
  });
};

export const togglePostLike = async (postId, username, author, like = true) => {
  const snapshot = await get(ref(db, `users/${author}/likesReceived`));
  const likesReceived = snapshot.val() || 0;

  return update(ref(db), {
    [`posts/${postId}/likedBy/${username}`]: like || null,
    [`users/${username}/likesGiven/${postId}`]: like || null,
    [`users/${author}/likesReceived`]: like === true ? likesReceived + 1 : likesReceived - 1,
  });
};