61 lines
1.6 KiB
JavaScript
61 lines
1.6 KiB
JavaScript
import fs from 'fs/promises';
|
|
import path from 'path';
|
|
import { fileURLToPath } from 'url';
|
|
import { IUserRepository } from '../Domain/IUserRepository.js';
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
const USER_FILE = path.join(__dirname, 'user.json');
|
|
|
|
export class UserRepository extends IUserRepository {
|
|
async getAll() {
|
|
try {
|
|
const data = await fs.readFile(USER_FILE, 'utf-8');
|
|
return JSON.parse(data);
|
|
} catch (error) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
async getById(id) {
|
|
const users = await this.getAll();
|
|
return users.find(user => user.id === id);
|
|
}
|
|
|
|
async create(user) {
|
|
const users = await this.getAll();
|
|
const newUser = {
|
|
id: Date.now().toString(),
|
|
...user,
|
|
createdAt: new Date().toISOString()
|
|
};
|
|
users.push(newUser);
|
|
await fs.writeFile(USER_FILE, JSON.stringify(users, null, 2));
|
|
return newUser;
|
|
}
|
|
|
|
async update(id, userData) {
|
|
const users = await this.getAll();
|
|
const index = users.findIndex(user => user.id === id);
|
|
if (index === -1) return null;
|
|
|
|
users[index] = {
|
|
...users[index],
|
|
...userData,
|
|
id: users[index].id,
|
|
updatedAt: new Date().toISOString()
|
|
};
|
|
await fs.writeFile(USER_FILE, JSON.stringify(users, null, 2));
|
|
return users[index];
|
|
}
|
|
|
|
async delete(id) {
|
|
const users = await this.getAll();
|
|
const filteredUsers = users.filter(user => user.id !== id);
|
|
if (users.length === filteredUsers.length) return false;
|
|
|
|
await fs.writeFile(USER_FILE, JSON.stringify(filteredUsers, null, 2));
|
|
return true;
|
|
}
|
|
}
|