Skip to content

03-常用代码

647字约2分钟

2025-07-15

Nexjs 中用到

const { execSync } = require("child_process")
const path = require("path")

async function setup() {
  try {
    console.log("🚀 Setting up Personal Blog...")

    // Install dependencies
    console.log("📦 Installing dependencies...")
    execSync("npm install", { stdio: "inherit" })

    // Generate Prisma client
    console.log("🔧 Generating Prisma client...")
    execSync("npx prisma generate", { stdio: "inherit" })

    // Run database migrations
    console.log("🗄️ Setting up database...")
    execSync("npx prisma db push", { stdio: "inherit" })

    // Seed database
    console.log("🌱 Seeding database...")
    execSync("npx tsx lib/seed.ts", { stdio: "inherit" })

    // Migrate existing posts
    console.log("📚 Migrating posts...")
    execSync("npx tsx scripts/migrate-posts.ts", { stdio: "inherit" })

    console.log("✅ Setup completed successfully!")
    console.log("\n🎉 Your blog is ready!")
    console.log("\nNext steps:")
    console.log("1. Run: npm run dev")
    console.log("2. Visit: http://localhost:3000")
    console.log("3. Admin panel: http://localhost:3000/admin/login")
    console.log("4. Login with: admin / admin123")
  } catch (error) {
    console.error("❌ Setup failed:", error.message)
    process.exit(1)
  }
}

setup()
import { prisma } from "../lib/prisma"
import { getAllPosts } from "../lib/posts-legacy"
import { slugify } from "../lib/utils"

export async function migratePosts() {
  try {
    console.log("📚 Starting post migration...")

    // Get categories and tags
    const categories = await prisma.category.findMany()
    const tags = await prisma.tag.findMany()

    const posts = await getAllPosts()

    for (const post of posts) {
      console.log(`📝 Migrating post: ${post.title}`)

      // Find or create categories for this post
      const postCategories = []
      for (const tagName of post.tags) {
        const category = categories.find(
          (c) => c.name.toLowerCase() === tagName.toLowerCase() || c.slug === slugify(tagName),
        )
        if (category) {
          postCategories.push(category.id)
        }
      }

      // Find or create tags for this post
      const postTags = []
      for (const tagName of post.tags) {
        let tag = tags.find((t) => t.name.toLowerCase() === tagName.toLowerCase() || t.slug === slugify(tagName))

        if (!tag) {
          tag = await prisma.tag.create({
            data: {
              name: tagName,
              slug: slugify(tagName),
            },
          })
          tags.push(tag)
        }
        postTags.push(tag.id)
      }

      // Create the post
      await prisma.post.upsert({
        where: { slug: post.slug },
        update: {
          title: post.title,
          content: post.content,
          excerpt: post.description,
          featuredImage: post.image,
          publishDate: new Date(post.date),
          status: "published",
          isFeatured: false, // You can manually set featured posts later
          readingTime: post.readingTime,
          categories: {
            deleteMany: {},
            create: postCategories.map((categoryId) => ({ categoryId })),
          },
          tags: {
            deleteMany: {},
            create: postTags.map((tagId) => ({ tagId })),
          },
        },
        create: {
          title: post.title,
          slug: post.slug,
          content: post.content,
          excerpt: post.description,
          featuredImage: post.image,
          publishDate: new Date(post.date),
          status: "published",
          isFeatured: false,
          readingTime: post.readingTime,
          categories: {
            create: postCategories.map((categoryId) => ({ categoryId })),
          },
          tags: {
            create: postTags.map((tagId) => ({ tagId })),
          },
        },
      })

      console.log(`✅ Migrated: ${post.title}`)
    }

    console.log("🎉 Post migration completed!")
  } catch (error) {
    console.error("❌ Post migration failed:", error)
    throw error
  }
}

// Run migration if called directly
if (require.main === module) {
  migratePosts()
    .then(() => {
      console.log("Migration completed")
      process.exit(0)
    })
    .catch((error) => {
      console.error("Migration failed:", error)
      process.exit(1)
    })
}

7.12 14:43 💡

人类的思维方式是:
- 遇到问题:现在脑海中搜索是否有解决办法
	- 如果有,则采取解决办法去解决
		- 定位问题是什么
		- 定位解决需要的方案
	- 如果没有
		- 定位问题是什么,复制错误内容
		- 先搜索各大搜索引擎,然后找到各大博客论坛解决
		- 目前是:问一下 AI 如何解决
- 执行任务:
	- 明确目标:做个人博客站点
	- 分析需求:需要什么布局,参考什么站点,如何设计
	- 技术栈选择:根据功能、自己的熟练程度选择合适的技术栈
	- 定位技术栈:搜集文档判断目前需要哪些技术、版本之间的一个关联
	- 学习官方最佳实践:根据技术的源头学习官方给出的最佳实践
- 困难解决:
	- 脑海中有一个各类知识的思维导图
	- 知道如果出现问题,该去哪里寻找答案解决