Skip to content

init: set up new branch with refactor to typescript - #2

Open
Acksakal wants to merge 1 commit into
file-managerfrom
file-manager-ts
Open

init: set up new branch with refactor to typescript#2
Acksakal wants to merge 1 commit into
file-managerfrom
file-manager-ts

Conversation

@Acksakal

Copy link
Copy Markdown
Owner

No description provided.

Comment thread .gitignore
test.js
test.txt No newline at end of file
test.txt
node_modules No newline at end of file

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
node_modules
node_modules/

Comment thread src/handleCommand.ts
await fn(args);
} catch (cause) {
} catch (error) {
// @ts-ignore

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чтобы тут избежать ts-ignore тебе нужно внятно описать тип твоего сервиса. Помимо Promise он так же должен возвращать Error(), который ты обрабатываешь внутри своих команд. Как следствие - try catch на этом уровне будет резолвить error как Error

root: string;
}

export const getTruePath = async (inputPath: string): Promise<string> => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В чем смысл этой функции и чем это отличается от той, что ты назвал стором?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Смысл в том, чтобы отображать путь к файлам в оригинальном регистре.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

store.currentDir даёт доступ всем службам к текущему пути каким бы он ни был в настоящий момент времени.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

т.e. это повторяет функционал того, что ты используешь для получения полного пути к файлу в mkdir, например?

@dmitry-blackwave dmitry-blackwave May 15, 2025

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я это к чему - стремись создавать меньше дубликатов. Если ты видишь, что функционал схож - создавай common функцию, которая будет отвечать за правильный путь до файла, например. Тогда это будет один источник правда и в случае внесения изменений ты отредактируешь только его

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

т.e. это повторяет функционал того, что ты используешь для получения полного пути к файлу в mkdir, например?

Не, это другое. Но я суть уловил.

Comment thread src/helpers/messages.ts

export const logGoodbyeMsg = (username) => {
export const logGoodbyeMsg = (username: string) => {
console.log('\r' + MESSAGE_GOODBYE, getColorizedMsg({ msg: username }) + ', goodbye!');

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Проще реализовать свой логгер, который под капотом будет делать что нужно с getColorizedMsg.

Типа:
Logger.error(), Logger.warn(), которые будут принимать текст и сами вызывать getColorizedMsg с нужными параметрами. Тогда ты сможешь свой логгер по всему проекту использовать как общее решение

Comment thread src/types/Service.type.ts
@@ -0,0 +1,7 @@
export type ServiceArgs = string[];

export type ServiceCommand<T extends ServiceArgs = ServiceArgs> = (args: T) => Promise<void>;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот этот тип должен быть не только Promise, но и Promise какой-нибудь, чтобы грамотно обрабатывать ошибки

Comment thread src/handleCommand.ts
*/
export async function handleCommand(inputString) {
export async function handleCommand(inputString: string) {
const inputTokens = inputString.split(/\s+/);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно сделать нормально и забыть про анонимные массивы. Ты можешь заюзать что-нибудь из серии https://www.npmjs.com/package/minimist или https://www.npmjs.com/package/yargs, которые позволять тебе грамотно парсить команду и аргументы. Далее, это все в типы можно обернуть и вместо arg[0] в mkdir ты будешь использовать dirName

Comment thread src/handleCommand.ts

const fn = services[command.toLowerCase()];

if (typeof fn !== 'function') {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот эта проверка немного лишена смысла, потому что ты уже попытался присвоить fn какой-то объект не зная есть ли он там на самом деле.

Я бы делал что-то типа:

if (!Object.keys(services).includes(command) || !services[command]) {
    return logInvalidInputErr();
}

const fn = services[command.toLowerCase()];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants