init app
This commit is contained in:
38
src/api.responses.ts
Normal file
38
src/api.responses.ts
Normal 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,
|
||||
};
|
||||
22
src/app.controller.spec.ts
Normal file
22
src/app.controller.spec.ts
Normal 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
116
src/app.controller.ts
Normal 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
26
src/app.module.ts
Normal 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
125
src/app.service.ts
Normal 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
12
src/consts.ts
Normal 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
26
src/main.ts
Normal 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
75
src/schemas.ts
Normal 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
15
src/types.ts
Normal 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;
|
||||
};
|
||||
Reference in New Issue
Block a user