├── .env
├── .eslintrc.js
├── .gitignore
├── .prettierrc
├── .vscode
└── settings.json
├── README.md
├── docker-compose.yml
├── nest-cli.json
├── package-lock.json
├── package.json
├── prisma
├── migrations
│ ├── 20240408033338_init
│ │ └── migration.sql
│ └── migration_lock.toml
└── schema.prisma
├── src
├── app.module.ts
├── auth
│ ├── auth.controller.ts
│ ├── auth.module.ts
│ └── auth.service.ts
├── hello
│ ├── guards
│ │ └── auth
│ │ │ ├── auth.guard.spec.ts
│ │ │ └── auth.guard.ts
│ ├── hello.controller.spec.ts
│ ├── hello.controller.ts
│ └── pipes
│ │ └── validateuser
│ │ ├── validateuser.pipe.spec.ts
│ │ └── validateuser.pipe.ts
├── main.ts
├── payments
│ ├── dto
│ │ ├── create-payment.dto.ts
│ │ └── update-payment.dto.ts
│ ├── entities
│ │ └── payment.entity.ts
│ ├── payments.controller.spec.ts
│ ├── payments.controller.ts
│ ├── payments.module.ts
│ ├── payments.service.spec.ts
│ └── payments.service.ts
├── prisma.service.ts
├── projects
│ ├── projects.controller.spec.ts
│ ├── projects.controller.ts
│ ├── projects.module.ts
│ ├── projects.service.spec.ts
│ └── projects.service.ts
├── tasks
│ ├── dto
│ │ ├── create-task.dto.ts
│ │ └── update-task.dto.ts
│ ├── tasks.controller.ts
│ ├── tasks.module.ts
│ └── tasks.service.ts
└── users
│ ├── auth
│ ├── auth.middleware.spec.ts
│ └── auth.middleware.ts
│ ├── dto
│ └── create-user.dto.ts
│ ├── logger
│ ├── logger.middleware.spec.ts
│ └── logger.middleware.ts
│ ├── users.controller.spec.ts
│ ├── users.controller.ts
│ ├── users.module.ts
│ ├── users.service.spec.ts
│ └── users.service.ts
├── test
├── app.e2e-spec.ts
└── jest-e2e.json
├── tsconfig.build.json
└── tsconfig.json
/.env:
--------------------------------------------------------------------------------
1 | # Environment variables declared in this file are automatically made available to Prisma.
2 | # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
3 |
4 | # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
5 | # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
6 |
7 | DATABASE_URL="postgresql://fazt:faztpassword@localhost:5499/nestdb?schema=public"
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | parser: '@typescript-eslint/parser',
3 | parserOptions: {
4 | project: 'tsconfig.json',
5 | tsconfigRootDir: __dirname,
6 | sourceType: 'module',
7 | },
8 | plugins: ['@typescript-eslint/eslint-plugin'],
9 | extends: [
10 | 'plugin:@typescript-eslint/recommended',
11 | 'plugin:prettier/recommended',
12 | ],
13 | root: true,
14 | env: {
15 | node: true,
16 | jest: true,
17 | },
18 | ignorePatterns: ['.eslintrc.js'],
19 | rules: {
20 | '@typescript-eslint/interface-name-prefix': 'off',
21 | '@typescript-eslint/explicit-function-return-type': 'off',
22 | '@typescript-eslint/explicit-module-boundary-types': 'off',
23 | '@typescript-eslint/no-explicit-any': 'off',
24 | },
25 | "prettier/prettier": [
26 | "error",
27 | {
28 | "endOfLine": "auto"
29 | }
30 | ]
31 | };
32 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # compiled output
2 | /dist
3 | /node_modules
4 |
5 | # Logs
6 | logs
7 | *.log
8 | npm-debug.log*
9 | pnpm-debug.log*
10 | yarn-debug.log*
11 | yarn-error.log*
12 | lerna-debug.log*
13 |
14 | # OS
15 | .DS_Store
16 |
17 | # Tests
18 | /coverage
19 | /.nyc_output
20 |
21 | # IDEs and editors
22 | /.idea
23 | .project
24 | .classpath
25 | .c9/
26 | *.launch
27 | .settings/
28 | *.sublime-workspace
29 |
30 | # IDE - VSCode
31 | .vscode/*
32 | !.vscode/settings.json
33 | !.vscode/tasks.json
34 | !.vscode/launch.json
35 | !.vscode/extensions.json
36 |
37 | .env
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "trailingComma": "all"
4 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "material-icon-theme.activeIconPack": "nest"
3 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
6 | [circleci-url]: https://circleci.com/gh/nestjs/nest
7 |
8 | A progressive Node.js framework for building efficient and scalable server-side applications.
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
24 |
25 | ## Description
26 |
27 | [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
28 |
29 | ## Installation
30 |
31 | ```bash
32 | $ npm install
33 | ```
34 |
35 | ## Running the app
36 |
37 | ```bash
38 | # development
39 | $ npm run start
40 |
41 | # watch mode
42 | $ npm run start:dev
43 |
44 | # production mode
45 | $ npm run start:prod
46 | ```
47 |
48 | ## Test
49 |
50 | ```bash
51 | # unit tests
52 | $ npm run test
53 |
54 | # e2e tests
55 | $ npm run test:e2e
56 |
57 | # test coverage
58 | $ npm run test:cov
59 | ```
60 |
61 | ## Support
62 |
63 | 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).
64 |
65 | ## Stay in touch
66 |
67 | - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
68 | - Website - [https://nestjs.com](https://nestjs.com/)
69 | - Twitter - [@nestframework](https://twitter.com/nestframework)
70 |
71 | ## License
72 |
73 | Nest is [MIT licensed](LICENSE).
74 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3.8'
2 | services:
3 | db:
4 | image: postgres
5 | restart: always
6 | environment:
7 | POSTGRES_USER: fazt
8 | POSTGRES_PASSWORD: faztpassword
9 | POSTGRES_DB: nestdb
10 | ports:
11 | - 5499:5432
--------------------------------------------------------------------------------
/nest-cli.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://json.schemastore.org/nest-cli",
3 | "collection": "@nestjs/schematics",
4 | "sourceRoot": "src",
5 | "compilerOptions": {
6 | "deleteOutDir": true
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "myfirstapp",
3 | "version": "0.0.1",
4 | "description": "",
5 | "author": "",
6 | "private": true,
7 | "license": "UNLICENSED",
8 | "scripts": {
9 | "build": "nest build",
10 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
11 | "start": "nest start",
12 | "start:dev": "nest start --watch",
13 | "start:debug": "nest start --debug --watch",
14 | "start:prod": "node dist/main",
15 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
16 | "test": "jest",
17 | "test:watch": "jest --watch",
18 | "test:cov": "jest --coverage",
19 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
20 | "test:e2e": "jest --config ./test/jest-e2e.json"
21 | },
22 | "dependencies": {
23 | "@nestjs/common": "^9.0.0",
24 | "@nestjs/core": "^9.0.0",
25 | "@nestjs/mapped-types": "*",
26 | "@nestjs/platform-express": "^9.0.0",
27 | "@nestjs/swagger": "^7.3.1",
28 | "@prisma/client": "^5.12.1",
29 | "class-transformer": "^0.5.1",
30 | "class-validator": "^0.14.1",
31 | "reflect-metadata": "^0.1.13",
32 | "rxjs": "^7.2.0"
33 | },
34 | "devDependencies": {
35 | "@nestjs/cli": "^9.0.0",
36 | "@nestjs/schematics": "^9.0.0",
37 | "@nestjs/testing": "^9.0.0",
38 | "@types/express": "^4.17.13",
39 | "@types/jest": "29.5.1",
40 | "@types/node": "18.16.12",
41 | "@types/supertest": "^2.0.11",
42 | "@typescript-eslint/eslint-plugin": "^5.0.0",
43 | "@typescript-eslint/parser": "^5.0.0",
44 | "eslint": "^8.0.1",
45 | "eslint-config-prettier": "^8.3.0",
46 | "eslint-plugin-prettier": "^4.0.0",
47 | "jest": "29.5.0",
48 | "prettier": "^2.3.2",
49 | "prisma": "^5.12.1",
50 | "source-map-support": "^0.5.20",
51 | "supertest": "^6.1.3",
52 | "ts-jest": "29.1.0",
53 | "ts-loader": "^9.2.3",
54 | "ts-node": "^10.0.0",
55 | "tsconfig-paths": "4.2.0",
56 | "typescript": "^5.0.0"
57 | },
58 | "jest": {
59 | "moduleFileExtensions": [
60 | "js",
61 | "json",
62 | "ts"
63 | ],
64 | "rootDir": "src",
65 | "testRegex": ".*\\.spec\\.ts$",
66 | "transform": {
67 | "^.+\\.(t|j)s$": "ts-jest"
68 | },
69 | "collectCoverageFrom": [
70 | "**/*.(t|j)s"
71 | ],
72 | "coverageDirectory": "../coverage",
73 | "testEnvironment": "node"
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/prisma/migrations/20240408033338_init/migration.sql:
--------------------------------------------------------------------------------
1 | -- CreateTable
2 | CREATE TABLE "User" (
3 | "id" TEXT NOT NULL,
4 | "email" TEXT NOT NULL,
5 | "name" TEXT,
6 | "password" TEXT NOT NULL,
7 | "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
8 | "updatedAt" TIMESTAMP(3) NOT NULL,
9 |
10 | CONSTRAINT "User_pkey" PRIMARY KEY ("id")
11 | );
12 |
13 | -- CreateIndex
14 | CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
15 |
--------------------------------------------------------------------------------
/prisma/migrations/migration_lock.toml:
--------------------------------------------------------------------------------
1 | # Please do not edit this file manually
2 | # It should be added in your version-control system (i.e. Git)
3 | provider = "postgresql"
--------------------------------------------------------------------------------
/prisma/schema.prisma:
--------------------------------------------------------------------------------
1 | // This is your Prisma schema file,
2 | // learn more about it in the docs: https://pris.ly/d/prisma-schema
3 |
4 | // Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
5 | // Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
6 |
7 | generator client {
8 | provider = "prisma-client-js"
9 | }
10 |
11 | datasource db {
12 | provider = "postgresql"
13 | url = env("DATABASE_URL")
14 | }
15 |
16 | model User {
17 | id String @id @default(cuid())
18 | email String @unique
19 | name String?
20 | password String
21 |
22 | createdAt DateTime @default(now())
23 | updatedAt DateTime @updatedAt
24 | }
--------------------------------------------------------------------------------
/src/app.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { TasksModule } from './tasks/tasks.module';
3 | import { ProjectsModule } from './projects/projects.module';
4 | import { AuthModule } from './auth/auth.module';
5 | import { UsersModule } from './users/users.module';
6 | import { HelloController } from './hello/hello.controller';
7 | import { PaymentsModule } from './payments/payments.module';
8 |
9 | @Module({
10 | imports: [TasksModule, ProjectsModule, AuthModule, UsersModule, PaymentsModule],
11 | controllers: [HelloController],
12 | })
13 | export class AppModule {}
14 |
--------------------------------------------------------------------------------
/src/auth/auth.controller.ts:
--------------------------------------------------------------------------------
1 | import { Controller } from '@nestjs/common';
2 |
3 | @Controller('auth')
4 | export class AuthController {}
5 |
--------------------------------------------------------------------------------
/src/auth/auth.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { AuthController } from './auth.controller';
3 | import { AuthService } from './auth.service';
4 |
5 | @Module({
6 | controllers: [AuthController],
7 | providers: [AuthService]
8 | })
9 | export class AuthModule {}
10 |
--------------------------------------------------------------------------------
/src/auth/auth.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 |
3 | @Injectable()
4 | export class AuthService {}
5 |
--------------------------------------------------------------------------------
/src/hello/guards/auth/auth.guard.spec.ts:
--------------------------------------------------------------------------------
1 | import { AuthGuard } from './auth.guard';
2 |
3 | describe('AuthGuard', () => {
4 | it('should be defined', () => {
5 | expect(new AuthGuard()).toBeDefined();
6 | });
7 | });
8 |
--------------------------------------------------------------------------------
/src/hello/guards/auth/auth.guard.ts:
--------------------------------------------------------------------------------
1 | import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
2 | import { Observable } from 'rxjs';
3 |
4 | @Injectable()
5 | export class AuthGuard implements CanActivate {
6 | canActivate(
7 | context: ExecutionContext,
8 | ): boolean | Promise | Observable {
9 | const request = context.switchToHttp().getRequest() as Request;
10 | console.log(request.url);
11 |
12 | if (!request.headers['authorization']) return false;
13 |
14 | return true;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/hello/hello.controller.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { HelloController } from './hello.controller';
3 |
4 | describe('HelloController', () => {
5 | let controller: HelloController;
6 |
7 | beforeEach(async () => {
8 | const module: TestingModule = await Test.createTestingModule({
9 | controllers: [HelloController],
10 | }).compile();
11 |
12 | controller = module.get(HelloController);
13 | });
14 |
15 | it('should be defined', () => {
16 | expect(controller).toBeDefined();
17 | });
18 | });
19 |
--------------------------------------------------------------------------------
/src/hello/hello.controller.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Controller,
3 | Get,
4 | HttpCode,
5 | Param,
6 | ParseBoolPipe,
7 | ParseIntPipe,
8 | Query,
9 | Req,
10 | Res,
11 | UseGuards,
12 | } from '@nestjs/common';
13 | import { Request, Response } from 'express';
14 | import { ValidateuserPipe } from './pipes/validateuser/validateuser.pipe';
15 | import { AuthGuard } from './guards/auth/auth.guard';
16 |
17 | @Controller()
18 | export class HelloController {
19 | @Get('/hello')
20 | index(@Req() request: Request, @Res() response: Response) {
21 | console.log(request.url);
22 | response.status(200).json({
23 | message: 'Hello World',
24 | });
25 | }
26 |
27 | @Get('new')
28 | @HttpCode(201)
29 | somethingNew() {
30 | return 'Something new';
31 | }
32 |
33 | @Get('notfound')
34 | @HttpCode(404)
35 | notFoundPage() {
36 | return '404 not found';
37 | }
38 |
39 | @Get('error')
40 | @HttpCode(500)
41 | errorPage() {
42 | return 'Error Route!!';
43 | }
44 |
45 | @Get('ticket/:num')
46 | getNumber(@Param('num', ParseIntPipe) num: number) {
47 | console.log(typeof num);
48 | return num + 14;
49 | }
50 |
51 | @Get('active/:status')
52 | @UseGuards(AuthGuard)
53 | isUserActive(@Param('status', ParseBoolPipe) status: boolean) {
54 | console.log(typeof status);
55 | return status;
56 | }
57 |
58 | @Get('greet')
59 | @UseGuards(AuthGuard)
60 | greet(@Query(ValidateuserPipe) query: { name: string; age: number }) {
61 | console.log(typeof query.age);
62 | console.log(typeof query.name);
63 | return `Hello ${query.name}, you are ${query.age + 30} years old`;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/hello/pipes/validateuser/validateuser.pipe.spec.ts:
--------------------------------------------------------------------------------
1 | import { ValidateuserPipe } from './validateuser.pipe';
2 |
3 | describe('ValidateuserPipe', () => {
4 | it('should be defined', () => {
5 | expect(new ValidateuserPipe()).toBeDefined();
6 | });
7 | });
8 |
--------------------------------------------------------------------------------
/src/hello/pipes/validateuser/validateuser.pipe.ts:
--------------------------------------------------------------------------------
1 | import {
2 | ArgumentMetadata,
3 | HttpException,
4 | HttpStatus,
5 | Injectable,
6 | PipeTransform,
7 | } from '@nestjs/common';
8 |
9 | @Injectable()
10 | export class ValidateuserPipe implements PipeTransform {
11 | transform(value: any, metadata: ArgumentMetadata) {
12 | console.log('value', value);
13 |
14 | const ageNumber = parseInt(value.age.toString(), 10);
15 |
16 | if (isNaN(ageNumber)) {
17 | throw new HttpException('Age must be a number', HttpStatus.BAD_REQUEST);
18 | }
19 |
20 | return { ...value, age: ageNumber };
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import { NestFactory } from '@nestjs/core';
2 | import { AppModule } from './app.module';
3 | import { ValidationPipe } from '@nestjs/common';
4 | import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
5 |
6 | async function bootstrap() {
7 | const app = await NestFactory.create(AppModule);
8 |
9 | app.useGlobalPipes(new ValidationPipe({
10 | whitelist: true,
11 | }));
12 |
13 | const config = new DocumentBuilder()
14 | .setTitle('Cats example')
15 | .setDescription('The cats API description')
16 | .setVersion('1.0')
17 | .addTag('cats')
18 | .build();
19 | const document = SwaggerModule.createDocument(app, config);
20 | SwaggerModule.setup('api', app, document);
21 |
22 | app.enableCors()
23 |
24 | await app.listen(process.env.PORT || 3000);
25 | }
26 | bootstrap();
27 |
--------------------------------------------------------------------------------
/src/payments/dto/create-payment.dto.ts:
--------------------------------------------------------------------------------
1 | export class CreatePaymentDto {}
2 |
--------------------------------------------------------------------------------
/src/payments/dto/update-payment.dto.ts:
--------------------------------------------------------------------------------
1 | import { PartialType } from '@nestjs/mapped-types';
2 | import { CreatePaymentDto } from './create-payment.dto';
3 |
4 | export class UpdatePaymentDto extends PartialType(CreatePaymentDto) {}
5 |
--------------------------------------------------------------------------------
/src/payments/entities/payment.entity.ts:
--------------------------------------------------------------------------------
1 | export class Payment {}
2 |
--------------------------------------------------------------------------------
/src/payments/payments.controller.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { PaymentsController } from './payments.controller';
3 | import { PaymentsService } from './payments.service';
4 |
5 | describe('PaymentsController', () => {
6 | let controller: PaymentsController;
7 |
8 | beforeEach(async () => {
9 | const module: TestingModule = await Test.createTestingModule({
10 | controllers: [PaymentsController],
11 | providers: [PaymentsService],
12 | }).compile();
13 |
14 | controller = module.get(PaymentsController);
15 | });
16 |
17 | it('should be defined', () => {
18 | expect(controller).toBeDefined();
19 | });
20 | });
21 |
--------------------------------------------------------------------------------
/src/payments/payments.controller.ts:
--------------------------------------------------------------------------------
1 | import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
2 | import { PaymentsService } from './payments.service';
3 | import { CreatePaymentDto } from './dto/create-payment.dto';
4 | import { UpdatePaymentDto } from './dto/update-payment.dto';
5 | import { ApiTags } from '@nestjs/swagger';
6 |
7 | @Controller('payments')
8 | @ApiTags('payments')
9 | export class PaymentsController {
10 | constructor(private readonly paymentsService: PaymentsService) {}
11 |
12 | @Post()
13 | create(@Body() createPaymentDto: CreatePaymentDto) {
14 | return this.paymentsService.create(createPaymentDto);
15 | }
16 |
17 | @Get()
18 | findAll() {
19 | return this.paymentsService.findAll();
20 | }
21 |
22 | @Get(':id')
23 | findOne(@Param('id') id: string) {
24 | return this.paymentsService.findOne(+id);
25 | }
26 |
27 | @Patch(':id')
28 | update(@Param('id') id: string, @Body() updatePaymentDto: UpdatePaymentDto) {
29 | return this.paymentsService.update(+id, updatePaymentDto);
30 | }
31 |
32 | @Delete(':id')
33 | remove(@Param('id') id: string) {
34 | return this.paymentsService.remove(+id);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/payments/payments.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { PaymentsService } from './payments.service';
3 | import { PaymentsController } from './payments.controller';
4 |
5 | @Module({
6 | controllers: [PaymentsController],
7 | providers: [PaymentsService]
8 | })
9 | export class PaymentsModule {}
10 |
--------------------------------------------------------------------------------
/src/payments/payments.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { PaymentsService } from './payments.service';
3 |
4 | describe('PaymentsService', () => {
5 | let service: PaymentsService;
6 |
7 | beforeEach(async () => {
8 | const module: TestingModule = await Test.createTestingModule({
9 | providers: [PaymentsService],
10 | }).compile();
11 |
12 | service = module.get(PaymentsService);
13 | });
14 |
15 | it('should be defined', () => {
16 | expect(service).toBeDefined();
17 | });
18 | });
19 |
--------------------------------------------------------------------------------
/src/payments/payments.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 | import { CreatePaymentDto } from './dto/create-payment.dto';
3 | import { UpdatePaymentDto } from './dto/update-payment.dto';
4 |
5 | @Injectable()
6 | export class PaymentsService {
7 | create(createPaymentDto: CreatePaymentDto) {
8 | return 'This action adds a new payment';
9 | }
10 |
11 | findAll() {
12 | return `This action returns all payments`;
13 | }
14 |
15 | findOne(id: number) {
16 | return `This action returns a #${id} payment`;
17 | }
18 |
19 | update(id: number, updatePaymentDto: UpdatePaymentDto) {
20 | return `This action updates a #${id} payment`;
21 | }
22 |
23 | remove(id: number) {
24 | return `This action removes a #${id} payment`;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/prisma.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable, OnModuleInit } from '@nestjs/common';
2 | import { PrismaClient } from '@prisma/client';
3 |
4 | @Injectable()
5 | export class PrismaService extends PrismaClient implements OnModuleInit {
6 | async onModuleInit() {
7 | await this.$connect();
8 | }
9 | }
--------------------------------------------------------------------------------
/src/projects/projects.controller.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { ProjectsController } from './projects.controller';
3 |
4 | describe('ProjectsController', () => {
5 | let controller: ProjectsController;
6 |
7 | beforeEach(async () => {
8 | const module: TestingModule = await Test.createTestingModule({
9 | controllers: [ProjectsController],
10 | }).compile();
11 |
12 | controller = module.get(ProjectsController);
13 | });
14 |
15 | it('should be defined', () => {
16 | expect(controller).toBeDefined();
17 | });
18 | });
19 |
--------------------------------------------------------------------------------
/src/projects/projects.controller.ts:
--------------------------------------------------------------------------------
1 | import { Controller } from '@nestjs/common';
2 |
3 | @Controller('projects')
4 | export class ProjectsController {}
5 |
--------------------------------------------------------------------------------
/src/projects/projects.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { ProjectsController } from './projects.controller';
3 | import { ProjectsService } from './projects.service';
4 |
5 | @Module({
6 | controllers: [ProjectsController],
7 | providers: [ProjectsService]
8 | })
9 | export class ProjectsModule {}
10 |
--------------------------------------------------------------------------------
/src/projects/projects.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { ProjectsService } from './projects.service';
3 |
4 | describe('ProjectsService', () => {
5 | let service: ProjectsService;
6 |
7 | beforeEach(async () => {
8 | const module: TestingModule = await Test.createTestingModule({
9 | providers: [ProjectsService],
10 | }).compile();
11 |
12 | service = module.get(ProjectsService);
13 | });
14 |
15 | it('should be defined', () => {
16 | expect(service).toBeDefined();
17 | });
18 | });
19 |
--------------------------------------------------------------------------------
/src/projects/projects.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 |
3 | @Injectable()
4 | export class ProjectsService {}
5 |
--------------------------------------------------------------------------------
/src/tasks/dto/create-task.dto.ts:
--------------------------------------------------------------------------------
1 | import { IsString, min, MinLength} from 'class-validator';
2 |
3 | export class CreateTaskDto {
4 | @IsString()
5 | @MinLength(1)
6 | title: string;
7 |
8 | @IsString()
9 | @MinLength(1)
10 | description: string;
11 | }
12 |
--------------------------------------------------------------------------------
/src/tasks/dto/update-task.dto.ts:
--------------------------------------------------------------------------------
1 | export interface UpdateTaskDto {
2 | title?: string
3 | description?: string
4 | }
--------------------------------------------------------------------------------
/src/tasks/tasks.controller.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Controller,
3 | Delete,
4 | Patch,
5 | Get,
6 | Post,
7 | Put,
8 | Body,
9 | Query,
10 | Param,
11 | } from '@nestjs/common';
12 | import { TasksService } from './tasks.service';
13 | import { CreateTaskDto } from './dto/create-task.dto';
14 | import { UpdateTaskDto } from './dto/update-task.dto';
15 | import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
16 |
17 | @Controller('/tasks')
18 | @ApiTags('tasks')
19 | export class TaskController {
20 | constructor(private tasksService: TasksService) {}
21 |
22 | @Get()
23 | @ApiOperation({ summary: 'Get all tasks' })
24 | @ApiResponse({ status: 200, description: 'Return all tasks.' })
25 | @ApiResponse({ status: 403, description: 'Forbidden.' })
26 | getAllTasks(@Query() query: any) {
27 | console.log(query);
28 | return this.tasksService.getTasks();
29 | }
30 |
31 | @Get('/:id')
32 | getTask(@Param('id') id: string) {
33 | return this.tasksService.getTask(parseInt(id));
34 | }
35 |
36 | @Post()
37 | @ApiOperation({ summary: 'Create a task' })
38 | createTask(@Body() task: CreateTaskDto) {
39 | return this.tasksService.createTask(task);
40 | }
41 |
42 | @Put()
43 | updateTask(@Body() task: UpdateTaskDto) {
44 | return this.tasksService.updateTask(task);
45 | }
46 |
47 | @Delete()
48 | deleteTask() {
49 | return this.tasksService.deleteTask();
50 | }
51 |
52 | @Patch()
53 | updateTaskStatus() {
54 | return this.tasksService.updateTaskStatus();
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/tasks/tasks.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { TaskController } from './tasks.controller';
3 | import { TasksService } from './tasks.service';
4 |
5 | @Module({
6 | controllers: [TaskController],
7 | providers: [TasksService],
8 | })
9 | export class TasksModule {}
10 |
--------------------------------------------------------------------------------
/src/tasks/tasks.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable, NotFoundException } from '@nestjs/common';
2 | import { CreateTaskDto } from './dto/create-task.dto';
3 | import { UpdateTaskDto } from './dto/update-task.dto';
4 |
5 | export interface User {
6 | name: string;
7 | age: number;
8 | }
9 |
10 | @Injectable()
11 | export class TasksService {
12 | private tasks = [];
13 |
14 | getTasks() {
15 | return this.tasks;
16 | }
17 |
18 | getTask(id: number) {
19 | const taskFound = this.tasks.find((task) => task.id === id);
20 |
21 | if (!taskFound) {
22 | return new NotFoundException(`Task with id ${id} not found`);
23 | }
24 |
25 | return taskFound;
26 | }
27 |
28 | createTask(task: CreateTaskDto) {
29 | this.tasks.push({
30 | ...task,
31 | id: this.tasks.length + 1,
32 | });
33 | return task;
34 | }
35 |
36 | updateTask(task: UpdateTaskDto) {
37 | console.log(task)
38 | return 'actualizando tareas';
39 | }
40 |
41 | deleteTask() {
42 | return 'Eliminando Tarea';
43 | }
44 |
45 | updateTaskStatus() {
46 | return 'actualizando el estado de una tarea';
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/users/auth/auth.middleware.spec.ts:
--------------------------------------------------------------------------------
1 | import { AuthMiddleware } from './auth.middleware';
2 |
3 | describe('AuthMiddleware', () => {
4 | it('should be defined', () => {
5 | expect(new AuthMiddleware()).toBeDefined();
6 | });
7 | });
8 |
--------------------------------------------------------------------------------
/src/users/auth/auth.middleware.ts:
--------------------------------------------------------------------------------
1 | import {
2 | HttpException,
3 | HttpStatus,
4 | Injectable,
5 | NestMiddleware,
6 | } from '@nestjs/common';
7 | import { Request, Response } from 'express';
8 |
9 | @Injectable()
10 | export class AuthMiddleware implements NestMiddleware {
11 | use(req: Request, res: Response, next: () => void) {
12 | const { authorization } = req.headers;
13 |
14 | if (!authorization) {
15 | throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
16 | }
17 |
18 | if (authorization !== 'xyz123') {
19 | throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
20 | }
21 |
22 | next();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/users/dto/create-user.dto.ts:
--------------------------------------------------------------------------------
1 | import { IsEmail, IsNotEmpty, IsNumber, IsString, Max } from 'class-validator';
2 |
3 | export class CreateUserDto {
4 | @IsEmail()
5 | @IsString()
6 | @IsNotEmpty()
7 | email: string;
8 |
9 | @IsString()
10 | @IsNotEmpty()
11 | password: string;
12 |
13 | @IsString()
14 | @IsNotEmpty()
15 | name: string;
16 | }
17 |
--------------------------------------------------------------------------------
/src/users/logger/logger.middleware.spec.ts:
--------------------------------------------------------------------------------
1 | import { LoggerMiddleware } from './logger.middleware';
2 |
3 | describe('LoggerMiddleware', () => {
4 | it('should be defined', () => {
5 | expect(new LoggerMiddleware()).toBeDefined();
6 | });
7 | });
8 |
--------------------------------------------------------------------------------
/src/users/logger/logger.middleware.ts:
--------------------------------------------------------------------------------
1 | import { Injectable, NestMiddleware } from '@nestjs/common';
2 | import { Request, Response } from 'express';
3 |
4 | @Injectable()
5 | export class LoggerMiddleware implements NestMiddleware {
6 | use(req: Request, res: Response, next: () => void) {
7 | console.log('middleware', req.originalUrl);
8 |
9 | next();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/users/users.controller.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { UsersController } from './users.controller';
3 |
4 | describe('UsersController', () => {
5 | let controller: UsersController;
6 |
7 | beforeEach(async () => {
8 | const module: TestingModule = await Test.createTestingModule({
9 | controllers: [UsersController],
10 | }).compile();
11 |
12 | controller = module.get(UsersController);
13 | });
14 |
15 | it('should be defined', () => {
16 | expect(controller).toBeDefined();
17 | });
18 | });
19 |
--------------------------------------------------------------------------------
/src/users/users.controller.ts:
--------------------------------------------------------------------------------
1 | import { Body, Controller, Get, Post } from '@nestjs/common';
2 | import { UsersService } from './users.service';
3 | import { CreateUserDto } from './dto/create-user.dto';
4 | import { ApiTags } from '@nestjs/swagger';
5 |
6 | @Controller()
7 | export class UsersController {
8 | constructor(private usersService: UsersService) {}
9 |
10 | @ApiTags('users')
11 | @Get('/users')
12 | getUsers() {
13 | return this.usersService.getUsers();
14 | }
15 |
16 | @Post('/users')
17 | @ApiTags('users')
18 | createUser(@Body() user: CreateUserDto) {
19 | return this.usersService.createUser(user);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/users/users.module.ts:
--------------------------------------------------------------------------------
1 | import {
2 | MiddlewareConsumer,
3 | Module,
4 | NestMiddleware,
5 | NestModule,
6 | RequestMethod,
7 | } from '@nestjs/common';
8 | import { UsersController } from './users.controller';
9 | import { UsersService } from './users.service';
10 | import { LoggerMiddleware } from './logger/logger.middleware';
11 | import { AuthMiddleware } from './auth/auth.middleware';
12 | import { PrismaService } from 'src/prisma.service';
13 |
14 | @Module({
15 | controllers: [UsersController],
16 | providers: [UsersService, PrismaService],
17 | })
18 | export class UsersModule implements NestModule {
19 | configure(consumer: MiddlewareConsumer) {
20 | // consumer
21 | // .apply(LoggerMiddleware)
22 | // .forRoutes(
23 | // { path: '/users', method: RequestMethod.GET },
24 | // {
25 | // path: '/users',
26 | // method: RequestMethod.POST,
27 | // },
28 | // )
29 | // .apply(AuthMiddleware)
30 | // .forRoutes('users');
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/users/users.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { UsersService } from './users.service';
3 |
4 | describe('UsersService', () => {
5 | let service: UsersService;
6 |
7 | beforeEach(async () => {
8 | const module: TestingModule = await Test.createTestingModule({
9 | providers: [UsersService],
10 | }).compile();
11 |
12 | service = module.get(UsersService);
13 | });
14 |
15 | it('should be defined', () => {
16 | expect(service).toBeDefined();
17 | });
18 | });
19 |
--------------------------------------------------------------------------------
/src/users/users.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 | import { CreateUserDto } from './dto/create-user.dto';
3 | import { PrismaService } from 'src/prisma.service';
4 |
5 | @Injectable()
6 | export class UsersService {
7 | constructor(private prisma: PrismaService) {}
8 |
9 | getUsers() {
10 | return this.prisma.user.findMany();
11 | }
12 |
13 | createUser(user: CreateUserDto) {
14 | return this.prisma.user.create({ data: user });
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/test/app.e2e-spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { INestApplication } from '@nestjs/common';
3 | import * as request from 'supertest';
4 | import { AppModule } from './../src/app.module';
5 |
6 | describe('AppController (e2e)', () => {
7 | let app: INestApplication;
8 |
9 | beforeEach(async () => {
10 | const moduleFixture: TestingModule = await Test.createTestingModule({
11 | imports: [AppModule],
12 | }).compile();
13 |
14 | app = moduleFixture.createNestApplication();
15 | await app.init();
16 | });
17 |
18 | it('/ (GET)', () => {
19 | return request(app.getHttpServer())
20 | .get('/')
21 | .expect(200)
22 | .expect('Hello World!');
23 | });
24 | });
25 |
--------------------------------------------------------------------------------
/test/jest-e2e.json:
--------------------------------------------------------------------------------
1 | {
2 | "moduleFileExtensions": ["js", "json", "ts"],
3 | "rootDir": ".",
4 | "testEnvironment": "node",
5 | "testRegex": ".e2e-spec.ts$",
6 | "transform": {
7 | "^.+\\.(t|j)s$": "ts-jest"
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
4 | }
5 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "commonjs",
4 | "declaration": true,
5 | "removeComments": true,
6 | "emitDecoratorMetadata": true,
7 | "experimentalDecorators": true,
8 | "allowSyntheticDefaultImports": true,
9 | "target": "es2017",
10 | "sourceMap": true,
11 | "outDir": "./dist",
12 | "baseUrl": "./",
13 | "incremental": true,
14 | "skipLibCheck": true,
15 | "strictNullChecks": false,
16 | "noImplicitAny": false,
17 | "strictBindCallApply": false,
18 | "forceConsistentCasingInFileNames": false,
19 | "noFallthroughCasesInSwitch": false
20 | }
21 | }
22 |
--------------------------------------------------------------------------------