Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Глаза дракона #9

Merged
merged 5 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"@typegoose/typegoose": "^12.4.0",
"chalk": "^5.3.0",
"class-transformer": "0.5.1",
"class-validator": "0.14.1",
"convict": "6.2.4",
"convict-format-with-validator": "6.2.0",
"dayjs": "^1.11.10",
Expand Down
2 changes: 2 additions & 0 deletions src/cli/cli.constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const DEFAULT_USER_LOGIN = '[email protected]';
export const DEFAULT_USER_PASSWORD = '123456';
49 changes: 11 additions & 38 deletions src/cli/commands/import.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ import { Logger } from '../../shared/libs/logger/index.js';
import { ConsoleLogger } from '../../shared/libs/logger/console.logger.js';
import { DefaultUserService } from '../../shared/modules/user/default-user.service.js';
import { OfferModel, UserModel } from '../../shared/entities/index.js';

const DEFAULT_USER_PASSWORD = '123456';
// TODO: Доставать из .env переменных
const DEFAULT_DB_PORT = '27017';
import { IRestSchema } from '../../shared/libs/config/rest.schema.interface.js';
import { Config, RestConfig } from '../../shared/libs/config/index.js';
import { DEFAULT_USER_LOGIN, DEFAULT_USER_PASSWORD } from '../cli.constants.js';

