This commit is contained in:
vigdorov
2020-12-06 14:57:45 +03:00
commit 0a8fb4cd50
20 changed files with 10042 additions and 0 deletions

24
.eslintrc.js Normal file
View File

@ -0,0 +1,24 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
root: true,
env: {
node: true,
jest: true,
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

34
.gitignore vendored Normal file
View File

@ -0,0 +1,34 @@
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-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

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

75
README.md Normal file
View File

@ -0,0 +1,75 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
</p>
[travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master
[travis-url]: https://travis-ci.org/nestjs/nest
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/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, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://gitter.im/nestjs/nestjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge"><img src="https://badges.gitter.im/nestjs/nestjs.svg" alt="Gitter" /></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec"><img src="https://img.shields.io/badge/Donate-PayPal-dc3d53.svg"/></a>
<a href="https://twitter.com/nestframework"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></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.
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## 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://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).

4
nest-cli.json Normal file
View File

@ -0,0 +1,4 @@
{
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}

9319
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

74
package.json Normal file
View File

@ -0,0 +1,74 @@
{
"name": "image-back",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest 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": "^7.0.0",
"@nestjs/core": "^7.0.0",
"@nestjs/mongoose": "^7.1.2",
"@nestjs/platform-express": "^7.0.0",
"@nestjs/swagger": "^4.7.5",
"mongoose": "^5.11.4",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.5.4",
"swagger-ui-express": "^4.1.5",
"uuid": "^8.3.1"
},
"devDependencies": {
"@nestjs/cli": "^7.0.0",
"@nestjs/schematics": "^7.0.0",
"@nestjs/testing": "^7.0.0",
"@types/express": "^4.17.3",
"@types/jest": "25.2.3",
"@types/mongoose": "^5.10.2",
"@types/node": "^13.9.1",
"@types/supertest": "^2.0.8",
"@types/uuid": "^8.3.0",
"@typescript-eslint/eslint-plugin": "3.0.2",
"@typescript-eslint/parser": "3.0.2",
"eslint": "7.1.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-import": "^2.20.1",
"jest": "26.0.1",
"prettier": "^1.19.1",
"supertest": "^4.0.2",
"ts-jest": "26.1.0",
"ts-loader": "^6.2.1",
"ts-node": "^8.6.2",
"tsconfig-paths": "^3.9.0",
"typescript": "^3.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

38
src/api.responses.ts Normal file
View File

@ -0,0 +1,38 @@
import {ApiProperty, ApiResponseOptions} from '@nestjs/swagger';
import {ImageResponse} from './schemas';
class Error {
@ApiProperty()
statusCode: number;
@ApiProperty()
message: string;
@ApiProperty()
error: string;
}
export const AUTH_ERROR: ApiResponseOptions = {
status: 406,
description: 'Ошибка, при попытке получить доступ к данным без токена или с не корректным токеном',
type: Error,
};
export const GET_IMAGE_LIST_SUCCESS: ApiResponseOptions = {
status: 200,
description: 'Список всех картинок',
type: ImageResponse,
isArray: true
};
export const MANIPULATE_IMAGE_SUCCESS: ApiResponseOptions = {
status: 200,
description: 'Картинка',
type: ImageResponse,
};
export const AUTH_SUCCESS: ApiResponseOptions = {
status: 200,
description: 'Токен пользователя',
type: String,
};

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!');
});
});
});

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

