Skip to content

Commit

Permalink
Merge pull request #8 from RnizereB/master
Browse files Browse the repository at this point in the history
  • Loading branch information
keksobot authored Nov 10, 2024
2 parents 3a6641e + 6f20609 commit 57541f2
Show file tree
Hide file tree
Showing 38 changed files with 114 additions and 105 deletions.
2 changes: 1 addition & 1 deletion .env-example
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ DB_NAME=six-cities
DB_USERNAME=Admin
DB_PASSWORD=admin
DB_PORT=27017
UPLOAD_DIRECTIRY=\upload
UPLOAD_DIRECTORY=\upload
JWT_SECRET=secret
HOST=localhost
STATIC_DIRECTORY_PATH=static\
4 changes: 2 additions & 2 deletions src/main.rest.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'reflect-metadata';
import { RestApplication, createReasApplicationContainer} from './rest/index.js';
import { RestApplication, createRestApplicationContainer} from './rest/index.js';
import { Container } from 'inversify';
import { Component } from './shared/types/index.js';
import { createUserContainer } from './shared/modules/user/index.js';
Expand All @@ -9,7 +9,7 @@ import { createAuthContainer } from './shared/modules/auth/index.js';

async function bootstrap() {
const appContainer = Container.merge(
createReasApplicationContainer(),
createRestApplicationContainer(),
createUserContainer(),
createOfferContainer(),
createCommentContainer(),
Expand Down
2 changes: 1 addition & 1 deletion src/rest/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export { RestApplication } from './rest.application.js';
export { createReasApplicationContainer } from './rest.container.js';
export { createRestApplicationContainer } from './rest.container.js';
export { StaticRoute } from './rest.constant.js';
12 changes: 6 additions & 6 deletions src/rest/rest.application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class RestApplication {
);
this.server.use(
StaticRoute.Static,
express.static(this.config.get('UPLOAD_DIRECTIRY'))
express.static(this.config.get('UPLOAD_DIRECTORY'))
);
this.server.use(authenticateMiddleware.execute.bind(authenticateMiddleware));
this.server.use(cors());
Expand All @@ -77,24 +77,24 @@ export class RestApplication {
}

public async init() {
this.logger.info('Application initiazation');
this.logger.info('Application initialization ');
this.logger.info(`Get value from env $PORT: ${this.config.get('PORT')}`);

this.logger.info('Init database...');
await this.initDb();
this.logger.info('init database completed');

this.logger.info('Init app-level midlleware');
this.logger.info('Init app-level middleware');
await this.initMiddleware();
this.logger.info('App-level middleware initiazation completed');
this.logger.info('App-level middleware initialization completed');

this.logger.info('Init controllers...');
await this.initControllers();
this.logger.info('Controller initiazation completed');
this.logger.info('Controller initialization completed');

this.logger.info('Init exception filters');
await this.initExceptionFilter();
this.logger.info('Exception filters initialization compleated.');
this.logger.info('Exception filters initialization completed.');

this.logger.info('Try to init server...');
await this.initServer();
Expand Down
6 changes: 3 additions & 3 deletions src/rest/rest.container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { Logger, PinoLogger} from './../shared/libs/logger/index.js';
import { Container } from 'inversify';
import { Component } from './../shared/types/index.js';
import { DatabaseClient, MongoDatabaseClient } from './../shared/libs/database-client/index.js';
import { AppExceptionFilter, ExceptionFilter, ValodationExceptionFilter, HttpErrorExceptionFilter, PathTransformer } from '../shared/libs/rest/index.js';
import { AppExceptionFilter, ExceptionFilter, ValidationExceptionFilter, HttpErrorExceptionFilter, PathTransformer } from '../shared/libs/rest/index.js';

export function createReasApplicationContainer() {
export function createRestApplicationContainer() {
const container = new Container();

container.bind<RestApplication>(Component.RestApplication).to(RestApplication).inSingletonScope();
Expand All @@ -15,7 +15,7 @@ export function createReasApplicationContainer() {
container.bind<DatabaseClient>(Component.DatabaseClient).to(MongoDatabaseClient).inSingletonScope();
container.bind<ExceptionFilter>(Component.ExceptionFilter).to(AppExceptionFilter).inSingletonScope();
container.bind<ExceptionFilter>(Component.HttpExceptionFilter).to(HttpErrorExceptionFilter).inSingletonScope();
container.bind<ExceptionFilter>(Component.ValidationExceptionFilter).to(ValodationExceptionFilter).inSingletonScope();
container.bind<ExceptionFilter>(Component.ValidationExceptionFilter).to(ValidationExceptionFilter).inSingletonScope();
container.bind<PathTransformer>(Component.PathTransformer).to(PathTransformer).inSingletonScope();

return container;
Expand Down
4 changes: 2 additions & 2 deletions src/shared/helpers/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export function getRandomElement<T>(items: T[]):T {
return items[getRandomNumber(0, items.length - 1)];
}

export function fillDTO<T, V>(someDto: ClassConstructor<T>, plainObjaect: V) {
return plainToInstance(someDto, plainObjaect, { excludeExtraneousValues: true});
export function fillDTO<T, V>(someDto: ClassConstructor<T>, plainObject: V) {
return plainToInstance(someDto, plainObject, { excludeExtraneousValues: true});
}

export function createErrorObject(errorType: ApplicationError, error: string, details: ValidationErrorField[] = []) {
Expand Down
6 changes: 3 additions & 3 deletions src/shared/libs/config/rest.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export type RestSchema = {
DB_USERNAME: string,
DB_PASSWORD: string,
DB_PORT: string,
UPLOAD_DIRECTIRY: string,
UPLOAD_DIRECTORY: string,
JWT_SECRET: string,
HOST: string
STATIC_DIRECTORY_PATH:string
Expand Down Expand Up @@ -60,10 +60,10 @@ export const configRestSchema = convict<RestSchema>({
env: 'DB_PORT',
default: '27017'
},
UPLOAD_DIRECTIRY: {
UPLOAD_DIRECTORY: {
doc: 'Directory for upload files',
format: String,
env: 'UPLOAD_DIRECTIRY',
env: 'UPLOAD_DIRECTORY',
default: null
},
JWT_SECRET: {
Expand Down
10 changes: 5 additions & 5 deletions src/shared/libs/database-client/mongo.database-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@ import { setTimeout } from 'node:timers/promises';
@injectable()
export class MongoDatabaseClient implements DatabaseClient {

private isConneted: boolean;
private isConnected: boolean;
private mongoose: typeof Mongoose;

constructor(
@inject(Component.Logger) private readonly logger: Logger
) {
this.isConneted = false;
this.isConnected = false;
}

public isConnectedToDatabase() {
return this.isConneted;
return this.isConnected;
}

public async connect(uri: string): Promise<void> {
Expand All @@ -36,7 +36,7 @@ export class MongoDatabaseClient implements DatabaseClient {
while (attempt < Retry.Count) {
try {
this.mongoose = await Mongoose.connect(uri);
this.isConneted = true;
this.isConnected = true;
this.logger.info('Database connection established.');
return;
} catch (error) {
Expand All @@ -53,7 +53,7 @@ export class MongoDatabaseClient implements DatabaseClient {
}

await this.mongoose.disconnect?.();
this.isConneted = false;
this.isConnected = false;
this.logger.info('Database connection closed');
}
}
26 changes: 12 additions & 14 deletions src/shared/libs/file-reader/tsv-file-reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,19 @@ export class TSVFileReader extends EventEmitter implements FileReader {
}

private parseBoolean(itemString: string): boolean {
if (itemString === 'true') {
return true;
}
return false;
return itemString === 'true';
}

private parseStringToNumber(itemString: string): number {
return Number.parseInt(itemString, 10);
}

private parseGoods(goods: string): string[] {
return goods.split(';').map((good) => (good));
return goods.split(';');
}

private parseImages(images: string): string[] {
return images.split(';').map((img) => (img));
return images.split(';');
}

private parseHost(name: string, email: string, avatarUser: string, password: string, status: string) {
Expand All @@ -88,27 +85,28 @@ export class TSVFileReader extends EventEmitter implements FileReader {
});

let remainingData = '';
let nextLinePosititon = -1;
let importedRowCouint = 0;

let nextLinePosition = -1;
let importedRowCount = 0;
for await (const chunk of readStream) {
remainingData += chunk.toString();
nextLinePosition = remainingData.indexOf('\n');

while((nextLinePosititon = remainingData.indexOf('\n')) >= 0) {
const completeRow = remainingData.slice(0, nextLinePosititon + 1);
remainingData = remainingData.slice(++nextLinePosititon);
importedRowCouint++;
while(nextLinePosition >= 0) {
const completeRow = remainingData.slice(0, nextLinePosition + 1);
remainingData = remainingData.slice(++nextLinePosition);
importedRowCount++;

const parsedOffer = this.parseLineToOffer(completeRow);

await new Promise((resolve) => {
this.emit('line', parsedOffer, resolve);
});

nextLinePosition = remainingData.indexOf('\n');
}
}

this.emit('end', importedRowCouint);
this.emit('end', importedRowCount);
}
}

2 changes: 1 addition & 1 deletion src/shared/libs/file-writer/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { FileWriter } from './file-writer.interface.js';
export { TSVFileWriter } from './tsv-file-wtiter.js';
export { TSVFileWriter } from './tsv-file-writer.js';
4 changes: 2 additions & 2 deletions src/shared/libs/rest/controller/base-controller.abstract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ export abstract class BaseController implements Controller {
}

public send<T>(res: Response, statusCode: number, data: T): void {
const modifieData = this.pathTransformer.execute(data as Record<string, unknown>);
res.type(this.DEFAULT_CONTENT_TYPE).status(statusCode).json(modifieData);
const modifyData = this.pathTransformer.execute(data as Record<string, unknown>);
res.type(this.DEFAULT_CONTENT_TYPE).status(statusCode).json(modifyData);
}

public created<T>(res: Response, data: T): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@ import { createErrorObject } from '../../../helpers/index.js';


@injectable()
export class ValodationExceptionFilter implements ExceptionFilter {
export class ValidationExceptionFilter implements ExceptionFilter {

constructor(
@inject(Component.Logger) private readonly logger: Logger
) {
this.logger.info('Register ValodationExceptionFilter');
this.logger.info('Register ValidationExceptionFilter');
}

public catch(error: unknown, _req: Request, res: Response, next: NextFunction): void {
if (! (error instanceof ValidationError)) {
return next(error);
}

this.logger.error(`[ValodationException]: ${error.message}`, error);
this.logger.error(`[ValidationException]: ${error.message}`, error);

error.details?.forEach(
(errorField) => this.logger.warn(`[${errorField.property}] - ${errorField.messages}`)
Expand Down
6 changes: 3 additions & 3 deletions src/shared/libs/rest/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export { HttpMethod } from './types/http-method.enum.js';
export { Route } from './types/route.interface.js';
export { Controller } from './controller/controller.interfase.js';
export { Controller } from './controller/controller.interface.js';
export { BaseController } from './controller/base-controller.abstract.js';
export { ExceptionFilter } from './exception-filter/exception-filter.interface.js';
export { AppExceptionFilter,} from './exception-filter/app-exception-filter.js';
Expand All @@ -11,7 +11,7 @@ export { Middleware } from './middleware/middleware.interface.js';
export { ParseTokenMiddleware } from './middleware/parse-token.middleware.js';
export { AuthExceptionFilter } from './exception-filter/auth-exception-filter.js';
export { HttpErrorExceptionFilter } from './exception-filter/http-error-exception-filter.js';
export { ValodationExceptionFilter } from './exception-filter/validation-exception-filter.js';
export { ValidationExceptionFilter } from './exception-filter/validation-exception-filter.js';
export { DEFAULT_STATIC_IMAGES, STATIC_RESOURCE_FIELDS } from './transform/path-transformer.constant.js';
export { PathTransformer } from './transform/path-transformer.js';
export { ValidationErrorField } from './types/validation-error-field.js';
Expand All @@ -21,4 +21,4 @@ export { ValidateDtoMiddleware } from './middleware/validate-dto.middleware.js';
export { PrivateRouteMiddleware } from './middleware/private-route.middleware.js';
export { DocumentExistsMiddleware } from './middleware/document-exists.middleware.js';
export { ValidateObjectIdMiddleware } from './middleware/validate-objectid.middleware.js';
export { UploadFileMiddleware } from './middleware/upload-file.middlewate.js';
export { UploadFileMiddleware } from './middleware/upload-file.middleware.js';
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ export class UploadFileMiddleware implements Middleware {
const storage = diskStorage({
destination: this.uploadDirectory,
filename: (_req, file, callback) => {
const fileExtention = extension(file.mimetype);
const fileExtension = extension(file.mimetype);
const filename = crypto.randomUUID();
callback(null, `${filename}.${fileExtention}`);
callback(null, `${filename}.${fileExtension}`);
}
});

Expand Down
2 changes: 1 addition & 1 deletion src/shared/modules/comment/comment.container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function createCommentContainer() {
const container = new Container();

container.bind<CommentService>(Component.CommentService).to(DefaultCommentService).inSingletonScope();
container.bind<types.ModelType<CommentEntity>>(Component.CommentModul).toConstantValue(CommentModel);
container.bind<types.ModelType<CommentEntity>>(Component.CommentModel).toConstantValue(CommentModel);
container.bind<Controller>(Component.CommentController).to(CommentController).inSingletonScope();

return container;
Expand Down
2 changes: 1 addition & 1 deletion src/shared/modules/comment/comment.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class CommentEntity extends defaultClasses.TimeStamps {
@prop({required: true, ref: OfferEntity})
public offerId: Ref<OfferEntity>;

@prop({required: true, minlength: 5, maxlength: 1024 })
@prop({required: true, minLength: 5, maxLength: 1024 })
public comment: string;

@prop({required: true, min: 1, max: 5})
Expand Down
6 changes: 3 additions & 3 deletions src/shared/modules/comment/default-comment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class DefaultCommentService implements CommentService {

constructor(
@inject(Component.Logger) private readonly logger: Logger,
@inject(Component.CommentModul) private readonly commentModel: types.ModelType<CommentEntity>
@inject(Component.CommentModel) private readonly commentModel: types.ModelType<CommentEntity>
) {}

public async create(dto: CreateCommentDto): Promise<types.DocumentType<CommentEntity>> {
Expand All @@ -21,10 +21,10 @@ export class DefaultCommentService implements CommentService {

public async findByOfferId(offerId: string, count?: number): Promise<types.DocumentType<CommentEntity>[]> {
const limit = count ?? 50;
const connets = this.commentModel.find({offerId}, {}, { limit }).populate('userId');
const connects = this.commentModel.find({offerId}, {}, { limit }).populate('userId');
this.logger.info(`List of comments for offer id:${offerId}`);

return connets;
return connects;
}

public async deleteByOfferId(offerId: string): Promise<number | null> {
Expand Down
2 changes: 1 addition & 1 deletion src/shared/modules/comment/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { CommentService } from './comment-servise.interface.js';
export { CommentService } from './comment-service.interface.js';
export { createCommentContainer } from './comment.container.js';
export { CommentEntity, CommentModel } from './comment.entity.js';
export { DefaultCommentService } from './default-comment.service.js';
Expand Down
2 changes: 1 addition & 1 deletion src/shared/modules/offer/default-offer.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class DefaultOfferService implements OfferService {

constructor(
@inject(Component.Logger) private readonly logger: Logger,
@inject(Component.OfferModul) private readonly offerModel: types.ModelType<OfferEntity>
@inject(Component.OfferModel) private readonly offerModel: types.ModelType<OfferEntity>
) {}

public async create(dto: CreateOfferDto): Promise<types.DocumentType<OfferEntity>> {
Expand Down
3 changes: 1 addition & 2 deletions src/shared/modules/offer/dto/create-offer.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MinLength, MaxLength, IsDateString, IsInt, Min, Max, IsEnum, IsBoolean, IsMongoId } from 'class-validator';
import { MinLength, MaxLength, IsDateString, IsInt, Min, Max, IsEnum, IsBoolean } from 'class-validator';
import { CreateOfferValidationMessage } from './create-offer.messages.js';
import { TypeOffer } from '../../../types/index.js';

Expand Down Expand Up @@ -47,6 +47,5 @@ export class CreateOfferDto {

public goods: string[];

@IsMongoId({ message: CreateOfferValidationMessage.host.invalidId })
public host: string;
}
8 changes: 2 additions & 6 deletions src/shared/modules/offer/dto/create-offer.messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ export const CreateOfferValidationMessage = {
postDate: {
invalidFormat: 'PostDate must be a valid ISO date',
},
//city: {},

previewImage:{
maxLength: 'Too short for field «previewImage»',
},
// images:

isFavorite: {
invalidFormat: 'isFavorite must be an false of true'
},
Expand Down Expand Up @@ -44,10 +44,6 @@ export const CreateOfferValidationMessage = {
min: 'Minimum price is 100',
max: 'Maximum price is 100 000'
},
//goods:
host: {
invalidId: 'Host field must be a valid id',
},
} as const;


Loading

0 comments on commit 57541f2

Please sign in to comment.