UNPKG

@braindb/core

Version:

markdown-graph-content-layer-database

40 lines (39 loc) 1.37 kB
import { Document } from "./Document.js"; import { document } from "./schema.js"; import { asc, desc, eq, and, sql } from "drizzle-orm"; export function documentsSync(db, options) { let query = db.select({ path: document.path }).from(document); const where = []; if (options?.slug !== undefined) { where.push(eq(document.slug, options?.slug)); } if (options?.url !== undefined) { where.push(eq(document.url, options?.url)); } if (options?.frontmatter !== undefined) { Object.entries(flattenObj(options?.frontmatter)).forEach(([key, value]) => where.push(eq(sql `${document.frontmatter}->>${"$." + key}`, value))); } const order = []; if (options?.sort !== undefined) { const dir = options?.sort?.[1] === "asc" ? asc : desc; order.push(dir(document.updated_at)); } return query .where(and(...where)) .orderBy(...order) .all() .map(({ path }) => new Document(db, path)); } function flattenObj(obj, parent, res = Object.create(null)) { for (let key in obj) { const propName = parent ? parent + "." + key : key; const value = obj[key]; if (typeof value == "object" && value !== null) { flattenObj(value, propName, res); } else { res[propName] = value; } } return res; }