Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelfgx committed Nov 30, 2024
0 parents commit ecf78b1
Show file tree
Hide file tree
Showing 37 changed files with 606 additions and 0 deletions.
16 changes: 16 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
**/*.bat
**/*.md
**/*.yml
**/.dockerignore
**/.editorconfig
**/.git
**/.gitattributes
**/.github
**/.gitignore
**/.vs
**/.vscode
**/coverage
**/dist
**/dockerfile
**/node_modules
**/package-lock.json
8 changes: 8 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
root = true

[*]
charset = utf-8
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
JWT_KEY=D6DAE157BC16417DB79339E6FA439D10
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* text=auto
*.js diff=js
*.ts diff=ts
27 changes: 27 additions & 0 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: build
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Node Setup
uses: actions/setup-node@v4
with:
node-version: latest
check-latest: true

- name: Node Build
run: |
npm run restore
npm run build
- name: Artifact Upload
uses: actions/upload-artifact@v4
with:
name: app
path: dist
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
*.bat
.vscode
dist
node_modules
package-lock.json
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
9 changes: 9 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"bracketSpacing": true,
"endOfLine": "lf",
"printWidth": 125,
"semi": true,
"singleQuote": false,
"tabWidth": 4,
"trailingComma": "none"
}
12 changes: 12 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# docker compose up --detach --build --force-recreate --remove-orphans

name: nest
services:
app:
image: app
container_name: app
build:
context: .
dockerfile: dockerfile
ports:
- "4000:3000"
10 changes: 10 additions & 0 deletions dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM node:alpine
RUN npm install -g pnpm
WORKDIR /app
COPY package.json tsconfig.json ./
RUN pnpm install
COPY ./src ./src
RUN npm run build
EXPOSE 3000
ENV NODE_ENV production
CMD ["node", "dist/main.js"]
19 changes: 19 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
import eslintConfigPrettier from "eslint-config-prettier";

export default tseslint.config(
{
ignores: ["**/*.mjs", "node_modules", "dist"],
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname
}
}
},
eslint.configs.recommended,
...tseslint.configs.strict,
...tseslint.configs.stylistic,
eslintConfigPrettier
);
5 changes: 5 additions & 0 deletions license.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
16 changes: 16 additions & 0 deletions nest-cli.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true,
"plugins": [
{
"name": "@nestjs/swagger",
"options": {
"dtoFileNameSuffix": [".dto.ts"]
}
}
]
}
}
54 changes: 54 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "nest",
"version": "1.0.0",
"scripts": {
"restore": "npm install",
"check": "prettier src --config .prettierrc --check && eslint",
"fix": "prettier src --config .prettierrc --write && eslint --fix",
"start": "nest start --watch --debug",
"test": "jest --no-cache",
"build": "nest build"
},
"jest": {
"testRegex": ".spec.ts",
"transform": {
".ts": "ts-jest"
}
},
"dependencies": {
"@nestjs/cache-manager": "2.3.0",
"@nestjs/common": "10.4.12",
"@nestjs/config": "3.3.0",
"@nestjs/core": "10.4.12",
"@nestjs/jwt": "10.2.0",
"@nestjs/platform-express": "10.4.12",
"@nestjs/swagger": "8.0.7",
"class-validator": "0.14.1",
"helmet": "8.0.0",
"reflect-metadata": "0.2.2",
"rxjs": "7.8.1",
"swagger-ui-express": "5.0.1"
},
"devDependencies": {
"@eslint/js": "9.16.0",
"@nestjs/cli": "10.4.8",
"@nestjs/schematics": "10.2.3",
"@nestjs/testing": "10.4.12",
"@types/express": "5.0.0",
"@types/jest": "29.5.14",
"@types/node": "22.10.1",
"@types/supertest": "6.0.2",
"eslint": "9.16.0",
"eslint-config-prettier": "9.1.0",
"jest": "29.7.0",
"prettier": "3.4.1",
"source-map-support": "0.5.21",
"supertest": "7.0.0",
"ts-jest": "29.2.5",
"ts-loader": "9.5.1",
"ts-node": "10.9.2",
"tsconfig-paths": "4.2.0",
"typescript": "5.7.2",
"typescript-eslint": "8.16.0"
}
}
43 changes: 43 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# NEST

API using Nest, JWT Authentication and Authorization, Swagger, Folder-by-Feature Structure.

## TECHNOLOGIES

