今天來繼續製作Simple Auth App,昨天將API interface設計好,再來需要設定資料庫與ORM,由於作業重點不是在資料庫,就選擇簡易的SQLite來實作資料庫與TypeORM。
npm install typeorm sqlite3 reflect-metadata
建立ormconfig.json
{
"type": "sqlite",
"database": "simple-auth-app.db",
"synchronize": true,
"logging": false,
"entities": ["src/entity/**/*.ts"],
"migrations": ["src/migration/**/*.ts"],
"subscribers": ["src/subscriber/**/*.ts"]
}
建立src/entity
folder,在裡面新增User.ts
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ unique: true })
email: string;
@Column()
password: string;
@Column({ default: '' })
name: string;
@Column({ default: false })
emailVerified: boolean;
@Column({ nullable: true })
emailVerificationToken: string;
@Column({ default: 0 })
loginCount: number;
@CreateDateColumn()
signUpTimestamp: Date;
@UpdateDateColumn()
lastLoginTimestamp: Date;
}
然後在src/index.ts
中新增使用TypeORM連結資料庫的方法
import "reflect-metadata";
import express from "express";
import { createConnection } from "typeorm";
import { User } from "./entity/User";
createConnection().then(async connection => {
const userRepository = connection.getRepository(User);
const app = express();
const port = 3000;
app.use(express.json()); // Middleware for parsing JSON
// Register Route
app.post("/register", async (req, res) => {
const user = new User();
user.email = req.body.email;
user.password = req.body.password;
await userRepository.save(user);
res.json({ message: "User registered!" });
});
// ... Add other routes for login, email verification, etc.
app.listen(port, () => {
console.log(`Server started on http://localhost:${port}`);
});
}).catch(error => console.log(error));