Skip to content

Commit

Permalink
Fix imports
Browse files Browse the repository at this point in the history
  • Loading branch information
Karlen-ll committed Nov 6, 2024
1 parent 34d851c commit a2b77ec
Show file tree
Hide file tree
Showing 82 changed files with 470 additions and 396 deletions.
2 changes: 1 addition & 1 deletion src/cli/cli-application.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { parseArgv } from './utils/parser.js';
import { ConsoleLogger, Logger } from '../shared/libs/logger/index.js';
import { ConsoleLogger, Logger } from '../shared/libs/index.js';
import { Command } from './index.js';

export type CommandInfo = { name: string; description: string; params?: string[] };
Expand Down
2 changes: 1 addition & 1 deletion src/cli/commands/command.interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CommandInfo } from '../../cli/index.js';
import { CommandInfo } from '../index.js';

export interface Command {
/** @example --help */
Expand Down
2 changes: 1 addition & 1 deletion src/cli/commands/help.command.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Command, CommandInfo } from '../../cli/index.js';
import { ConsoleLogger, Logger } from '../../shared/libs/logger/index.js';
import { ConsoleLogger, Logger } from '../../shared/libs/index.js';

export class HelpCommand implements Command {
readonly name = '--help';
Expand Down
4 changes: 2 additions & 2 deletions src/cli/commands/import.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { declination, getFileName } from '../../shared/helpers/index.js';

import { DefaultOfferService, OfferModel, OfferService } from '../../shared/modules/offer/index.js';
import { DefaultUserService, UserModel, UserService } from '../../shared/modules/user/index.js';
import { DatabaseClient, MongoDatabaseClient } from '../../shared/libs/database-client/index.js';
import { ConsoleLogger, Logger } from '../../shared/libs/logger/index.js';
import { DatabaseClient, MongoDatabaseClient } from '../../shared/libs/index.js';
import { ConsoleLogger, Logger } from '../../shared/libs/index.js';
import { TSVOfferFileReader } from '../../shared/libs/index.js';
import { EventName } from '../../constants/index.js';
import { Offer } from '../../shared/types/index.js';
Expand Down
10 changes: 5 additions & 5 deletions src/cli/commands/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export * from './command.interface.js';
export { Command } from './command.interface.js';

export * from './help.command.js';
export * from './version.command.js';
export * from './import.command.js';
export * from './generate.command.js';
export { HelpCommand } from './help.command.js';
export { VersionCommand } from './version.command.js';
export { ImportCommand } from './import.command.js';
export { GenerateCommand } from './generate.command.js';
2 changes: 1 addition & 1 deletion src/cli/commands/version.command.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { readFileSync } from 'node:fs';
import { ConsoleLogger, Logger } from '../../shared/libs/logger/index.js';
import { ConsoleLogger, Logger } from '../../shared/libs/index.js';
import { Command } from '../../cli/index.js';

export class VersionCommand implements Command {
Expand Down
13 changes: 9 additions & 4 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
export * from './cli-application.js';

export * from './utils/index.js';
export * from './commands/index.js';
export { CommandInfo, CliApplication } from './cli-application.js';
export { parseArgv } from './utils/index.js';
export {
Command,
HelpCommand,
ImportCommand,
VersionCommand,
GenerateCommand,
} from './commands/index.js';
2 changes: 1 addition & 1 deletion src/cli/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './parser.js';
export { parseArgv } from './parser.js';
2 changes: 1 addition & 1 deletion src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './common.js';
export * from './city.js';
export { coordinatesCityMap } from './city.js';
2 changes: 1 addition & 1 deletion src/rest/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './rest.application.js';
export { RestApplication } from './rest.application.js';
51 changes: 30 additions & 21 deletions src/rest/rest.application.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { inject, injectable } from 'inversify';
import express, { Express } from 'express';
import { Controller, ExceptionFilter, ParseTokenMiddleware } from '../shared/libs/rest/index.js';
import { DatabaseClient } from '../shared/libs/database-client/index.js';
import { Config, RestSchema } from '../shared/libs/config/index.js';
import { Logger } from '../shared/libs/logger/index.js';

import { Logger } from '../shared/libs/index.js';
import { Component } from '../shared/types/index.js';
import { DatabaseClient } from '../shared/libs/index.js';
import { Config, RestSchema } from '../shared/libs/index.js';
import { Controller, ExceptionFilter, ParseTokenMiddleware } from '../shared/libs/index.js';

@injectable()
export class RestApplication {
Expand All @@ -13,12 +14,18 @@ export class RestApplication {
constructor(
@inject(Component.Logger) private readonly logger: Logger,
@inject(Component.Config) private readonly config: Config<RestSchema>,
@inject(Component.DatabaseClient) private readonly databaseClient: DatabaseClient,
@inject(Component.ExceptionFilter) private readonly appExceptionFilter: ExceptionFilter,
@inject(Component.UserController) private readonly userController: Controller,
@inject(Component.OfferController) private readonly offerController: Controller,
@inject(Component.CommentController) private readonly commentController: Controller,
@inject(Component.AuthExceptionFilter) private readonly authExceptionFilter: ExceptionFilter
@inject(Component.DatabaseClient)
private readonly databaseClient: DatabaseClient,
@inject(Component.ExceptionFilter)
private readonly appExceptionFilter: ExceptionFilter,
@inject(Component.UserController)
private readonly userController: Controller,
@inject(Component.OfferController)
private readonly offerController: Controller,
@inject(Component.CommentController)
private readonly commentController: Controller,
@inject(Component.AuthExceptionFilter)
private readonly authExceptionFilter: ExceptionFilter
) {
this.server = express();
}
Expand All @@ -31,48 +38,50 @@ export class RestApplication {
}

private initServer() {
this.logger.info('Инициализация сервера…');
this.logger.info('Try to init server…');

const port = this.config.get('PORT');
this.server.listen(port);

this.logger.info(`🚀 Сервер запущен: http://localhost:${port}`);
this.logger.info(`🚀 Server started on http://localhost:${port}`);
}

private initControllers() {
this.logger.info('Инициализация контроллеров');
this.logger.info('Init controllers');
this.server.use('/users', this.userController.router);
this.server.use('/offers', this.offerController.router);
this.server.use('/comments', this.commentController.router);
// this.server.use('/category', this.categoryController.router);
this.logger.info('Инициализация контроллеров завершена');
this.logger.info('Controller initialization completed');
}

private initMiddleware() {
this.logger.info('Инициализация middleware-ов');
this.logger.info('Init app-level middleware');

const authenticateMiddleware = new ParseTokenMiddleware(this.config.get('JWT_SECRET'));

this.server.use(express.json());
this.server.use('/upload', express.static(this.config.get('UPLOAD_DIRECTORY')));
this.server.use(authenticateMiddleware.execute.bind(authenticateMiddleware));
this.logger.info('Инициализация middleware-ов завершена');
this.logger.info('App-level middleware initialization completed');
}

private initExceptionFilters() {
this.logger.info('Инициализация фильтров исключений');
this.logger.info('Init exception filters');
this.server.use(this.authExceptionFilter.catch.bind(this.authExceptionFilter));
this.server.use(this.appExceptionFilter.catch.bind(this.appExceptionFilter));
this.logger.info('Инициализация фильтров исключений завершена');
this.logger.info('Exception filters initialization compleated');
}

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

await this.initDb();

this.initMiddleware();

this.initControllers();

this.initExceptionFilters();

this.initServer();
Expand Down
10 changes: 5 additions & 5 deletions src/rest/rest.container.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Container } from 'inversify';
import { DatabaseClient, MongoDatabaseClient } from '../shared/libs/database-client/index.js';
import { AppExceptionFilter, ExceptionFilter } from '../shared/libs/rest/index.js';
import { Config, RestConfig, RestSchema } from '../shared/libs/config/index.js';
import { Logger, PinoLogger } from '../shared/libs/logger/index.js';
import { RestApplication } from './rest.application.js';
import { Component } from '../shared/types/index.js';
import { RestApplication } from './rest.application.js';
import { Logger, PinoLogger } from '../shared/libs/index.js';
import { Config, RestConfig, RestSchema } from '../shared/libs/index.js';
import { DatabaseClient, MongoDatabaseClient } from '../shared/libs/index.js';
import { AppExceptionFilter, ExceptionFilter } from '../shared/libs/index.js';

export function createRestApplicationContainer() {
const restApplicationContainer = new Container();
Expand Down
4 changes: 2 additions & 2 deletions src/shared/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from './common.js';
export * from './file-system.js';
export * from './hash.js';
export { getCurrentModuleDirectoryPath, getFileName } from './file-system.js';
export { createSHA256 } from './hash.js';
6 changes: 3 additions & 3 deletions src/shared/libs/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from './config.interface.js';
export * from './rest.config.js';
export * from './rest.schema.js';
export { Config } from './config.interface.js';
export { RestConfig } from './rest.config.js';
export { RestSchema } from './rest.schema.js';
12 changes: 6 additions & 6 deletions src/shared/libs/config/rest.config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { config } from 'dotenv';
import { inject, injectable } from 'inversify';

import { Logger } from '../logger/index.js';
import { Config } from './config.interface.js';
import { configRestSchema, RestSchema } from './rest.schema.js';
import { inject, injectable } from 'inversify';
import { Component } from '../../types/index.js';
import { Config } from './config.interface.js';
import { Logger } from '../logger/index.js';

@injectable()
export class RestConfig implements Config<RestSchema> {
Expand All @@ -14,14 +13,15 @@ export class RestConfig implements Config<RestSchema> {
const parsedOutput = config();

if (parsedOutput.error) {
throw new Error('Файл «.env» — не найден.');
throw new Error("Can't read .env file. Perhaps the file does not exist.");
}

configRestSchema.load({});
configRestSchema.validate({ allowed: 'strict', output: this.logger.info });

this.config = configRestSchema.getProperties();
this.logger.info('Файл «.env» — успешно проанализирован!');

this.logger.info('.env file was found and successfully parsed!');
}

public get<T extends keyof RestSchema>(key: T): RestSchema[T] {
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 @@ -30,7 +30,7 @@ export const configRestSchema = convict<RestSchema>({
},
DB_HOST: {
doc: 'Host of the database server (MongoDB)',
format: 'ipaddress',
format: String,
env: 'DB_HOST',
default: '127.0.0.1',
},
Expand All @@ -43,8 +43,8 @@ export const configRestSchema = convict<RestSchema>({
DB_PASS: {
doc: 'Password to connect to the database',
format: String,
env: 'DB_PASSWORD',
default: '',
env: 'DB_PASS',
default: null,
},
DB_PORT: {
doc: 'Port to connect to the database',
Expand Down
4 changes: 2 additions & 2 deletions src/shared/libs/database-client/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './database-client.interface.js';
export * from './mongo.database-client.js';
export { DatabaseClient } from './database-client.interface.js';
export { MongoDatabaseClient } from './mongo.database-client.js';
28 changes: 11 additions & 17 deletions src/shared/libs/database-client/mongo.database-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,47 +11,41 @@ const RETRY_TIMEOUT = 1000;
@injectable()
export class MongoDatabaseClient implements DatabaseClient {
private mongoose: typeof Mongoose;
private isConnectedToDatabase = false;
private isConnected = false;

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

public isConnected() {
return this.isConnectedToDatabase;
}

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

this.logger.info('Подключение к MongoDB…');
this.logger.info('Trying to connect to MongoDB…');

let attempt = 0;
while (attempt < RETRY_COUNT) {
try {
this.mongoose = await Mongoose.connect(uri);
this.isConnectedToDatabase = true;
this.logger.info('Соединение с базой данных установлено');
this.isConnected = true;
this.logger.info('Database connection established');
return;
} catch (error) {
attempt++;
this.logger.error(error, `Не удалось подключиться к базе данных (Попытка ${attempt})`);
this.logger.error(`Failed to connect to the database. Attempt ${attempt}`, error as Error);
await setTimeout(RETRY_TIMEOUT);
}
}

throw new Error(`Невозможно установить соединение с базой данных (${RETRY_COUNT} попыток)`);
throw new Error(`Unable to establish database connection after ${RETRY_COUNT} attempts`);
}

public async disconnect(): Promise<void> {
if (!this.isConnectedToDatabase) {
this.logger.warn('MongoDB клиент не подключен');
if (!this.isConnected) {
return;
}

await this.mongoose.disconnect();
this.isConnectedToDatabase = false;
this.logger.info('Соединение с базой данных закрыто');
await this.mongoose.disconnect?.();
this.isConnected = false;
this.logger.info('Database connection closed.');
}
}
4 changes: 2 additions & 2 deletions src/shared/libs/file-reader/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './file-reader.interface.js';
export * from './tsv-offer-file-reader.js';
export { FileReader } from './file-reader.interface.js';
export { TSVOfferFileReader } from './tsv-offer-file-reader.js';
4 changes: 2 additions & 2 deletions src/shared/libs/file-writer/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './file-writer.interface.js';
export * from './tsv-file-writer.js';
export { FileWriter } from './file-writer.interface.js';
export { TSVFileWriter } from './tsv-file-writer.js';
29 changes: 26 additions & 3 deletions src/shared/libs/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,26 @@
export * from './file-reader/index.js';
export * from './file-writer/index.js';
export * from './offer-generator/index.js';
export { DatabaseClient, MongoDatabaseClient } from './database-client/index.js';
export { OfferGenerator, TSVOfferGenerator } from './offer-generator/index.js';
export { FileReader, TSVOfferFileReader } from './file-reader/index.js';
export { ConsoleLogger, Logger, PinoLogger } from './logger/index.js';
export { RestSchema, RestConfig, Config } from './config/index.js';
export { TSVFileWriter, FileWriter } from './file-writer/index.js';

export {
ValidateCityQueryMiddleware,
ValidateObjectIdMiddleware,
DocumentExistsMiddleware,
PrivateRouteMiddleware,
ValidateDtoMiddleware,
UploadFileMiddleware,
ParseTokenMiddleware,
AppExceptionFilter,
ExceptionFilter,
BaseController,
RequestParams,
RequestBody,
Controller,
Middleware,
HttpMethod,
HttpError,
Route,
} from './rest/index.js';
File renamed without changes.
6 changes: 3 additions & 3 deletions src/shared/libs/logger/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from './logger.interface.js';
export * from './console-logger.js';
export * from './pino.logger.js';
export { Logger } from './logger.interface.js';
export { PinoLogger } from './pino.logger.js';
export { ConsoleLogger } from './console.logger.js';
4 changes: 2 additions & 2 deletions src/shared/libs/offer-generator/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './offer-generator.interface.js';
export * from './tsv-offer-generator.js';
export { OfferGenerator } from './offer-generator.interface.js';
export { TSVOfferGenerator } from './tsv-offer-generator.js';
Loading

0 comments on commit a2b77ec

Please sign in to comment.