2022-08-29 15:06:17 +00:00
|
|
|
import {
|
|
|
|
deleteDoc,
|
|
|
|
doc,
|
|
|
|
getDocs,
|
|
|
|
query,
|
|
|
|
updateDoc,
|
|
|
|
where,
|
|
|
|
} from 'firebase/firestore'
|
2022-09-27 22:30:07 +00:00
|
|
|
import { DateDoc, Post } from 'common/post'
|
|
|
|
import { coll, getValue, getValues, listenForValue } from './utils'
|
|
|
|
import { getUserByUsername } from './users'
|
2022-08-29 15:06:17 +00:00
|
|
|
|
|
|
|
export const posts = coll<Post>('posts')
|
|
|
|
|
|
|
|
export function postPath(postSlug: string) {
|
|
|
|
return `/post/${postSlug}`
|
|
|
|
}
|
|
|
|
|
|
|
|
export function updatePost(post: Post, updates: Partial<Post>) {
|
|
|
|
return updateDoc(doc(posts, post.id), updates)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function deletePost(post: Post) {
|
|
|
|
return deleteDoc(doc(posts, post.id))
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getPost(postId: string) {
|
|
|
|
return getValue<Post>(doc(posts, postId))
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getPostBySlug(slug: string) {
|
|
|
|
const q = query(posts, where('slug', '==', slug))
|
|
|
|
const docs = (await getDocs(q)).docs
|
|
|
|
return docs.length === 0 ? null : docs[0].data()
|
|
|
|
}
|
2022-08-30 12:39:10 +00:00
|
|
|
|
|
|
|
export function listenForPost(
|
|
|
|
postId: string,
|
|
|
|
setPost: (post: Post | null) => void
|
|
|
|
) {
|
|
|
|
return listenForValue(doc(posts, postId), setPost)
|
|
|
|
}
|
2022-09-23 19:11:50 +00:00
|
|
|
|
|
|
|
export async function listPosts(postIds?: string[]) {
|
|
|
|
if (postIds === undefined) return []
|
|
|
|
return Promise.all(postIds.map(getPost))
|
|
|
|
}
|
2022-09-27 22:30:07 +00:00
|
|
|
|
|
|
|
export async function getDateDocs() {
|
|
|
|
const q = query(posts, where('type', '==', 'date-doc'))
|
|
|
|
return getValues<DateDoc>(q)
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getDateDoc(username: string) {
|
|
|
|
const user = await getUserByUsername(username)
|
|
|
|
if (!user) return null
|
|
|
|
|
|
|
|
const q = query(
|
|
|
|
posts,
|
|
|
|
where('type', '==', 'date-doc'),
|
|
|
|
where('creatorId', '==', user.id)
|
|
|
|
)
|
|
|
|
const docs = await getValues<DateDoc>(q)
|
|
|
|
const post = docs.length === 0 ? null : docs[0]
|
|
|
|
return { post, user }
|
|
|
|
}
|