56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
/**
|
|
* In-Memory User Repository
|
|
*
|
|
* Stores users in memory for demo/development purposes.
|
|
*/
|
|
|
|
import type { IUserRepository, StoredUser } from '../../domain/repositories/IUserRepository';
|
|
|
|
export class InMemoryUserRepository implements IUserRepository {
|
|
private users: Map<string, StoredUser> = new Map();
|
|
private emailIndex: Map<string, string> = new Map(); // email -> userId
|
|
|
|
constructor(initialUsers: StoredUser[] = []) {
|
|
for (const user of initialUsers) {
|
|
this.users.set(user.id, user);
|
|
this.emailIndex.set(user.email.toLowerCase(), user.id);
|
|
}
|
|
}
|
|
|
|
async findByEmail(email: string): Promise<StoredUser | null> {
|
|
const userId = this.emailIndex.get(email.toLowerCase());
|
|
if (!userId) return null;
|
|
return this.users.get(userId) ?? null;
|
|
}
|
|
|
|
async findById(id: string): Promise<StoredUser | null> {
|
|
return this.users.get(id) ?? null;
|
|
}
|
|
|
|
async create(user: StoredUser): Promise<StoredUser> {
|
|
if (this.emailIndex.has(user.email.toLowerCase())) {
|
|
throw new Error('Email already exists');
|
|
}
|
|
this.users.set(user.id, user);
|
|
this.emailIndex.set(user.email.toLowerCase(), user.id);
|
|
return user;
|
|
}
|
|
|
|
async update(user: StoredUser): Promise<StoredUser> {
|
|
const existing = this.users.get(user.id);
|
|
if (!existing) {
|
|
throw new Error('User not found');
|
|
}
|
|
// If email changed, update index
|
|
if (existing.email.toLowerCase() !== user.email.toLowerCase()) {
|
|
this.emailIndex.delete(existing.email.toLowerCase());
|
|
this.emailIndex.set(user.email.toLowerCase(), user.id);
|
|
}
|
|
this.users.set(user.id, user);
|
|
return user;
|
|
}
|
|
|
|
async emailExists(email: string): Promise<boolean> {
|
|
return this.emailIndex.has(email.toLowerCase());
|
|
}
|
|
} |