first commit, participant fully working correctly

This commit is contained in:
OkaykOrhmn 2025-07-13 15:34:38 +03:30
commit 9a20d97745
24 changed files with 13397 additions and 0 deletions

56
.gitignore vendored Normal file
View File

@ -0,0 +1,56 @@
# compiled output
/dist
/node_modules
/build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"tabWidth": 2
}

98
README.md Normal file
View File

@ -0,0 +1,98 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Project setup
```bash
$ npm install
```
## Compile and run the project
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Run tests
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
```bash
$ npm install -g @nestjs/mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).

41
eslint.config.mjs Normal file
View File

@ -0,0 +1,41 @@
// @ts-check
import eslint from '@eslint/js';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: ['eslint.config.mjs'],
},
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginPrettierRecommended,
{
languageOptions: {
globals: {
...globals.node,
...globals.jest,
},
sourceType: 'commonjs',
parserOptions: {
project: './tsconfig.json',
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
},
},
{
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking'
]
}
);

8
nest-cli.json Normal file
View File

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

12676
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

84
package.json Normal file
View File

@ -0,0 +1,84 @@
{
"name": "proj",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^11.1.3",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.1.3",
"@nestjs/mapped-types": "^2.1.0",
"@nestjs/mongoose": "^11.0.3",
"@nestjs/platform-express": "^11.1.3",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.2",
"libphonenumber-js": "^1.12.9",
"mongodb": "^6.17.0",
"mongoose": "^8.16.3",
"mongoose-paginate-v2": "^1.9.1",
"nestjs-paginate": "^12.5.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2",
"uuid": "^11.1.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.3.1",
"@eslint/js": "^9.31.0",
"@nestjs/cli": "^11.0.7",
"@nestjs/schematics": "^11.0.5",
"@nestjs/testing": "^11.1.3",
"@swc/cli": "^0.7.8",
"@swc/core": "^1.12.11",
"@types/express": "^5.0.3",
"@types/jest": "^30.0.0",
"@types/node": "^24.0.13",
"@types/supertest": "^6.0.3",
"eslint": "^9.31.0",
"eslint-config-prettier": "^10.1.5",
"eslint-plugin-prettier": "^5.5.1",
"globals": "^16.3.0",
"jest": "^30.0.4",
"prettier": "^3.6.2",
"source-map-support": "^0.5.21",
"supertest": "^7.1.3",
"ts-jest": "^29.4.0",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.8.3",
"typescript-eslint": "^8.36.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

47
src/_core/_base.entity.ts Normal file
View File

@ -0,0 +1,47 @@
import { Prop, Schema } from '@nestjs/mongoose';
import { v4 as uuidv4 } from 'uuid';
import { Metadata, MetadataSchema } from './_metadata.entity';
@Schema({ _id: false, id: false }) // Disable _id and virtual id
export abstract class BaseEntity {
@Prop({
type: String,
default: () => uuidv4(),
required: true,
unique: true,
immutable: true,
})
id: string;
@Prop({
type: Date,
default: () => new Date(),
required: true,
immutable: true,
})
createdAt: Date;
@Prop({
type: Date,
default: () => new Date(),
required: true,
})
updatedAt: Date;
@Prop({
type: MetadataSchema,
default: () => ({ entries: [] }),
required: true,
})
metadata: Metadata;
@Prop({
type: String,
enum: ['active', 'inactive'],
default: 'active',
required: true,
})
status: 'active' | 'inactive';
}
export type BaseEntityDocument = BaseEntity & Document;

View File

@ -0,0 +1,28 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { v4 as uuidv4 } from 'uuid';
@Schema({ _id: false }) // Embedded document
export class Metadata {
@Prop({
type: String,
default: () => uuidv4(),
required: true,
immutable: true,
})
id: string;
@Prop({
type: [
{
key: { type: String, required: true },
value: { type: String, required: true },
},
],
default: [],
})
entries: { key: string; value: string }[];
}
export type MetadataDocument = Metadata & Document;
export const MetadataSchema = SchemaFactory.createForClass(Metadata);

View File

@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

12
src/app.controller.ts Normal file
View File

@ -0,0 +1,12 @@
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();
}
}

20
src/app.module.ts Normal file
View File

@ -0,0 +1,20 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ParticipantModule } from './participant/participant.module';
// import { TestModule } from './test/test.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true, // Makes ConfigModule available globally
}),
MongooseModule.forRoot(process.env.MONGODB_URI || 'mongodb://localhost:27017/db'),
ParticipantModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

8
src/app.service.ts Normal file
View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'This is the main app!';
}
}

8
src/main.ts Normal file
View File

@ -0,0 +1,8 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

View File

@ -0,0 +1,37 @@
import { IsString, IsEnum, IsOptional, IsUUID, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
class MetadataEntryDto {
@IsString()
key: string;
@IsString()
value: string;
}
class MetadataDto {
@ValidateNested({ each: true })
@Type(() => MetadataEntryDto)
entries: MetadataEntryDto[];
}
export class CreateParticipantDto {
@IsUUID()
@IsOptional() // id is optional since BaseEntity generates it
id?: string;
@IsUUID()
userId: string; // Required, provided by client
@IsString()
displayName: string; // Required, provided by client
@IsEnum(['moderator', 'tester', 'admin', 'user'])
@IsOptional()
role?: 'moderator' | 'tester' | 'admin' | 'user'; // Optional, defaults to 'user'
@ValidateNested()
@Type(() => MetadataDto)
@IsOptional()
metadata?: MetadataDto; // Optional, defaults to { entries: [] }
}

View File

@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateParticipantDto } from './create-participant.dto';
export class UpdateParticipantDto extends PartialType(CreateParticipantDto) {}

View File

@ -0,0 +1,40 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { v4 as uuidv4 } from 'uuid';
import { BaseEntity } from 'src/_core/_base.entity';
import * as mongoosePaginate from 'mongoose-paginate-v2';
import { Document } from 'mongoose';
@Schema({ _id: false, id: false }) // Disable _id and virtual id
export class Participant extends BaseEntity {
@Prop({
type: String,
default: () => uuidv4(),
required: true,
immutable: true,
})
userId: string;
@Prop({
type: String,
enum: ['moderator', 'tester', 'admin', 'user'],
default: 'user',
required: true,
})
role: 'moderator' | 'tester' | 'admin' | 'user';
@Prop({
type: String,
required: true,
})
displayName: string;
}
export type ParticipantDocument = Participant & Document;
export const ParticipantSchema = SchemaFactory.createForClass(Participant);
ParticipantSchema.plugin(mongoosePaginate);
ParticipantSchema.set('toJSON', {
transform: (doc: ParticipantDocument, ret: Participant & { _id?: any }) => {
delete ret._id;
return ret;
},
});

View File

@ -0,0 +1,53 @@
import { Controller, Get, Post, Patch, Delete, Param, Body, UsePipes, ValidationPipe, Query, ParseUUIDPipe } from '@nestjs/common';
import { ParticipantService } from './participant.service';
import { CreateParticipantDto } from './dto/create-participant.dto';
import { UpdateParticipantDto } from './dto/update-participant.dto';
import { Participant } from './entity/participant.entity';
@Controller('participants')
export class ParticipantController {
constructor(private readonly participantService: ParticipantService) {}
@Post()
@UsePipes(new ValidationPipe({ transform: true }))
async create(@Body() body: CreateParticipantDto): Promise<Participant> {
return this.participantService.create(body);
}
@Get('findAll') // returns non uuid id !!!
async findAll(
@Query('page') page: string = '1',
@Query('limit') limit: string = '10',
): Promise<{
docs: Participant[];
totalDocs: number;
limit: number;
page: number;
totalPages: number;
hasNextPage: boolean;
hasPrevPage: boolean;
nextPage: number | null;
prevPage: number | null;
}> {
return this.participantService.findAll(parseInt(page), parseInt(limit));
}
@Get(':id')
async findOne(@Param('id', new ParseUUIDPipe()) id: string): Promise<Participant | null> {
return this.participantService.findById(id);
}
@Patch(':id')
@UsePipes(new ValidationPipe({ transform: true }))
async update(
@Param('id', new ParseUUIDPipe()) id: string,
@Body() body: UpdateParticipantDto,
): Promise<Participant | null> {
return this.participantService.update(id, body);
}
@Delete(':id')
async remove(@Param('id', new ParseUUIDPipe()) id: string): Promise<void> {
return this.participantService.remove(id);
}
}

View File

@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ParticipantService } from './participant.service';
import { ParticipantController } from './participant.controller';
import { Participant, ParticipantSchema } from './entity/participant.entity';
@Module({
imports: [
MongooseModule.forFeature([{ name: Participant.name, schema: ParticipantSchema }]),
],
controllers: [ParticipantController],
providers: [ParticipantService],
})
export class ParticipantModule {}

View File

@ -0,0 +1,78 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CreateParticipantDto } from './dto/create-participant.dto';
import { Participant, ParticipantDocument } from './entity/participant.entity';
import { UpdateParticipantDto } from './dto/update-participant.dto';
import { v4 as uuidv4 } from 'uuid';
interface PaginateModel<T> extends Model<T> {
paginate: (
query?: any,
options?: { page: number; limit: number; lean?: boolean; select?: string },
) => Promise<{
docs: T[];
totalDocs: number;
limit: number;
page: number;
totalPages: number;
hasNextPage: boolean;
hasPrevPage: boolean;
nextPage: number | null;
prevPage: number | null;
}>;
}
@Injectable()
export class ParticipantService {
constructor(
@InjectModel(Participant.name)
private readonly participantModel: PaginateModel<ParticipantDocument>,
) {}
async create(data: CreateParticipantDto): Promise<Participant> {
const participant = new this.participantModel({
...data,
id: data.id || undefined, // Let BaseEntity generate UUID
metadata: data.metadata || { entries: [] },
});
return participant.save();
}
async findAll(page = 1, limit = 10): Promise<{ // returns non uuid id !!!
docs: Participant[];
totalDocs: number;
limit: number;
page: number;
totalPages: number;
hasNextPage: boolean;
hasPrevPage: boolean;
nextPage: number | null;
prevPage: number | null;
}> {
return this.participantModel.paginate(
{},
{ page, limit, lean: true, select: 'id metadata status userId role displayName createdAt updatedAt' },
);
}
async findById(id: string): Promise<Participant | null> {
return this.participantModel.findOne({ id }).select('id metadata status userId role displayName createdAt updatedAt').lean().exec();
}
async update(id: string, data: UpdateParticipantDto): Promise<Participant | null> {
return this.participantModel
.findOneAndUpdate(
{ id },
{ $set: { ...data, updatedAt: new Date() } },
{ new: true },
)
.select('id metadata status userId role displayName createdAt updatedAt')
.lean()
.exec();
}
async remove(id: string): Promise<void> {
await this.participantModel.deleteOne({ id }).exec();
}
}

25
test/app.e2e-spec.ts Normal file
View File

@ -0,0 +1,25 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication<App>;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

9
test/jest-e2e.json Normal file
View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

4
tsconfig.build.json Normal file
View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

21
tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
}
}