├── .env
├── .eslintrc.js
├── .gitignore
├── .prettierrc
├── README.md
├── nest-cli.json
├── package.json
├── pnpm-lock.yaml
├── src
├── app.controller.ts
├── app.module.ts
├── app.service.ts
├── auth
│ ├── auth.controller.ts
│ ├── auth.module.ts
│ ├── auth.service.ts
│ ├── guards
│ │ ├── jwt.guard.ts
│ │ └── local.guard.ts
│ └── strategies
│ │ ├── jwt.strategy.ts
│ │ └── local.strategy.ts
├── decorators
│ └── user-id.decorator.ts
├── files
│ ├── dto
│ │ ├── create-file.dto.ts
│ │ └── update-file.dto.ts
│ ├── entities
│ │ └── file.entity.ts
│ ├── files.controller.ts
│ ├── files.module.ts
│ ├── files.service.ts
│ └── storage.ts
├── main.ts
└── users
│ ├── dto
│ ├── create-user.dto.ts
│ └── update-user.dto.ts
│ ├── entities
│ └── user.entity.ts
│ ├── users.controller.ts
│ ├── users.module.ts
│ └── users.service.ts
├── test
├── app.e2e-spec.ts
└── jest-e2e.json
├── tsconfig.build.json
└── tsconfig.json
/.env:
--------------------------------------------------------------------------------
1 | # JWT
2 | SECRET_KEY=test123
3 | EXPIRES_IN=30d
4 |
5 | # Database
6 | DB_HOST=mel.db.elephantsql.com
7 | DB_PORT=5432
8 | DB_USER=ygsrjzat
9 | DB_PASSWORD=UWroty0nCBanfAnbBXESkiW6hoXqiF_w
10 | DB_NAME=ygsrjzat
--------------------------------------------------------------------------------
/.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 | };
26 |
--------------------------------------------------------------------------------
/.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
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "trailingComma": "all"
4 | }
--------------------------------------------------------------------------------
/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 | $ pnpm install
33 | ```
34 |
35 | ## Running the app
36 |
37 | ```bash
38 | # development
39 | $ pnpm run start
40 |
41 | # watch mode
42 | $ pnpm run start:dev
43 |
44 | # production mode
45 | $ pnpm run start:prod
46 | ```
47 |
48 | ## Test
49 |
50 | ```bash
51 | # unit tests
52 | $ pnpm run test
53 |
54 | # e2e tests
55 | $ pnpm run test:e2e
56 |
57 | # test coverage
58 | $ pnpm 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 |
--------------------------------------------------------------------------------
/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": "cloud-storage",
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/config": "^2.2.0",
25 | "@nestjs/core": "^9.0.0",
26 | "@nestjs/jwt": "^10.0.1",
27 | "@nestjs/mapped-types": "*",
28 | "@nestjs/passport": "^9.0.0",
29 | "@nestjs/platform-express": "^9.0.0",
30 | "@nestjs/swagger": "^6.1.4",
31 | "@nestjs/typeorm": "^9.0.1",
32 | "@types/multer": "^1.4.7",
33 | "@types/passport-jwt": "^3.0.8",
34 | "@types/passport-local": "^1.0.34",
35 | "passport": "^0.6.0",
36 | "passport-jwt": "^4.0.1",
37 | "passport-local": "^1.0.0",
38 | "pg": "^8.8.0",
39 | "reflect-metadata": "^0.1.13",
40 | "rxjs": "^7.2.0",
41 | "typeorm": "^0.3.11"
42 | },
43 | "devDependencies": {
44 | "@nestjs/cli": "^9.0.0",
45 | "@nestjs/schematics": "^9.0.0",
46 | "@nestjs/testing": "^9.0.0",
47 | "@types/express": "^4.17.13",
48 | "@types/jest": "29.2.4",
49 | "@types/node": "18.11.18",
50 | "@types/supertest": "^2.0.11",
51 | "@typescript-eslint/eslint-plugin": "^5.0.0",
52 | "@typescript-eslint/parser": "^5.0.0",
53 | "eslint": "^8.0.1",
54 | "eslint-config-prettier": "^8.3.0",
55 | "eslint-plugin-prettier": "^4.0.0",
56 | "jest": "29.3.1",
57 | "prettier": "^2.3.2",
58 | "source-map-support": "^0.5.20",
59 | "supertest": "^6.1.3",
60 | "ts-jest": "29.0.3",
61 | "ts-loader": "^9.2.3",
62 | "ts-node": "^10.0.0",
63 | "tsconfig-paths": "4.1.1",
64 | "typescript": "^4.7.4"
65 | },
66 | "jest": {
67 | "moduleFileExtensions": [
68 | "js",
69 | "json",
70 | "ts"
71 | ],
72 | "rootDir": "src",
73 | "testRegex": ".*\\.spec\\.ts$",
74 | "transform": {
75 | "^.+\\.(t|j)s$": "ts-jest"
76 | },
77 | "collectCoverageFrom": [
78 | "**/*.(t|j)s"
79 | ],
80 | "coverageDirectory": "../coverage",
81 | "testEnvironment": "node"
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/app.controller.ts:
--------------------------------------------------------------------------------
1 | import { Controller, Get } from '@nestjs/common';
2 | import { AppService } from './app.service';
3 |
4 | @Controller()
5 | export class AppController {
6 | constructor(private readonly appService: AppService) {}
7 |
8 | @Get()
9 | getHello(): string {
10 | return this.appService.getHello();
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/app.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { AppController } from './app.controller';
3 | import { AppService } from './app.service';
4 | import { UsersModule } from './users/users.module';
5 | import { FilesModule } from './files/files.module';
6 | import { TypeOrmModule } from '@nestjs/typeorm';
7 | import { UserEntity } from './users/entities/user.entity';
8 | import { FileEntity } from './files/entities/file.entity';
9 | import { ConfigModule } from '@nestjs/config';
10 | import { AuthModule } from './auth/auth.module';
11 |
12 | @Module({
13 | imports: [
14 | ConfigModule.forRoot(),
15 | TypeOrmModule.forRoot({
16 | type: 'postgres',
17 | host: process.env.DB_HOST,
18 | port: Number(process.env.DB_PORT) || 5432,
19 | username: process.env.DB_USER,
20 | password: process.env.DB_PASSWORD,
21 | database: process.env.DB_NAME,
22 | entities: [UserEntity, FileEntity],
23 | synchronize: true,
24 | }),
25 | UsersModule,
26 | FilesModule,
27 | AuthModule,
28 | ],
29 | controllers: [AppController],
30 | providers: [AppService],
31 | })
32 | export class AppModule {}
33 |
--------------------------------------------------------------------------------
/src/app.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 |
3 | @Injectable()
4 | export class AppService {
5 | getHello(): string {
6 | return 'Hello World!';
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/auth/auth.controller.ts:
--------------------------------------------------------------------------------
1 | import { Controller, Post, UseGuards, Request, Body } from '@nestjs/common';
2 | import { AuthGuard } from '@nestjs/passport';
3 | import { ApiBody } from '@nestjs/swagger';
4 | import { CreateUserDto } from '../users/dto/create-user.dto';
5 | import { AuthService } from './auth.service';
6 | import { UserEntity } from '../users/entities/user.entity';
7 | import { LocalAuthGuard } from './guards/local.guard';
8 |
9 | @Controller('auth')
10 | export class AuthController {
11 | constructor(private readonly authService: AuthService) {}
12 |
13 | @UseGuards(LocalAuthGuard)
14 | @Post('login')
15 | @ApiBody({ type: CreateUserDto })
16 | async login(@Request() req) {
17 | return this.authService.login(req.user as UserEntity);
18 | }
19 |
20 | @Post('/register')
21 | register(@Body() dto: CreateUserDto) {
22 | return this.authService.register(dto);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/auth/auth.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { AuthService } from './auth.service';
3 | import { AuthController } from './auth.controller';
4 | import { UsersModule } from '../users/users.module';
5 | import { PassportModule } from '@nestjs/passport';
6 | import { LocalStrategy } from './strategies/local.strategy';
7 | import { JwtModule } from '@nestjs/jwt';
8 | import { ConfigModule, ConfigService } from '@nestjs/config';
9 | import { JwtStrategy } from './strategies/jwt.strategy';
10 |
11 | @Module({
12 | imports: [
13 | JwtModule.registerAsync({
14 | imports: [ConfigModule],
15 | inject: [ConfigService],
16 | useFactory: async (configService: ConfigService) => {
17 | return {
18 | secret: configService.get('SECRET_KEY'),
19 | signOptions: { expiresIn: configService.get('EXPIRES_IN') },
20 | };
21 | },
22 | }),
23 | UsersModule,
24 | PassportModule,
25 | ],
26 | providers: [AuthService, LocalStrategy, JwtStrategy],
27 | controllers: [AuthController],
28 | })
29 | export class AuthModule {}
30 |
--------------------------------------------------------------------------------
/src/auth/auth.service.ts:
--------------------------------------------------------------------------------
1 | import { ForbiddenException, Injectable } from '@nestjs/common';
2 | import { UsersService } from '../users/users.service';
3 | import { CreateUserDto } from '../users/dto/create-user.dto';
4 | import { UserEntity } from '../users/entities/user.entity';
5 | import { JwtService } from '@nestjs/jwt';
6 |
7 | @Injectable()
8 | export class AuthService {
9 | constructor(
10 | private usersService: UsersService,
11 | private jwtService: JwtService,
12 | ) {}
13 |
14 | async validateUser(email: string, password: string): Promise {
15 | const user = await this.usersService.findByEmail(email);
16 |
17 | if (user && user.password === password) {
18 | const { password, ...result } = user;
19 | return result;
20 | }
21 |
22 | return null;
23 | }
24 |
25 | async register(dto: CreateUserDto) {
26 | try {
27 | const userData = await this.usersService.create(dto);
28 |
29 | return {
30 | token: this.jwtService.sign({ id: userData.id }),
31 | };
32 | } catch (err) {
33 | console.log(err);
34 | throw new ForbiddenException('Ошибка при регистрации');
35 | }
36 | }
37 |
38 | async login(user: UserEntity) {
39 | return {
40 | token: this.jwtService.sign({ id: user.id }),
41 | };
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/auth/guards/jwt.guard.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 | import { AuthGuard } from '@nestjs/passport';
3 |
4 | @Injectable()
5 | export class JwtAuthGuard extends AuthGuard('jwt') {}
6 |
--------------------------------------------------------------------------------
/src/auth/guards/local.guard.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 | import { AuthGuard } from '@nestjs/passport';
3 |
4 | @Injectable()
5 | export class LocalAuthGuard extends AuthGuard('local') {}
6 |
--------------------------------------------------------------------------------
/src/auth/strategies/jwt.strategy.ts:
--------------------------------------------------------------------------------
1 | import { ExtractJwt, Strategy } from 'passport-jwt';
2 | import { PassportStrategy } from '@nestjs/passport';
3 | import { Injectable, UnauthorizedException } from '@nestjs/common';
4 | import { UsersService } from '../../users/users.service';
5 |
6 | @Injectable()
7 | export class JwtStrategy extends PassportStrategy(Strategy) {
8 | constructor(private readonly userService: UsersService) {
9 | super({
10 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
11 | ignoreExpiration: false,
12 | secretOrKey: process.env.SECRET_KEY,
13 | });
14 | }
15 |
16 | async validate(payload: { id: string }) {
17 | const user = await this.userService.findById(+payload.id);
18 |
19 | if (!user) {
20 | throw new UnauthorizedException('У вас нет доступа');
21 | }
22 |
23 | return {
24 | id: user.id,
25 | };
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/auth/strategies/local.strategy.ts:
--------------------------------------------------------------------------------
1 | import { Strategy } from 'passport-local';
2 | import { PassportStrategy } from '@nestjs/passport';
3 | import { Injectable, UnauthorizedException } from '@nestjs/common';
4 | import { AuthService } from '../auth.service';
5 |
6 | @Injectable()
7 | export class LocalStrategy extends PassportStrategy(Strategy) {
8 | constructor(private authService: AuthService) {
9 | super({
10 | usernameField: 'email',
11 | });
12 | }
13 |
14 | async validate(email: string, password: string): Promise {
15 | const user = await this.authService.validateUser(email, password);
16 |
17 | if (!user) {
18 | throw new UnauthorizedException('Неверный логин или пароль');
19 | }
20 |
21 | return user;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/decorators/user-id.decorator.ts:
--------------------------------------------------------------------------------
1 | import { createParamDecorator, ExecutionContext } from '@nestjs/common';
2 |
3 | export const UserId = createParamDecorator(
4 | (_: unknown, ctx: ExecutionContext): number | null => {
5 | const request = ctx.switchToHttp().getRequest();
6 | return request.user?.id ? Number(request.user.id) : null;
7 | },
8 | );
9 |
--------------------------------------------------------------------------------
/src/files/dto/create-file.dto.ts:
--------------------------------------------------------------------------------
1 | export class CreateFileDto {}
2 |
--------------------------------------------------------------------------------
/src/files/dto/update-file.dto.ts:
--------------------------------------------------------------------------------
1 | import { PartialType } from '@nestjs/swagger';
2 | import { CreateFileDto } from './create-file.dto';
3 |
4 | export class UpdateFileDto extends PartialType(CreateFileDto) {}
5 |
--------------------------------------------------------------------------------
/src/files/entities/file.entity.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Column,
3 | DeleteDateColumn,
4 | Entity,
5 | ManyToOne,
6 | PrimaryGeneratedColumn,
7 | } from 'typeorm';
8 | import { UserEntity } from '../../users/entities/user.entity';
9 |
10 | export enum FileType {
11 | PHOTOS = 'photos',
12 | TRASH = 'trash',
13 | }
14 |
15 | @Entity('files')
16 | export class FileEntity {
17 | @PrimaryGeneratedColumn()
18 | id: number;
19 |
20 | @Column()
21 | filename: string;
22 |
23 | @Column()
24 | originalName: string;
25 |
26 | @Column()
27 | size: number;
28 |
29 | @Column()
30 | mimetype: string;
31 |
32 | @ManyToOne(() => UserEntity, (user) => user.files)
33 | user: UserEntity;
34 |
35 | @DeleteDateColumn()
36 | deletedAt?: Date;
37 | }
38 |
--------------------------------------------------------------------------------
/src/files/files.controller.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Controller,
3 | Post,
4 | Body,
5 | UseInterceptors,
6 | UploadedFile,
7 | ParseFilePipe,
8 | MaxFileSizeValidator,
9 | Get,
10 | UseGuards,
11 | Query,
12 | Delete,
13 | } from '@nestjs/common';
14 | import { FilesService } from './files.service';
15 | import { CreateFileDto } from './dto/create-file.dto';
16 | import { ApiBearerAuth, ApiBody, ApiConsumes, ApiTags } from '@nestjs/swagger';
17 | import { FileInterceptor } from '@nestjs/platform-express';
18 | import { fileStorage } from './storage';
19 | import { JwtAuthGuard } from '../auth/guards/jwt.guard';
20 | import { UserId } from '../decorators/user-id.decorator';
21 | import { FileType } from './entities/file.entity';
22 |
23 | @Controller('files')
24 | @ApiTags('files')
25 | @UseGuards(JwtAuthGuard)
26 | @ApiBearerAuth()
27 | export class FilesController {
28 | constructor(private readonly filesService: FilesService) {}
29 |
30 | @Get()
31 | findAll(@UserId() userId: number, @Query('type') fileType: FileType) {
32 | return this.filesService.findAll(userId, fileType);
33 | }
34 |
35 | @Post()
36 | @UseInterceptors(
37 | FileInterceptor('file', {
38 | storage: fileStorage,
39 | }),
40 | )
41 | @ApiConsumes('multipart/form-data')
42 | @ApiBody({
43 | schema: {
44 | type: 'object',
45 | properties: {
46 | file: {
47 | type: 'string',
48 | format: 'binary',
49 | },
50 | },
51 | },
52 | })
53 | create(
54 | @UploadedFile(
55 | new ParseFilePipe({
56 | validators: [new MaxFileSizeValidator({ maxSize: 1024 * 1024 * 5 })],
57 | }),
58 | )
59 | file: Express.Multer.File,
60 | @UserId() userId: number,
61 | ) {
62 | return this.filesService.create(file, userId);
63 | }
64 |
65 | @Delete()
66 | remove(@UserId() userId: number, @Query('ids') ids: string) {
67 | // files?ids=1,2,7,8
68 | return this.filesService.remove(userId, ids);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/files/files.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { FilesService } from './files.service';
3 | import { FilesController } from './files.controller';
4 | import { TypeOrmModule } from '@nestjs/typeorm';
5 | import { FileEntity } from './entities/file.entity';
6 |
7 | @Module({
8 | controllers: [FilesController],
9 | providers: [FilesService],
10 | imports: [TypeOrmModule.forFeature([FileEntity])],
11 | })
12 | export class FilesModule {}
13 |
--------------------------------------------------------------------------------
/src/files/files.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 | import { InjectRepository } from '@nestjs/typeorm';
3 | import { FileEntity, FileType } from './entities/file.entity';
4 | import { Repository } from 'typeorm';
5 |
6 | @Injectable()
7 | export class FilesService {
8 | constructor(
9 | @InjectRepository(FileEntity)
10 | private repository: Repository,
11 | ) {}
12 |
13 | findAll(userId: number, fileType: FileType) {
14 | const qb = this.repository.createQueryBuilder('file');
15 |
16 | qb.where('file.userId = :userId', { userId });
17 |
18 | if (fileType === FileType.PHOTOS) {
19 | qb.andWhere('file.mimetype ILIKE :type', { type: '%image%' });
20 | }
21 |
22 | if (fileType === FileType.TRASH) {
23 | qb.withDeleted().andWhere('file.deletedAt IS NOT NULL');
24 | }
25 |
26 | return qb.getMany();
27 | }
28 |
29 | create(file: Express.Multer.File, userId: number) {
30 | return this.repository.save({
31 | filename: file.filename,
32 | originalName: file.originalname,
33 | size: file.size,
34 | mimetype: file.mimetype,
35 | user: { id: userId },
36 | });
37 | }
38 |
39 | async remove(userId: number, ids: string) {
40 | const idsArray = ids.split(',');
41 |
42 | const qb = this.repository.createQueryBuilder('file');
43 |
44 | qb.where('id IN (:...ids) AND userId = :userId', {
45 | ids: idsArray,
46 | userId,
47 | });
48 |
49 | return qb.softDelete().execute();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/files/storage.ts:
--------------------------------------------------------------------------------
1 | import { diskStorage } from 'multer';
2 |
3 | const generateId = () =>
4 | Array(18)
5 | .fill(null)
6 | .map(() => Math.round(Math.random() * 16).toString(16))
7 | .join('');
8 |
9 | const normalizeFileName = (req, file, callback) => {
10 | const fileExtName = file.originalname.split('.').pop();
11 |
12 | callback(null, `${generateId()}.${fileExtName}`);
13 | };
14 |
15 | export const fileStorage = diskStorage({
16 | destination: './uploads',
17 | filename: normalizeFileName,
18 | });
19 |
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import { NestFactory } from '@nestjs/core';
2 | import { AppModule } from './app.module';
3 | import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
4 | import * as express from 'express';
5 | import { join } from 'path';
6 |
7 | async function bootstrap() {
8 | const app = await NestFactory.create(AppModule, { cors: false });
9 |
10 | app.enableCors({ credentials: true, origin: true });
11 |
12 | app.use('/uploads', express.static(join(__dirname, '..', 'uploads')));
13 |
14 | const config = new DocumentBuilder()
15 | .setTitle('Облачное хранилище')
16 | .setVersion('1.0')
17 | .addBearerAuth()
18 | .build();
19 |
20 | const document = SwaggerModule.createDocument(app, config);
21 |
22 | SwaggerModule.setup('swagger', app, document, {
23 | swaggerOptions: {
24 | persistAuthorization: true,
25 | },
26 | });
27 |
28 | await app.listen(7777);
29 | }
30 | bootstrap();
31 |
--------------------------------------------------------------------------------
/src/users/dto/create-user.dto.ts:
--------------------------------------------------------------------------------
1 | import { ApiProperty } from '@nestjs/swagger';
2 |
3 | export class CreateUserDto {
4 | @ApiProperty({
5 | default: 'test@test.ru',
6 | })
7 | email: string;
8 |
9 | @ApiProperty({
10 | default: 'Мистер Кредо',
11 | })
12 | fullName: string;
13 |
14 | @ApiProperty({
15 | default: '123',
16 | })
17 | password: string;
18 | }
19 |
--------------------------------------------------------------------------------
/src/users/dto/update-user.dto.ts:
--------------------------------------------------------------------------------
1 | import { PartialType } from '@nestjs/mapped-types';
2 | import { CreateUserDto } from './create-user.dto';
3 |
4 | export class UpdateUserDto extends PartialType(CreateUserDto) {}
5 |
--------------------------------------------------------------------------------
/src/users/entities/user.entity.ts:
--------------------------------------------------------------------------------
1 | import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
2 | import { FileEntity } from '../../files/entities/file.entity';
3 |
4 | @Entity('users')
5 | export class UserEntity {
6 | @PrimaryGeneratedColumn()
7 | id: number;
8 |
9 | @Column()
10 | email: string;
11 |
12 | @Column()
13 | password: string;
14 |
15 | @Column()
16 | fullName: string;
17 |
18 | @OneToMany(() => FileEntity, (file) => file.user)
19 | files: FileEntity[];
20 | }
21 |
--------------------------------------------------------------------------------
/src/users/users.controller.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Controller,
3 | Get,
4 | Post,
5 | Body,
6 | Patch,
7 | Param,
8 | Delete,
9 | UseGuards,
10 | } from '@nestjs/common';
11 | import { UsersService } from './users.service';
12 | import { CreateUserDto } from './dto/create-user.dto';
13 | import { UpdateUserDto } from './dto/update-user.dto';
14 | import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
15 | import { JwtAuthGuard } from '../auth/guards/jwt.guard';
16 | import { UserId } from '../decorators/user-id.decorator';
17 |
18 | @Controller('users')
19 | @ApiTags('users')
20 | @ApiBearerAuth()
21 | export class UsersController {
22 | constructor(private readonly usersService: UsersService) {}
23 |
24 | @Get('/me')
25 | @UseGuards(JwtAuthGuard)
26 | getMe(@UserId() id: number) {
27 | return this.usersService.findById(id);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/users/users.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { UsersService } from './users.service';
3 | import { UsersController } from './users.controller';
4 | import { TypeOrmModule } from '@nestjs/typeorm';
5 | import { UserEntity } from './entities/user.entity';
6 |
7 | @Module({
8 | controllers: [UsersController],
9 | providers: [UsersService],
10 | imports: [TypeOrmModule.forFeature([UserEntity])],
11 | exports: [UsersService],
12 | })
13 | export class UsersModule {}
14 |
--------------------------------------------------------------------------------
/src/users/users.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 | import { InjectRepository } from '@nestjs/typeorm';
3 | import { Repository } from 'typeorm';
4 | import { UserEntity } from './entities/user.entity';
5 | import { CreateUserDto } from './dto/create-user.dto';
6 |
7 | @Injectable()
8 | export class UsersService {
9 | constructor(
10 | @InjectRepository(UserEntity)
11 | private repository: Repository,
12 | ) {}
13 |
14 | async findByEmail(email: string) {
15 | return this.repository.findOneBy({
16 | email,
17 | });
18 | }
19 |
20 | async findById(id: number) {
21 | return this.repository.findOneBy({
22 | id,
23 | });
24 | }
25 |
26 | create(dto: CreateUserDto) {
27 | return this.repository.save(dto);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------