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

Приложение для терминала #2

Merged
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
1 change: 1 addition & 0 deletions mocks/mock-data.tsv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Breathtaking Mountain views in cozy Birdbox Enjoy the relaxed and comfortable enclosure of the Birdbox. Sleep right beside nature and its amazing surroundings. 2022-04-06T08:45:40.283Z Dusseldorf preview.jpg photo1.jpg;photo2.jpg;photo3.jpg;photo4.jpg 5 house 2 4 2400 Laptop;friendly;workspace;Baby seat;Washer;Towels;Fridge John [email protected] ava.jpg qwerty pro 48.85661 2.351499
55 changes: 38 additions & 17 deletions package-lock.json

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

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,8 @@
"engines": {
"node": "^20.0.0",
"npm": ">=10"
},
"dependencies": {
"chalk": "^5.3.0"
}
}
41 changes: 41 additions & 0 deletions src/cli/cli-application.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { CommandParser } from './command-parser.js';
import { Command } from './commands/command.interface.js';

type CommandCollection = Record<string, Command>

export class CLIApplication {
private commands: CommandCollection = {};

constructor(
private readonly defaultCommand: string = '--help'
) {}

public registerCommands(commandList: Command[]): void {
commandList.forEach((command) => {
if (Object.hasOwn(this.commands, command.getName())) {
throw new Error(`Command ${command.getName()} is already registered`);
}

this.commands[command.getName()] = command;
});
}

public getCommand(commandName: string): Command {
return this.commands[commandName] ?? this.getDefaultCommand();
}

public getDefaultCommand(): Command | never {
if (! this.commands[this.defaultCommand]) {
throw new Error(`The default command (${this.defaultCommand}) is not registered.`);
}
return this.commands[this.defaultCommand];
}

public processCommand(argv: string[]): void {
const parsedCommand = CommandParser.parse(argv);
const [commandName] = Object.keys(parsedCommand);
const command = this.getCommand(commandName);
const commandArguments = parsedCommand[commandName] ?? [];
command.execute(...commandArguments);
}
}
19 changes: 19 additions & 0 deletions src/cli/command-parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
type ParsedCommand = Record<string, string[]>

export class CommandParser {
static parse(cliArguments: string[]): ParsedCommand {
const parsedCommand: ParsedCommand = {};
let currentCommand = '';

for (const argument of cliArguments) {
if (argument.startsWith('--')) {
parsedCommand[argument] = [];
currentCommand = argument;
} else if (currentCommand && argument) {
parsedCommand[currentCommand].push(argument);
}
}

return parsedCommand;
}
}
4 changes: 4 additions & 0 deletions src/cli/commands/command.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface Command {
getName(): string;
execute(...parameters: string[]): void;
}
21 changes: 21 additions & 0 deletions src/cli/commands/help.command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import chalk from 'chalk';
import { Command } from './command.interface.js';

export class HelpCommand implements Command {
public getName(): string {
return '--help';
}

public async execute(..._parameters: string[]): Promise<void> {
console.info(`
${chalk.yellow('Программа для подготовки данных для REST API сервера.')}
Пример:
cli.js --<command> [--arguments]
Команды:
--version: # выводит номер версии
--help: # печатает этот текст
--import <path>: # импортирует данные из TSV
--generate <n> <path> <url> # генерирует произвольное количество тестовых данных
`);
}
}
26 changes: 26 additions & 0 deletions src/cli/commands/import.command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Command } from './command.interface.js';
import { TSVFileReader } from '../../shared/libs/file-reader/index.js';

export class ImportCommand implements Command {
public getName(): string {
return '--import';
}

public execute(...parameters: string[]): void {
const [filename] = parameters;
const fileReader = new TSVFileReader(filename.trim());

try {
fileReader.read();
console.log(fileReader.toArray());
} catch (err) {

if (!(err instanceof Error)) {
throw err;
}

console.error(`Can't import data from file: ${filename}`);
console.error(`Details: ${err.message}`);
}
}
}
51 changes: 51 additions & 0 deletions src/cli/commands/version.command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';

import { Command } from './command.interface.js';

type PackageJSONConfig = {
version: string;
}

