198 lines
6.2 KiB
JavaScript
198 lines
6.2 KiB
JavaScript
// Phase B — seed mock content into PostgreSQL.
|
|
// Usage: node db/seed.mjs (re-runnable; uses upsert by primary key)
|
|
// Reads DATABASE_URL from .env.local if not already in the environment.
|
|
|
|
import { existsSync, readFileSync } from "node:fs";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import pg from "pg";
|
|
|
|
import { courses } from "../src/lib/mock/courses.ts";
|
|
import {
|
|
campaignBanners,
|
|
faculty,
|
|
legalPages,
|
|
stats,
|
|
} from "../src/lib/mock/site.ts";
|
|
import {
|
|
SEED_COURSE_CATEGORIES,
|
|
SEED_COURSE_TAGS,
|
|
} from "../src/lib/taxonomy.ts";
|
|
|
|
import {
|
|
campaignBannerToRow,
|
|
courseToRow,
|
|
facultyMemberToRow,
|
|
legalPageToRow,
|
|
siteStatToRow,
|
|
} from "../src/lib/db/mappers.ts";
|
|
|
|
if (!process.env.DATABASE_URL) {
|
|
const envPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".env.local");
|
|
if (existsSync(envPath)) {
|
|
for (const line of readFileSync(envPath, "utf8").split(/\r?\n/)) {
|
|
const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
|
|
if (match && !(match[1] in process.env)) {
|
|
process.env[match[1]] = match[2];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!process.env.DATABASE_URL) {
|
|
console.error("DATABASE_URL is not set and .env.local was not found.");
|
|
process.exit(1);
|
|
}
|
|
|
|
const { Client } = pg;
|
|
|
|
async function upsertByKey(client, table, rows, columns, key = "id") {
|
|
if (rows.length === 0) return 0;
|
|
const placeholders = columns.map((_, i) => `$${i + 1}`).join(", ");
|
|
const updates = columns
|
|
.filter((c) => c !== key)
|
|
.map((c) => `${c} = EXCLUDED.${c}`)
|
|
.join(", ");
|
|
const sql = `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${placeholders})
|
|
ON CONFLICT (${key}) DO UPDATE SET ${updates}`;
|
|
for (const row of rows) {
|
|
const values = columns.map((c) => row[c]);
|
|
await client.query(sql, values);
|
|
}
|
|
return rows.length;
|
|
}
|
|
|
|
async function main() {
|
|
const client = new Client({ connectionString: process.env.DATABASE_URL });
|
|
await client.connect();
|
|
|
|
try {
|
|
const results = [];
|
|
const upsert = (table, rows, columns, key) =>
|
|
upsertByKey(client, table, rows, columns, key).then((n) => {
|
|
results.push([table, n]);
|
|
});
|
|
|
|
await upsert(
|
|
"course_categories",
|
|
SEED_COURSE_CATEGORIES.map((c) => ({
|
|
id: c.id,
|
|
slug: c.slug,
|
|
label: c.label,
|
|
sort_order: c.sortOrder,
|
|
show_in_filter: true,
|
|
published: true,
|
|
})),
|
|
["id", "slug", "label", "sort_order", "show_in_filter", "published"],
|
|
);
|
|
await upsert(
|
|
"course_tags",
|
|
SEED_COURSE_TAGS.map((t) => ({
|
|
id: t.id,
|
|
slug: t.slug,
|
|
label: t.label,
|
|
sort_order: t.sortOrder,
|
|
show_in_nav: t.showInNav,
|
|
show_in_filter: true,
|
|
published: true,
|
|
})),
|
|
[
|
|
"id",
|
|
"slug",
|
|
"label",
|
|
"sort_order",
|
|
"show_in_nav",
|
|
"show_in_filter",
|
|
"published",
|
|
],
|
|
);
|
|
|
|
await upsert("courses", courses.map(courseToRow), [
|
|
"id", "slug", "title", "summary", "duration_hours", "format", "price",
|
|
"registration_url", "poster_image_url", "brochure_image_url", "image_url",
|
|
"lead_html", "body_html", "seo_description", "published", "featured",
|
|
"sort_order",
|
|
]);
|
|
const courseIds = courses.map((c) => c.id);
|
|
await client.query(
|
|
`DELETE FROM courses WHERE id <> ALL($1::text[])`,
|
|
[courseIds],
|
|
);
|
|
results.push(["courses_pruned", courseIds.length]);
|
|
|
|
await client.query(`DELETE FROM course_category_links`);
|
|
await client.query(`DELETE FROM course_tag_links`);
|
|
let catLinks = 0;
|
|
let tagLinks = 0;
|
|
for (const course of courses) {
|
|
for (const cat of course.categories ?? []) {
|
|
await client.query(
|
|
`INSERT INTO course_category_links (course_id, category_id)
|
|
VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
|
[course.id, cat.id],
|
|
);
|
|
catLinks += 1;
|
|
}
|
|
for (const tag of course.tags ?? []) {
|
|
await client.query(
|
|
`INSERT INTO course_tag_links (course_id, tag_id)
|
|
VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
|
[course.id, tag.id],
|
|
);
|
|
tagLinks += 1;
|
|
}
|
|
}
|
|
results.push(["course_category_links", catLinks]);
|
|
results.push(["course_tag_links", tagLinks]);
|
|
for (const table of [
|
|
"programs",
|
|
"events",
|
|
"articles",
|
|
"intersection_topics",
|
|
"alumni_stories",
|
|
"testimonials",
|
|
]) {
|
|
const deleted = await client.query(`DELETE FROM ${table}`);
|
|
results.push([`${table}_cleared`, deleted.rowCount]);
|
|
}
|
|
await upsert("faculty_members", faculty.map(facultyMemberToRow), [
|
|
"id", "name", "title", "focus", "bio", "image_url",
|
|
"email", "office", "phone", "department", "linkedin_url", "scholar_url",
|
|
"published",
|
|
]);
|
|
await upsert("campaign_banners", campaignBanners.map(campaignBannerToRow), [
|
|
"id", "version", "text", "href", "cta", "published",
|
|
]);
|
|
await upsert("legal_pages", legalPages.map(legalPageToRow), [
|
|
"slug", "title", "body", "published",
|
|
], "slug");
|
|
await upsert("site_stats", stats.map(siteStatToRow), [
|
|
"id", "value", "label", "published",
|
|
]);
|
|
|
|
const counts = await client.query(`
|
|
SELECT (SELECT count(*) FROM courses) AS courses,
|
|
(SELECT count(*) FROM programs) AS programs,
|
|
(SELECT count(*) FROM events) AS events,
|
|
(SELECT count(*) FROM articles) AS articles,
|
|
(SELECT count(*) FROM intersection_topics) AS topics,
|
|
(SELECT count(*) FROM faculty_members) AS faculty,
|
|
(SELECT count(*) FROM alumni_stories) AS alumni,
|
|
(SELECT count(*) FROM campaign_banners) AS banners,
|
|
(SELECT count(*) FROM legal_pages) AS legal,
|
|
(SELECT count(*) FROM site_stats) AS stats,
|
|
(SELECT count(*) FROM testimonials) AS testimonials,
|
|
(SELECT count(*) FROM articles WHERE featured = true AND published = true) AS featured_articles
|
|
`);
|
|
|
|
console.log("seed_rows:");
|
|
for (const [table, n] of results) {
|
|
console.log(` ${table}: ${n}`);
|
|
}
|
|
console.log("db_counts:", JSON.stringify(counts.rows[0]));
|
|
} finally {
|
|
await client.end().catch(() => {});
|
|
}
|
|
}
|
|
|
|
await main(); |