Updated: 2026-03-24
{
"scripts": {
"build": "nest build",
"format": "prettier --write\\"src/**/*.ts\\"\\"test/**/*.ts\\"",
"fix": "npx eslint\\"{src,apps,libs}/**/*.ts\\" --fix ",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch"
}
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
@Module({
imports: [UserModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Welcome to NestJS!';
}
}
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';
@Module({
imports: [],
controllers: [UserController],
providers: [UserService],
})
export class UserModule {}
export interface IUser {
id: string;
firstName: string;
lastName: string;
email: string;
username: string;
}
import { IsEmail, IsNotEmpty } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsNotEmpty()
firstName: string;
@IsNotEmpty()
lastName: string;
@IsNotEmpty()
username: string;
}
import { Injectable, NotFoundException } from '@nestjs/common';
import { IUser } from './user.interface';
import { readFileSync, writeFileSync } from 'fs';
import { CreateUserDto } from './dto/create-user.dto';
@Injectable()
export class UserService {
test(): [] {
return [];
}
findAll(): IUser[] {
return JSON.parse(readFileSync('./data/users.json', 'utf-8')) as IUser[];
}
findOne(id: string, fields?: string[]): IUser | Record<string, unknown> {
const users = this.findAll();
const user = users.find((U: IUser) => U.id == id);
if (!user) {
throw new NotFoundException('User not found');
}
if (fields) {
const filteredUser: Record<string, unknown> = {};
fields.forEach((field) => {
if (Object.prototype.hasOwnProperty.call(user, field)) {
filteredUser[field] = user[field];
}
});
return filteredUser;
}
return user;
}
create(dto: CreateUserDto): IUser {
const users = this.findAll();
const newId = (
users.reduce((maxId, user) => Math.max(maxId, Number(user.id)), 0) + 1
).toString();
const newUser: IUser = {
id: newId,
firstName: dto.firstName,
lastName: dto.lastName,
username: dto.username,
email: dto.email,
};
users.push(newUser);
writeFileSync('./data/users.json', JSON.stringify(users, null, 2), 'utf-8');
return newUser;
}
}