返回

**Next.js + TypeORM 實踐:打造博客系統(二)**

前端

接下來,我們將探討如何使用 TypeORM 初始化資料庫,為我們的 Next.js 部落格系統奠定堅實的基礎。我們將探討如何在不同的資料庫(例如 MySQL、PostgreSQL 和 SQLite)中設定和組態 TypeORM,以及如何使用 TypeORM 執行基本的 CRUD 操作(建立、讀取、更新和刪除)。透過追蹤這個系列的文章,您將學習如何構建一個功能完整的部落格系統,並掌握使用 Next.js 和 TypeORM 的技巧。

1. 安裝 TypeORM

首先,我們需要在專案中安裝 TypeORM。您可以使用以下指令來安裝:

npm install typeorm

2. 建立 TypeORM 實例

安裝好 TypeORM 之後,我們需要建立一個 TypeORM 實例。您可以參考以下範例:

import { TypeORMDataSource } from "@next-auth/typeorm-adapters";

export const typeOrmDataSource = new TypeORMDataSource({
  type: "postgres",
  host: "localhost",
  port: 5432,
  username: "postgres",
  password: "password",
  database: "next-auth-typeorm-example",
});

3. 設定 TypeORM 選項

在建立 TypeORM 實例之後,我們需要設定 TypeORM 選項。您可以參考以下範例:

import { TypeORMDataSource } from "@next-auth/typeorm-adapters";

export const typeOrmDataSource = new TypeORMDataSource({
  type: "postgres",
  host: "localhost",
  port: 5432,
  username: "postgres",
  password: "password",
  database: "next-auth-typeorm-example",
  // 其他 TypeORM 選項
  synchronize: true,
  logging: true,
});

4. 執行 CRUD 操作

設定好 TypeORM 之後,我們就可以開始執行 CRUD 操作了。以下是一些範例:

// 建立資料
const user = new User();
user.name = "John Doe";
user.email = "john.doe@example.com";
await typeOrmDataSource.manager.save(user);

// 讀取資料
const users = await typeOrmDataSource.manager.find(User);

// 更新資料
const user = await typeOrmDataSource.manager.findOne(User, 1);
user.name = "Jane Doe";
await typeOrmDataSource.manager.save(user);

// 刪除資料
const user = await typeOrmDataSource.manager.findOne(User, 1);
await typeOrmDataSource.manager.remove(user);

以上就是如何使用 TypeORM 初始化資料庫的基本介紹。如果您想了解更多關於 TypeORM 的資訊,您可以參考官方文件:https://typeorm.io/