Initial commit
This commit is contained in:
39
src/users/users.service.ts
Normal file
39
src/users/users.service.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user