function isPackageJSONConfig(value: unknown): value is PackageJSONConfig {
return (
typeof value === 'object' &&
value !== null &&
!Array.isArray(value) &&
Object.hasOwn(value, 'version')
);
}

export class VersionCommand implements Command {
constructor(
private readonly filePath: string = 'package.json'
) {}

public getName(): string {
return '--version';
}

private readVersion(): string {
const jsonContent = readFileSync(resolve(this.filePath), 'utf-8');
const importedContent: unknown = JSON.parse(jsonContent);

if (! isPackageJSONConfig(importedContent)) {
throw new Error('Failed to parse json content.');
}

return importedContent.version;
}

public async execute(..._parameters: string[]): Promise<void> {
try {
const version = this.readVersion();
console.info(version);
} catch (error: unknown) {
console.error(`Failed to read version from ${this.filePath}`);

if (error instanceof Error) {
console.error(error.message);
}
}
}
}
5 changes: 5 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export { VersionCommand } from './commands/version.command.js';
export { ImportCommand } from './commands/import.command.js';
export { HelpCommand } from './commands/help.command.js';
export { CLIApplication } from './cli-application.js';
export { CommandParser } from './command-parser.js';
15 changes: 15 additions & 0 deletions src/main.cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env node
import { CLIApplication, HelpCommand, ImportCommand, VersionCommand } from './cli/index.js';

function bootstrap() {
const cliApplication = new CLIApplication();
cliApplication.registerCommands([
new HelpCommand(),
new VersionCommand(),
new ImportCommand(),
]);

cliApplication.processCommand(process.argv);
}

bootstrap();
3 changes: 3 additions & 0 deletions src/shared/libs/file-reader/file-reader.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface FileReader {
read(): void;
}
2 changes: 2 additions & 0 deletions src/shared/libs/file-reader/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { FileReader } from './file-reader.interface.js';
export { TSVFileReader } from './tsv-file-reader.js';
92 changes: 92 additions & 0 deletions src/shared/libs/file-reader/tsv-file-reader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { readFileSync } from 'node:fs';

import { FileReader } from './file-reader.interface.js';
import { Offer, User, UserType, PropertyType, Amenities, Coordinates } from '../../types/index.js';

export class TSVFileReader implements FileReader {
private rawData = '';

constructor(
private readonly filename: string
) {}

private validateRawData(): void {
if (! this.rawData) {
throw new Error('File was not read');
}
}

private parseRawDataToOffers(): Offer[] {
return this.rawData
.split('\n')
.filter((row) => row.trim().length > 0)
.map((line) => this.parseLineToOffer(line));
}

private parseLineToOffer(line: string): Offer {
const [
title,
description,
postDate,
city,
preview,
photos,
rating,
type,
roomsCount,
guestsCount,
price,
amenities,
name,
email,
avatarPath,
password,
userType,
latitude,
longitude,
] = line.split('\t');

return {
title,
description,
postDate: new Date(postDate),
city,
preview,
photos: photos.split(';'),
rating: Number.parseInt(rating, 10),
type: type as PropertyType,
roomsCount: Number.parseInt(roomsCount, 10),
guestsCount: Number.parseInt(guestsCount, 10),
price: Number.parseInt(price, 10),
amenities: amenities.split(';') as Amenities[],
author: this.parseUser(name, email, avatarPath, password, userType) as User,
coordinates: this.parseCoordinates(latitude, longitude) as Coordinates,
};
}

private parseUser(
name: string,
email: string,
avatarPath: string,
password: string,
userType: string
): User {
return { name, email, avatarPath, password, type: userType as UserType };
}

private parseCoordinates(latitude: string, longitude: string) {
return {
latitude: Number.parseInt(latitude, 10),
longitude: Number(longitude)
};
}

public read(): void {
this.rawData = readFileSync(this.filename, { encoding: 'utf-8' });
}

public toArray(): Offer[] {
this.validateRawData();
return this.parseRawDataToOffers();
}
}
2 changes: 2 additions & 0 deletions src/shared/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { User, UserType } from './user.type.js';
export { Offer, PropertyType, Amenities, Coordinates } from './offer.type.js';
Loading
Loading