-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.ts
More file actions
72 lines (60 loc) · 2.01 KB
/
database.ts
File metadata and controls
72 lines (60 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* SIMULATED SQLITE3 DATABASE
*
* Since this is a frontend-only application (React), we cannot directly bind to
* the C++ 'sqlite3' library used in Node.js.
*
* This file acts as a mock Database Adapter. It simulates SQL queries but
* persists the data to the browser's localStorage.
*
* To switch to real SQLite:
* 1. Set up a Node.js/Express backend.
* 2. Replace this logic to fetch() from your API endpoints.
*/
import { generateId } from "./utils";
interface User {
id: string;
username: string;
passwordHash: string; // In a real app, hash this!
createdAt: number;
}
const DB_KEY = 'deck_of_thoughts_users_db';
class SimulatedDB {
private users: User[];
constructor() {
const data = localStorage.getItem(DB_KEY);
this.users = data ? JSON.parse(data) : [];
}
private save() {
localStorage.setItem(DB_KEY, JSON.stringify(this.users));
}
// Simulate: SELECT * FROM users WHERE username = ?
findUser(username: string): User | undefined {
return this.users.find(u => u.username === username);
}
// Simulate: INSERT INTO users (id, username, password) VALUES (?, ?, ?)
createUser(username: string, password: string): User {
const existing = this.findUser(username);
if (existing) {
throw new Error("Username already taken");
}
const newUser: User = {
id: generateId(),
username,
passwordHash: password, // WARNING: Plaintext for demo only. Use bcrypt in production.
createdAt: Date.now()
};
this.users.push(newUser);
this.save();
return newUser;
}
// Simulate: SELECT * FROM users WHERE username = ? AND password = ?
loginUser(username: string, password: string): User {
const user = this.findUser(username);
if (!user || user.passwordHash !== password) {
throw new Error("Invalid credentials");
}
return user;
}
}
export const db = new SimulatedDB();