@ -0,0 +1,116 @@
import {Controller, Delete, Get, Header, HttpCode, Options, Post, Put, Req} from '@nestjs/common';
import {AppService} from './app.service';
import {AuthRequest, ImageCreateRequest} from './schemas';
import {Request} from 'express';
import {ApiBody, ApiParam, ApiResponse, ApiSecurity, ApiTags} from '@nestjs/swagger';
import {Image, ImageCreate} from './types';
import {ALLOW_CREDENTIALS, ALLOW_HEADERS, ALLOW_METHOD, ALLOW_ORIGIN_ALL, CONTENT_LENGTH} from './consts';
import {AUTH_ERROR, AUTH_SUCCESS, GET_IMAGE_LIST_SUCCESS, MANIPULATE_IMAGE_SUCCESS} from './api.responses';
@Controller()
@ApiTags('image-app')
export class AppController {
constructor(private readonly appService: AppService) { }
@Post('/auth')
@ApiBody({
type: AuthRequest,
description: 'Объект с логином пользователя',
})
@Header(...ALLOW_ORIGIN_ALL)
@ApiResponse(AUTH_SUCCESS)
authUser(
@Req() request: Request<null, {login: string}>
): Promise<string> {
return this.appService.authUser(request.body.login);
}
@Get('/list')
@ApiSecurity('apiKey')
@Header(...ALLOW_ORIGIN_ALL)
@ApiResponse(GET_IMAGE_LIST_SUCCESS)
@ApiResponse(AUTH_ERROR)
async getImageList(
@Req() request: Request
): Promise<Image[]> {
await this.appService.checkRequest(request.headers.authorization);
return this.appService.getImageList();
}
@Get('/list/:id')
@ApiSecurity('apiKey')
@ApiParam({
name: 'id',
description: 'id картинки',
})
@Header(...ALLOW_ORIGIN_ALL)
@ApiResponse(MANIPULATE_IMAGE_SUCCESS)
@ApiResponse(AUTH_ERROR)
async getImageById(
@Req() request: Request<{id: string}>
): Promise<Image> {
await this.appService.checkRequest(request.headers.authorization);
return this.appService.getImageById(request.params.id);
}
@Post('/list')
@ApiSecurity('apiKey')
@ApiBody({
type: ImageCreateRequest,
description: 'Объект создания картинки',
})
@Header(...ALLOW_ORIGIN_ALL)
@ApiResponse(MANIPULATE_IMAGE_SUCCESS)
@ApiResponse(AUTH_ERROR)
async createImage(
@Req() request: Request<null, ImageCreate>
): Promise<Image> {
const {login} = await this.appService.checkRequest(request.headers.authorization);
return this.appService.addImage(login, request.body)
}
@Put('/list/:id')
@ApiSecurity('apiKey')
@ApiParam({
name: 'id',
description: 'id картинки',
})
@Header(...ALLOW_ORIGIN_ALL)
@ApiResponse(MANIPULATE_IMAGE_SUCCESS)
@ApiResponse(AUTH_ERROR)
async toggleLike(
@Req() request: Request<{id: string}>
): Promise<Image> {
const {login} = await this.appService.checkRequest(request.headers.authorization);
return this.appService.toggleLike(login, request.params.id);
}
@Delete('/list/:id')
@ApiSecurity('apiKey')
@ApiParam({
name: 'id',
description: 'id картинки',
})
@Header(...ALLOW_ORIGIN_ALL)
@ApiResponse(MANIPULATE_IMAGE_SUCCESS)
@ApiResponse(AUTH_ERROR)
async deleteImage(
@Req() request: Request<{id: string}>
): Promise<Image> {
const {login} = await this.appService.checkRequest(request.headers.authorization);
return this.appService.deleteImageById(login, request.params.id);
}
@Options([
'', '/auth', '/list', '/list/:id'
])
@Header(...ALLOW_ORIGIN_ALL)
@Header(...ALLOW_METHOD)
@Header(...ALLOW_CREDENTIALS)
@Header(...CONTENT_LENGTH)
@Header(...ALLOW_HEADERS)
@HttpCode(204)
async options(): Promise<string> {
return '';
}
}

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

