Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | 103x 18x 18x 18x 15x 3x 8x 8x 8x 4x 2x 2x 2x 2x 2x 1x 1x 1x 2x 1x 2x 2x 1x 1x 3x 3x 2x 2x 4x 4x 1x 4x 4x 2x 2x 2x 2x 2x 2x 2x 26x 26x 26x 7x 2x 5x 26x 2x 26x 9x 5x 2x 3x 2x 21x 1x 26x 1x 26x 2x 1x 1x 26x 1x 26x 1x 26x 5x 5x 26x 8x 18x 1x 26x 26x | // Data Access Layer for Blogs (core blog operations)
import { eq, like, sql, desc, and, inArray, lt, or } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { Blog, NewBlog } from "../db/schema";
import { sanitizeSearchInput } from "../lib/utils";
export type BlogFilters = {
status?: string | string[];
blogType?: string;
categoryId?: string; // single category
categoryIds?: string; // comma-separated for multi-select
cityId?: string;
ideaSource?: string | string[];
ideaSourceProId?: string;
createdBy?: string;
search?: string;
proId?: string; // Filter by blogs featuring this pro
// Marketplace-only: keep only blogs that are either editorial (no approved
// author attribution) or have at least one approved attribution whose pro
// is published. Mirrors the in-memory filter the marketplace /blogs route
// used to apply, so findAll/count stay honest w.r.t. paginated output.
requirePublishedAuthor?: boolean;
};
export class BlogsDal {
constructor(private db: DrizzleD1Database<typeof schema>) {}
async findAll(
filters: BlogFilters = {},
offset = 0,
limit = 20,
): Promise<Blog[]> {
const conditions = this.buildBlogConditions(filters);
const query = this.db
.select()
.from(schema.blogs)
.orderBy(desc(schema.blogs.dateCreated))
.limit(limit)
.offset(offset);
if (conditions.length > 0) {
return query.where(and(...conditions));
}
return query;
}
async count(filters: BlogFilters = {}): Promise<number> {
const conditions = this.buildBlogConditions(filters);
const query = this.db
.select({ count: sql<number>`count(*)` })
.from(schema.blogs);
const result =
conditions.length > 0
? await query.where(and(...conditions))
: await query;
return result[0]?.count ?? 0;
}
async findById(id: string): Promise<Blog | undefined> {
const result = await this.db
.select()
.from(schema.blogs)
.where(eq(schema.blogs.id, id))
.limit(1);
return result[0];
}
async findBySlug(slug: string): Promise<Blog | undefined> {
const result = await this.db
.select()
.from(schema.blogs)
.where(eq(schema.blogs.slug, slug))
.limit(1);
return result[0];
}
/**
* Bulk fetch blogs by IDs (N+1 optimization)
* @param ids Array of blog IDs
* @returns Map of blogId -> Blog
*/
async findByIds(ids: string[]): Promise<Map<string, Blog>> {
if (ids.length === 0) return new Map();
const result = await this.db
.select()
.from(schema.blogs)
.where(inArray(schema.blogs.id, ids));
const map = new Map<string, Blog>();
for (const blog of result) {
map.set(blog.id, blog);
}
return map;
}
async create(data: NewBlog): Promise<Blog> {
const result = await this.db.insert(schema.blogs).values(data).returning();
if (!result[0]) {
throw new Error("Blog insert returned no row");
}
return result[0];
}
async update(
id: string,
data: Partial<Omit<Blog, "id" | "dateCreated">>,
): Promise<Blog | undefined> {
const result = await this.db
.update(schema.blogs)
.set({ ...data, dateUpdated: new Date() })
.where(eq(schema.blogs.id, id))
.returning();
return result[0];
}
async delete(id: string): Promise<boolean> {
const result = await this.db
.delete(schema.blogs)
.where(eq(schema.blogs.id, id))
.returning();
return result.length > 0;
}
async slugExists(slug: string, excludeId?: string): Promise<boolean> {
const conditions = [eq(schema.blogs.slug, slug)];
if (excludeId) {
conditions.push(sql`${schema.blogs.id} != ${excludeId}`);
}
const result = await this.db
.select({ count: sql<number>`count(*)` })
.from(schema.blogs)
.where(and(...conditions));
return (result[0]?.count ?? 0) > 0;
}
async publish(id: string): Promise<Blog | undefined> {
const now = new Date();
const result = await this.db
.update(schema.blogs)
.set({
status: "published",
publishedAt: now,
dateUpdated: now,
})
.where(eq(schema.blogs.id, id))
.returning();
return result[0];
}
async findPendingApprovalOlderThan(days: number) {
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
return this.db
.select()
.from(schema.blogs)
.where(
and(
eq(schema.blogs.status, "pending_approval"),
lt(schema.blogs.dateCreated, cutoff),
),
);
}
async unpublish(id: string): Promise<Blog | undefined> {
const result = await this.db
.update(schema.blogs)
.set({
status: "draft",
publishedAt: null,
dateUpdated: new Date(),
})
.where(eq(schema.blogs.id, id))
.returning();
return result[0];
}
private buildBlogConditions(filters: BlogFilters) {
const conditions = [];
// Category and free-text search are BOTH "discovery" intents from the
// homeowner. When only one is set, behavior is unchanged. When both are
// set, AND'ing them returns empty for the common case
// (e.g. "kitchen" typed while Bedroom category is selected) — see #312.
// We treat category and search as an OR group so either match wins.
const discoveryConditions: ReturnType<typeof or>[] = [];
if (filters.status) {
if (Array.isArray(filters.status)) {
conditions.push(
inArray(schema.blogs.status, filters.status as Blog["status"][]),
);
} else {
conditions.push(
eq(schema.blogs.status, filters.status as Blog["status"]),
);
}
}
if (filters.blogType) {
conditions.push(
eq(schema.blogs.blogType, filters.blogType as Blog["blogType"]),
);
}
if (filters.categoryIds) {
const ids = filters.categoryIds.split(",").map((id) => id.trim()).filter(Boolean);
if (ids.length === 1) {
discoveryConditions.push(eq(schema.blogs.categoryId, ids[0]));
} else if (ids.length > 1) {
discoveryConditions.push(inArray(schema.blogs.categoryId, ids));
}
} else if (filters.categoryId) {
discoveryConditions.push(eq(schema.blogs.categoryId, filters.categoryId));
}
if (filters.cityId) {
conditions.push(eq(schema.blogs.cityId, filters.cityId));
}
if (filters.ideaSource) {
if (Array.isArray(filters.ideaSource)) {
conditions.push(
inArray(schema.blogs.ideaSource, filters.ideaSource as Blog["ideaSource"][]),
);
} else {
conditions.push(
eq(schema.blogs.ideaSource, filters.ideaSource as Blog["ideaSource"]),
);
}
}
if (filters.ideaSourceProId) {
conditions.push(
eq(schema.blogs.ideaSourceProId, filters.ideaSourceProId),
);
}
if (filters.createdBy) {
conditions.push(eq(schema.blogs.createdBy, filters.createdBy));
}
if (filters.search) {
const sanitized = sanitizeSearchInput(filters.search);
discoveryConditions.push(
or(
like(schema.blogs.title, `%${sanitized}%`),
like(schema.blogs.content, `%${sanitized}%`),
),
);
}
// Combine discovery conditions: single → AND into base, multiple → OR group
// so category OR search wins.
if (discoveryConditions.length === 1) {
conditions.push(discoveryConditions[0]);
} else if (discoveryConditions.length > 1) {
conditions.push(or(...discoveryConditions));
}
/* v8 ignore start -- proId filter requires subquery handled at service layer, body intentionally empty */
if (filters.proId) {
// Filter by blogs featuring this pro - requires subquery
// This will be handled by a join in the service layer if needed
// For now, we'll just note this needs special handling
}
/* v8 ignore stop */
Iif (filters.requirePublishedAuthor) {
// Keep a blog if ANY approved attribution has a published pro, OR if
// the blog has no approved author attribution at all (editorial).
// Written against physical column names to keep the Drizzle sql
// template simple; column names map to schema.blogPros fields.
conditions.push(sql`(
EXISTS (
SELECT 1 FROM blog_pros AS bp
INNER JOIN pros AS p ON p.id = bp.pro_id
WHERE bp.blog_id = ${schema.blogs.id}
AND bp.approval_status = 'approved'
AND p.status = 'published'
)
OR NOT EXISTS (
SELECT 1 FROM blog_pros AS bp2
WHERE bp2.blog_id = ${schema.blogs.id}
AND bp2.attribution_type = 'author'
AND bp2.approval_status = 'approved'
)
)`);
}
return conditions;
}
}
|