import * as schema from './schema/schema.ts'; import { eq } from 'drizzle-orm'; import { db } from "./db.ts"; import { BlogNotFoundError } from '@/lib/errors.ts'; import type { Blog } from '@/lib/types.ts'; /** * Retrieves the given user's blogs. * @param id User's ID. * @returns Blogs with posts inside. */ export async function get_user_blogs(id: number) { const result = await db.query.blogs.findMany({ where: { user_id: id }, with: { posts: { orderBy: { id: "desc", }, } } }); return result; } /** * Retrieves a blog, if the user owns it (optional). Feed it the blog's UUID and user's ID (optional). Might error with `BlogNotFoundError`. * @param uuid Blog's UUID. * @param user_id User's ID. * @returns Blog. */ export async function get_blog(uuid: string, user_id?: number) { const result = await db.query.blogs.findFirst({ where: { user_id: user_id, uuid, }, with: { posts: true } }); if (!result) throw new BlogNotFoundError(); return result; } /** * Retrieves a blog. Feed it the blog's domain. Might error with `BlogNotFoundError`. * @param uuid Blog's subdomain. * @returns Blog. */ export async function get_blog_domain(subdomain: string): Promise { const result = await db.query.blogs.findFirst({ where: { subdomain, }, with: { posts: { where: { published_at: { isNotNull: true } } } } }); if (!result) throw new BlogNotFoundError(); return result; }