@ -0,0 +1,26 @@
import {Module} from '@nestjs/common';
import {MongooseModule} from '@nestjs/mongoose/dist/mongoose.module';
import {AppController} from './app.controller';
import {AppService} from './app.service';
import {DB_IMAGES, DB_AUTHORS, MONGO_URL} from './consts';
import {AuthorDocument, AuthorScheme, ImageDocument, ImageScheme} from './schemas';
@Module({
imports: [
MongooseModule.forRoot(`${MONGO_URL}/${DB_AUTHORS}`, {
connectionName: DB_AUTHORS,
}),
MongooseModule.forRoot(`${MONGO_URL}/${DB_IMAGES}`, {
connectionName: DB_IMAGES,
}),
MongooseModule.forFeature([
{name: AuthorDocument.name, schema: AuthorScheme},
], DB_AUTHORS),
MongooseModule.forFeature([
{name: ImageDocument.name, schema: ImageScheme},
], DB_IMAGES),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }

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

@ -0,0 +1,125 @@
import {BadRequestException, Injectable, NotAcceptableException} from '@nestjs/common';
import {InjectModel} from '@nestjs/mongoose';
import {Model} from 'mongoose';
import {v4} from 'uuid';
import {AuthorDocument, ImageDocument} from './schemas';
import {Author, Image, ImageCreate} from './types';
@Injectable()
export class AppService {
constructor(
@InjectModel(AuthorDocument.name) private authorModel: Model<AuthorDocument>,
@InjectModel(ImageDocument.name) private imageModel: Model<ImageDocument>,
) { }
async checkRequest(token?: string): Promise<Author> {
const authorList = await this.authorModel.find().exec();
const searchAuthor = authorList.find((author) => author.token === token);
if (searchAuthor) {
return {
login: searchAuthor.login,
token: searchAuthor.token,
};
}
throw new NotAcceptableException(`Доступ запрещен`);
}
async getImageList(): Promise<Image[]> {
const imageList = await this.imageModel.find().exec();
return imageList.map(({url, author, likes, id}) => ({
url,
author,
likes,
id,
}));
}
async authUser(login: string): Promise<string> {
const authorList = await this.authorModel.find().exec();
const searchAuthor = authorList.find((author) => author.login === login);
if (searchAuthor) {
return searchAuthor.token;
}
const Model = await this.authorModel;
const userModel = new Model({
login,
token: v4(),
});
const newUser = await userModel.save();
return newUser.token;
}
async addImage(login: string, image: ImageCreate): Promise<Image> {
const Model = await this.imageModel;
const imageModel = new Model({
url: image.url,
likes: [],
author: login,
});
try {
await imageModel.validate();
} catch (e) {
throw new BadRequestException(e.message);
}
const newImage = await imageModel.save();
return {
url: newImage.url,
author: newImage.author,
likes: [],
id: newImage.id,
};
}
async getImageById(id: string): Promise<Image> {
const searchImage = await this.imageModel.findById(id);
if (searchImage) {
return {
url: searchImage.url,
author: searchImage.author,
likes: searchImage.likes,
id: searchImage.id,
};
}
throw new BadRequestException(`Картинка с id - "${id}" не найдена`);
}
async deleteImageById(login: string, id: string): Promise<Image> {
const searchImage = await this.imageModel.findById(id);
if (!searchImage) {
throw new BadRequestException(`Картинка с id - "${id}" не найдена`);
}
if (searchImage.author !== login) {
throw new NotAcceptableException(`Нельзя удалить чужую картинку`);
}
const Model = await this.imageModel;
await Model.findByIdAndDelete(id);
return {
url: searchImage.url,
author: searchImage.author,
likes: searchImage.likes,
id: searchImage.id,
};
}
async toggleLike(login: string, id: string): Promise<Image> {
const searchImage = await this.imageModel.findById(id);
if (!searchImage) {
throw new BadRequestException(`Картинка с id - "${id}" не найдена`);
}
const updatedLikes = searchImage.likes.includes(login)
? searchImage.likes.filter(userLogin => userLogin !== login)
: searchImage.likes.concat(login);
await searchImage.updateOne({
likes: updatedLikes,
});
return {
url: searchImage.url,
author: searchImage.author,
likes: updatedLikes,
id: searchImage.id,
};
}
}

12
src/consts.ts Normal file
View File

@ -0,0 +1,12 @@
export const MONGO_URL = 'mongodb://localhost:27017';
export const DB_AUTHORS = 'image-back-authors';
export const DB_IMAGES = 'image-back-images';
export const APP_CONTROLLER = 'image-app';
export const ALLOW_ORIGIN_ALL: [string, string] = ['Access-Control-Allow-Origin', '*'];
export const ALLOW_CREDENTIALS: [string, string] = ['Access-Control-Allow-Credentials', 'true'];
export const CONTENT_LENGTH: [string, string] = ['Content-Length', '0'];
export const ALLOW_METHOD: [string, string] = ['Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE'];
export const ALLOW_HEADERS: [string, string] = ['Access-Control-Allow-Headers', 'Version, Authorization, Content-Type, Api-Name, x-turbo-id, x-turbo-compression, chrome-proxy, chrome-proxy-ect'];

26
src/main.ts Normal file
View File

@ -0,0 +1,26 @@
import {NestFactory} from '@nestjs/core';
import {SwaggerModule, DocumentBuilder} from '@nestjs/swagger';
import {AppModule} from './app.module';
import {APP_CONTROLLER} from './consts';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const options = new DocumentBuilder()
.addSecurity('apiKey', {
type: 'apiKey',
in: 'header',
name: 'Authorization',
})
.setTitle('Image API')
.setDescription('API для работы с картинками')
.setVersion('1.0.0')
.addTag(APP_CONTROLLER)
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
await app.listen(4003);
}
bootstrap();

75
src/schemas.ts Normal file
View File

@ -0,0 +1,75 @@
import {ApiProperty} from '@nestjs/swagger/dist/decorators';
import {Document} from 'mongoose';
import {Prop, Schema, SchemaFactory} from '@nestjs/mongoose';
import {Author, Image} from './types';
export class AuthRequest {
@ApiProperty()
login: string;
}
export class ImageCreateRequest {
@ApiProperty()
url: string;
}
export class AuthorResponse implements Author {
@ApiProperty()
login: string;
@ApiProperty()
token: string;
}
export class ImageResponse implements Image {
@ApiProperty()
url: string;
@ApiProperty()
author: string;
@ApiProperty()
likes: string[];
@ApiProperty()
id: string;
}
@Schema()
export class AuthorDocument extends Document {
@Prop({
type: String,
required: true,
})
login: string;
@Prop({
type: String,
required: true,
})
token: string;
}
@Schema()
export class ImageDocument extends Document {
@Prop({
type: String,
required: true,
})
url: string;
@Prop({
type: String,
required: true,
})
author: string;
@Prop({
type: [String],
required: true,
})
likes: string[];
}
export const ImageScheme = SchemaFactory.createForClass(ImageDocument);
export const AuthorScheme = SchemaFactory.createForClass(AuthorDocument);

15
src/types.ts Normal file
View File

@ -0,0 +1,15 @@
export type ImageCreate = {
url: string;
};
export type Image = {
url: string;
author: string;
likes: string[];
id: string;
};
export type Author = {
login: string;
token: string;
};

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

@ -0,0 +1,24 @@
import {Test, TestingModule} from '@nestjs/testing';
import {INestApplication} from '@nestjs/common';
import * as request from 'supertest';
import {AppModule} from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
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"]
}

16
tsconfig.json Normal file
View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true
}
}