Skip to content

Commit

Permalink
Code review
Browse files Browse the repository at this point in the history
  • Loading branch information
Karlen-ll committed Oct 30, 2024
1 parent 402a8f3 commit 84848f4
Show file tree
Hide file tree
Showing 14 changed files with 35 additions and 60 deletions.
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
PORT=3100
SALT=hash

# Docker
DB_USER=admin
DB_PASS=test
DB_HOST=127.0.0.1
DB_PORT=27017
DB_NAME=six-cities
3 changes: 1 addition & 2 deletions src/cli/cli-application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@ export class CliApplication {
private commandAliasMap: Record<string, string> = {};

private readonly defaultCommand: string = '';
private readonly logger: Logger;
private readonly logger: Logger = new ConsoleLogger();

constructor(defaultCommand: string) {
this.logger = new ConsoleLogger();
this.defaultCommand = defaultCommand;
}

Expand Down
1 change: 0 additions & 1 deletion src/cli/commands/command.constant.ts

This file was deleted.

8 changes: 2 additions & 6 deletions src/cli/commands/generate.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,8 @@ export class GenerateCommand implements Command {
readonly description = 'Генерирует произвольное количество тестовых данных';
readonly params = ['n', 'filepath', 'url'];

private readonly logger: Logger;
private initialData!: MockServerData;

constructor() {
this.logger = new ConsoleLogger();
}
private readonly logger: Logger = new ConsoleLogger();
private initialData: MockServerData;

private async load(url: string) {
try {
Expand Down
6 changes: 1 addition & 5 deletions src/cli/commands/help.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,7 @@ export class HelpCommand implements Command {
readonly alias = '-h';
readonly description = 'Выводит справочную информацию';

private readonly logger: Logger;

constructor() {
this.logger = new ConsoleLogger();
}
private readonly logger: Logger = new ConsoleLogger();

/** Получить пример вызова
* @example --command <param_1> <param_2> */
Expand Down
17 changes: 5 additions & 12 deletions src/cli/commands/import.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,22 @@ import { TSVOfferFileReader } from '../../shared/libs/index.js';
import { EventName } from '../../constants/index.js';
import { Offer } from '../../shared/types/index.js';
import { Command } from '../../cli/index.js';
import { DEFAULT_USER_PASS } from './command.constant.js';

const LINE_WORDS = ['строка', 'строки', 'строк'];
const DEFAULT_USER_PASS = '123456';

export class ImportCommand implements Command {
readonly name = '--import';
readonly alias = '-i';
readonly description = 'Импортирует данные из TSV файла';
readonly params = ['path', 'mongoUri', 'salt'];

private readonly logger: Logger;
private databaseClient: DatabaseClient;
private offerService: OfferService;
private userService: UserService;
private readonly logger: Logger = new ConsoleLogger();
private offerService: OfferService = new DefaultOfferService(this.logger, OfferModel);
private userService: UserService = new DefaultUserService(this.logger, UserModel);
private databaseClient: DatabaseClient = new MongoDatabaseClient(this.logger);
private salt: string;

constructor() {
this.logger = new ConsoleLogger();
this.offerService = new DefaultOfferService(this.logger, OfferModel);
this.userService = new DefaultUserService(this.logger, UserModel);
this.databaseClient = new MongoDatabaseClient(this.logger);
}

private async onReadLine(offer: Offer, index: number, resolve: () => void) {
this.logger.info(`\nИмпортирована ${chalk.bold.magenta(`${index}-ая`)} строка:`, offer);
await this.saveOffer(offer);
Expand Down
6 changes: 1 addition & 5 deletions src/cli/commands/version.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ export class VersionCommand implements Command {
readonly alias = '-v';
readonly description = 'Выводит номер версии';

private readonly logger: Logger;

constructor() {
this.logger = new ConsoleLogger();
}
private readonly logger: Logger = new ConsoleLogger();

private getVersion(): string {
if (process.env?.npm_package_version) {
Expand Down
13 changes: 2 additions & 11 deletions src/rest/rest.application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { inject, injectable } from 'inversify';

import { DatabaseClient } from '../shared/libs/database-client/index.js';
import { Config, RestSchema } from '../shared/libs/config/index.js';
import { getMongoUri } from '../shared/helpers/index.js';
import { Logger } from '../shared/libs/logger/index.js';
import { Component } from '../shared/types/index.js';

Expand All @@ -16,20 +15,12 @@ export class RestApplication {
) {}

private async initDb() {
const mongoUri = getMongoUri(
this.config.get('DB_USER'),
this.config.get('DB_PASS'),
this.config.get('DB_HOST'),
this.config.get('DB_PORT'),
this.config.get('DB_NAME')
);

await this.databaseClient.connect(mongoUri);
await this.databaseClient.connect(this.config.mongoUri);
}

public async init() {
this.logger.info('Инициализация приложения');
this.logger.info(`Получить ценность из окружения $PORT: ${this.config.get('PORT')}`);
this.logger.info(`Получить значение $PORT из переменной окружения: ${this.config.get('PORT')}`);

this.logger.info('Инициализировать базу данных…');
await this.initDb();
Expand Down
9 changes: 0 additions & 9 deletions src/shared/helpers/database.ts

This file was deleted.

6 changes: 2 additions & 4 deletions src/shared/helpers/hash.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import * as crypto from 'node:crypto';
import { createHmac } from 'node:crypto';

export const createSHA256 = (line: string, salt: string): string => {
const shaHasher = crypto.createHmac('sha256', salt);

return shaHasher.update(line).digest('hex');
return createHmac('sha256', salt).update(line).digest('hex');
};
1 change: 1 addition & 0 deletions src/shared/libs/config/config.interface.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export interface Config<U> {
get<T extends keyof U>(key: T): U[T];
mongoUri: string;
}
4 changes: 4 additions & 0 deletions src/shared/libs/config/rest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,8 @@ export class RestConfig implements Config<RestSchema> {
public get<T extends keyof RestSchema>(key: T): RestSchema[T] {
return this.config[key];
}

public get mongoUri() {
return `mongodb://${this.get('DB_USER')}:${this.get('DB_PASS')}@${this.get('DB_HOST')}:${this.get('DB_PORT')}/${this.get('DB_NAME')}?authSource=admin`;
}
}
10 changes: 6 additions & 4 deletions src/shared/libs/database-client/mongo.database-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const RETRY_TIMEOUT = 1000;
@injectable()
export class MongoDatabaseClient implements DatabaseClient {
private mongoose: typeof Mongoose;
private isConnectedToDatabase: boolean = false;
private isConnectedToDatabase = false;

constructor(@inject(Component.Logger) private readonly logger: Logger) {}

Expand All @@ -21,7 +21,8 @@ export class MongoDatabaseClient implements DatabaseClient {

public async connect(uri: string): Promise<void> {
if (this.isConnectedToDatabase) {
throw new Error('MongoDB клиент подключен');
this.logger.warn('MongoDB клиент подключен');
return;
}

this.logger.info('Подключение к MongoDB…');
Expand All @@ -45,10 +46,11 @@ export class MongoDatabaseClient implements DatabaseClient {

public async disconnect(): Promise<void> {
if (!this.isConnectedToDatabase) {
throw new Error('Не подключен к базе данных');
this.logger.warn('MongoDB клиент не подключен');
return;
}

await this.mongoose.disconnect?.();
await this.mongoose.disconnect();
this.isConnectedToDatabase = false;
this.logger.info('Соединение с базой данных закрыто');
}
Expand Down
2 changes: 1 addition & 1 deletion src/shared/types/user.type.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export enum UserType {
/** Обычный */
Regular = 'regular',
Regular = 'Regular',

/** Продвинутый */
Pro = 'Pro',
Expand Down

0 comments on commit 84848f4

Please sign in to comment.