Files
heval/auth-app-backup/src/services/database.ts
2025-07-15 20:38:04 +02:00

139 lines
3.4 KiB
TypeScript

import SQLite from "react-native-sqlite-storage";
import { RegisterCredentials, User } from "../types";
SQLite.DEBUG(true);
SQLite.enablePromise(true);
class DatabaseService {
private db: SQLite.SQLiteDatabase | null = null;
async initDatabase(): Promise<void> {
try {
this.db = await SQLite.openDatabase({
name: "AuthApp.db",
location: "default",
});
await this.db.executeSql(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
firstName TEXT NOT NULL,
lastName TEXT NOT NULL,
createdAt TEXT NOT NULL
)
`);
console.log("Database initialized successfully");
} catch (error) {
console.error("Database initialization failed:", error);
throw error;
}
}
async registerUser(credentials: RegisterCredentials): Promise<User> {
if (!this.db) {
throw new Error("Database not initialized");
}
try {
const createdAt = new Date().toISOString();
const result = await this.db.executeSql(
"INSERT INTO users (email, password, firstName, lastName, createdAt) VALUES (?, ?, ?, ?, ?)",
[
credentials.email,
credentials.password,
credentials.firstName,
credentials.lastName,
createdAt,
]
);
const userId = result[0].insertId;
return {
id: userId,
email: credentials.email,
password: credentials.password,
firstName: credentials.firstName,
lastName: credentials.lastName,
createdAt,
};
} catch (error) {
console.error("User registration failed:", error);
throw error;
}
}
async loginUser(email: string, password: string): Promise<User | null> {
if (!this.db) {
throw new Error("Database not initialized");
}
try {
const result = await this.db.executeSql(
"SELECT * FROM users WHERE email = ? AND password = ?",
[email, password]
);
if (result[0].rows.length > 0) {
const userData = result[0].rows.item(0);
return {
id: userData.id,
email: userData.email,
password: userData.password,
firstName: userData.firstName,
lastName: userData.lastName,
createdAt: userData.createdAt,
};
}
return null;
} catch (error) {
console.error("User login failed:", error);
throw error;
}
}
async getUserByEmail(email: string): Promise<User | null> {
if (!this.db) {
throw new Error("Database not initialized");
}
try {
const result = await this.db.executeSql(
"SELECT * FROM users WHERE email = ?",
[email]
);
if (result[0].rows.length > 0) {
const userData = result[0].rows.item(0);
return {
id: userData.id,
email: userData.email,
password: userData.password,
firstName: userData.firstName,
lastName: userData.lastName,
createdAt: userData.createdAt,
};
}
return null;
} catch (error) {
console.error("Get user by email failed:", error);
throw error;
}
}
async closeDatabase(): Promise<void> {
if (this.db) {
await this.db.close();
this.db = null;
}
}
}
export default new DatabaseService();