export class ImportCommand implements Command {

private userService!: UserService;
private offerService!: OfferService;
private databaseClient!: DatabaseClient;
private config!: Config<IRestSchema>;
private logger!: Logger;
private salt!: string;

Expand All @@ -27,6 +27,7 @@ export class ImportCommand implements Command {
this.onCompleteImport = this.onCompleteImport.bind(this);

this.logger = new ConsoleLogger();
this.config = new RestConfig(this.logger);
this.userService = new DefaultUserService(this.logger, UserModel);
this.offerService = new DefaultOfferService(this.logger, OfferModel);
this.databaseClient = new MongoDatabaseClient(this.logger);
Expand All @@ -48,42 +49,34 @@ export class ImportCommand implements Command {

private async saveOffer(offer: Offer) {
const user = await this.userService.findOrCreate({
...offer.author, // offer.user
email: '[email protected]',
...offer.author,
email: DEFAULT_USER_LOGIN,
password: DEFAULT_USER_PASSWORD
}, this.salt);

// for (const { name } of offer.categories) {
// const existCategory = await this.categoryService.findByCategoryNameOrCreate(name, { name });
// categories.push(existCategory.id);
// }

await this.offerService.create({
title: offer.title,
description: offer.description,
city: offer.city,
previewImg: offer.previewImg,
images: offer.images,
// isPremium: offer.isPremium,
// rating: offer.rating,
isPremium: offer.isPremium,
type: offer.type,
flatCount: offer.flatCount,
guestCount: offer.guestCount,
cost: offer.cost,
conveniences: offer.conveniences,
coordinate: offer.coordinate,

publicationDate: offer.publicationDate,
author: user.id, // userId
author: user.id,
commentCount: offer.commentCount || 0,
});

}

// TODO: В --help команду нужно добавить аргументы, которые передаем
public async execute(filename: string, login: string, password: string, host: string, dbname: string): Promise<void> { // salt: string
const uri = getMongoURI(login, password, host, DEFAULT_DB_PORT, dbname);
// this.salt = salt;
public async execute(filename: string, login: string, password: string, host: string, dbname: string): Promise<void> {
const uri = getMongoURI(login, password, host, this.config.get('DB_PORT'), dbname);

await this.databaseClient.connect(uri);

Expand All @@ -100,23 +93,3 @@ export class ImportCommand implements Command {
}
}


// public async execute(...parameters: string[]): Promise<void> {
// const [filename] = parameters;

// let fileReader;
// if (filename) {
// fileReader = new TSVFileReader(filename.trim());

// fileReader.on('line', this.onImportedOffer);
// fileReader.on('end', this.onCompleteImport);
// }

// try {
// fileReader?.read();
// } catch (err) {
// console.error(chalk.red(`Can't import data from file: ${filename}`));
// console.error(getErrorMessage(err));
// }
// }
// }
8 changes: 4 additions & 4 deletions src/mocks/mock-server-data.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
"isPremuimArr": [true, false],
"ratings": [1, 2, 3, 4, 5],
"types": [
"Apartment",
"House",
"Room",
"Hotel"
"apartment",
"house",
"room",
"hotel"
],
"flatCounts": [1, 2, 3, 4, 5, 6],
"guestCounts": [1, 2, 3, 4, 5, 6, 7, 8],
Expand Down
4 changes: 3 additions & 1 deletion src/rest/rest.application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export class RestApplication {
@inject(COMPONENT.OFFER_CONTROLLER) private readonly offerController: Controller,
@inject(COMPONENT.EXCEPTION_FILTER) private readonly appExceptionFilter: ExceptionFilter,
@inject(COMPONENT.USER_CONTROLLER) private readonly userController: Controller,
@inject(COMPONENT.COMMENT_CONTROLLER) private readonly commentController: Controller,
) {}

private async initDb() {
Expand All @@ -41,6 +42,7 @@ export class RestApplication {
private async initControllers() {
this.server.use('/offers', this.offerController.router);
this.server.use('/users', this.userController.router);
this.server.use('/comments', this.commentController.router);
}

private async initMiddleware() {
Expand Down Expand Up @@ -72,7 +74,7 @@ export class RestApplication {

this.logger.info('Try to init server…');
await this.initServer();
// TODO: Нужно найти как правильно брать протокол

this.logger.info(
`Server started on http://${this.config.get('DB_HOST')}:${this.config.get('PORT')}`
);
Expand Down
1 change: 1 addition & 0 deletions src/shared/constants/component.constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ export const COMPONENT = {
OFFER_CONTROLLER: Symbol.for('kOfferController'),
EXCEPTION_FILTER: Symbol.for('kExceptionFilter'),
USER_CONTROLLER: Symbol.for('kUserController'),
COMMENT_CONTROLLER: Symbol.for('kCommentController'),
} as const;
10 changes: 6 additions & 4 deletions src/shared/entities/comment.entity.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {
defaultClasses,
getModelForClass,
modelOptions,
prop,
Ref
} from '@typegoose/typegoose';
import { OfferEntity, UserEntity } from './index.js';
import { OfferEntity } from './offer.entity.js';
import { UserEntity } from './user.entity.js';

// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export interface CommentEntity extends defaultClasses.Base {}
Expand Down Expand Up @@ -35,6 +35,8 @@ export class CommentEntity extends defaultClasses.TimeStamps {
required: true,
})
public author!: Ref<UserEntity>;
}

export const CommentModel = getModelForClass(CommentEntity);
public get id() {
return this._id.toString();
}
}
13 changes: 10 additions & 3 deletions src/shared/entities/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
export { UserEntity, UserModel } from './user.entity.js';
export { OfferEntity, OfferModel } from './offer.entity.js';
export { CommentEntity, CommentModel } from './comment.entity.js';
import { getModelForClass } from '@typegoose/typegoose';
import { OfferEntity } from './offer.entity.js';
import { UserEntity } from './user.entity.js';
import { CommentEntity } from './comment.entity.js';

export const OfferModel = getModelForClass(OfferEntity);
export const UserModel = getModelForClass(UserEntity);
export const CommentModel = getModelForClass(CommentEntity);

export { OfferEntity, UserEntity, CommentEntity };
18 changes: 4 additions & 14 deletions src/shared/entities/offer.entity.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
import {
defaultClasses,
getModelForClass,
modelOptions,
prop,
Ref
} from '@typegoose/typegoose';
import { City, ConvenienceType, Coordinate, OfferType } from '../types/index.js';
import { UserEntity } from './user.entity.js';

// import { UserEntity } from '../user/index.js';

// import { City, ConvenienceType, Coordinate, OfferType } from '../../types/index.js';

// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export interface OfferEntity extends defaultClasses.Base {}

Expand All @@ -29,9 +24,6 @@ export class OfferEntity extends defaultClasses.TimeStamps {
@prop({ trim: true, required: true })
public description!: string;

// @prop()
// public publicationDate!: Date;

@prop({ type: () => String, enum: City, required: true })
public city!: City;

Expand All @@ -41,10 +33,10 @@ export class OfferEntity extends defaultClasses.TimeStamps {
@prop({ type: () => [String], required: true })
public images!: string[];

@prop() // { required: true }
@prop({ default: false })
public isPremium!: boolean;

@prop() // { required: true }
@prop()
public rating!: number;

@prop({
Expand All @@ -63,20 +55,18 @@ export class OfferEntity extends defaultClasses.TimeStamps {
@prop({ required: true })
public cost!: number;

@prop({ type: [String], required: true })
@prop({ type: () => [String], required: true })
public conveniences!: ConvenienceType[];

@prop({
ref: () => UserEntity,
required: true
})
public author!: Ref<UserEntity>; // userId
public author!: Ref<UserEntity>;

@prop({default: 0})
public commentCount!: number;

@prop({ required: true })
public coordinate!: Coordinate;
}

export const OfferModel = getModelForClass(OfferEntity);
Loading
Loading