40 lines
897 B
TypeScript
40 lines
897 B
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import * as fs from 'fs';
|
|
import * as path from 'path';
|
|
|
|
export interface User {
|
|
id: number;
|
|
fullName: string;
|
|
createdAt: string;
|
|
}
|
|
|
|
@Injectable()
|
|
export class UsersService {
|
|
private readonly filePath = path.resolve(__dirname, '..', 'data', 'users.json');
|
|
|
|
private readUsers(): User[] {
|
|
if (!fs.existsSync(this.filePath)) {
|
|
return [];
|
|
}
|
|
const data = fs.readFileSync(this.filePath, 'utf8');
|
|
return JSON.parse(data);
|
|
}
|
|
|
|
private writeUsers(users: User[]): void {
|
|
fs.writeFileSync(this.filePath, JSON.stringify(users, null, 2), 'utf8');
|
|
}
|
|
|
|
findAll(): User[] {
|
|
return this.readUsers();
|
|
}
|
|
|
|
create(user: User): void {
|
|
const users = this.readUsers();
|
|
const existingUser = users.find((u) => u.id === user.id);
|
|
if (!existingUser) {
|
|
users.push(user);
|
|
this.writeUsers(users);
|
|
}
|
|
}
|
|
}
|