* [Node](https://nodejs.org)
* [Nest](https://nestjs.com)
* [ESLint](https://eslint.org)
* [Prettier](https://prettier.io)

## RUN

<details>
<summary>Visual Studio Code</summary>

#### Prerequisites

* [Node](https://nodejs.org)
* [Visual Studio Code](https://code.visualstudio.com)
* [Visual Studio Code Node Debug](https://code.visualstudio.com/docs/nodejs/nodejs-debugging)

#### Steps

1. Run the command **npm run restore** in the **Terminal**.
2. Run the command **npm run start** in the **Terminal**.
3. Open **<http://localhost:3000>** in the **Web Browser**.

</details>

<details>
<summary>Docker</summary>

#### Prerequisites

* [Docker](https://www.docker.com/get-started)

#### Steps

1. Run the command **docker compose up --detach --build --force-recreate --remove-orphans** in the **Terminal**.
2. Open **<http://localhost:4000>** in the **Web Browser**.

</details>
17 changes: 17 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { CacheModule } from "@nestjs/cache-manager";
import { AuthModule } from "./auth/auth.module";
import { UserModule } from "./user/user.module";
import { ProductModule } from "./product/product.module";

@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, cache: true }),
CacheModule.register(),
AuthModule,
UserModule,
ProductModule
]
})
export class AppModule {}
3 changes: 3 additions & 0 deletions src/auth/anonymous.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { SetMetadata } from "@nestjs/common";
export const ANONYMOUS = "ANONYMOUS";
export const Anonymous = () => SetMetadata(ANONYMOUS, true);
18 changes: 18 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Controller, Body, Post, HttpCode, HttpStatus } from "@nestjs/common";
import { ApiTags } from "@nestjs/swagger";
import { Anonymous } from "./anonymous.decorator";
import { AuthService } from "./auth.service";
import { AuthDto } from "./auth.dto";

@ApiTags("Auth")
@Controller("auth")
@Anonymous()
export class AuthController {
constructor(private readonly authService: AuthService) {}

@HttpCode(HttpStatus.OK)
@Post()
signIn(@Body() dto: AuthDto) {
return this.authService.signIn(dto);
}
}
9 changes: 9 additions & 0 deletions src/auth/auth.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { IsNotEmpty } from "class-validator";

export class AuthDto {
@IsNotEmpty()
username!: string;

@IsNotEmpty()
password!: string;
}
26 changes: 26 additions & 0 deletions src/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Reflector } from "@nestjs/core";
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { ANONYMOUS } from "./anonymous.decorator";

@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly jwtService: JwtService
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
if (this.reflector.getAllAndOverride<boolean>(ANONYMOUS, [context.getHandler(), context.getClass()])) return true;
const request = context.switchToHttp().getRequest();
const token = request.headers.authorization?.replace("Bearer", "").trim();

try {
await this.jwtService.verifyAsync(token);
} catch {
throw new UnauthorizedException();
}

return true;
}
}
29 changes: 29 additions & 0 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Module } from "@nestjs/common";
import { AuthService } from "./auth.service";
import { AuthController } from "./auth.controller";
import { UserModule } from "src/user/user.module";
import { JwtModule, JwtModuleOptions } from "@nestjs/jwt";
import { ConfigService } from "@nestjs/config";
import { APP_GUARD } from "@nestjs/core";
import { AuthGuard } from "./auth.guard";

@Module({
imports: [
JwtModule.registerAsync({
inject: [ConfigService],
useFactory: async (configService: ConfigService): Promise<JwtModuleOptions> => ({
secret: configService.get<string>("JWT_KEY")!
})
}),
UserModule
],
providers: [
{
provide: APP_GUARD,
useClass: AuthGuard
},
AuthService
],
controllers: [AuthController]
})
export class AuthModule {}
18 changes: 18 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { AuthDto } from "./auth.dto";
import { UserService } from "src/user/user.service";

@Injectable()
export class AuthService {
constructor(
private readonly jwtService: JwtService,
private readonly userService: UserService
) {}

async signIn(dto: AuthDto): Promise<string> {
const user = await this.userService.getByUsername(dto.username);
if (user?.password !== dto.password) throw new UnauthorizedException();
return await this.jwtService.signAsync({ sub: user.id });
}
}
20 changes: 20 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { NestFactory } from "@nestjs/core";
import { VersioningType, ValidationPipe } from "@nestjs/common";
import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger";
import helmet from "helmet";
import { AppModule } from "./app.module";

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableVersioning({ type: VersioningType.URI, defaultVersion: "1" });
app.useGlobalPipes(new ValidationPipe({ transform: true }));
app.use(helmet());
SwaggerModule.setup(
"",
app,
SwaggerModule.createDocument(app, new DocumentBuilder().setTitle("API").addBearerAuth().build())
);
await app.listen(3000);
}

bootstrap();
6 changes: 6 additions & 0 deletions src/product/dtos/add.product.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { IsNotEmpty } from "class-validator";

export class AddProductDto {
@IsNotEmpty()
description!: string;
}
Loading

0 comments on commit ecf78b1

Please sign in to comment.