Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2 from Nikmas-creator/module1-task3
Учебный проект: консольные забавы
- Loading branch information
Showing
8 changed files
with
211 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
'use strict'; | ||
|
||
module.exports.DEFAULT_COMMAND = `--help`; | ||
|
||
module.exports.USER_ARGV_INDEX = 2; | ||
|
||
module.exports.ExitCode = { | ||
error: 1, | ||
success: 0, | ||
}; | ||
|
||
module.exports.HttpCode = { | ||
OK: 200, | ||
CREATED: 201, | ||
NOT_FOUND: 404, | ||
INTERNAL_SERVER_ERROR: 500, | ||
FORBIDDEN: 403, | ||
UNAUTHORIZED: 401, | ||
BAD_REQUEST: 400, | ||
}; | ||
|
||
module.exports.API_PREFIX = `/api`; | ||
|
||
module.exports.MAX_ID_LENGTH = 6; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
'use strict'; | ||
|
||
const { | ||
getRandomInt, | ||
shuffle, | ||
} = require(`../../utils`); | ||
const fs = require(`fs`); | ||
const chalk = require(`chalk`); | ||
const {ExitCode} = require(`../../constants`); | ||
|
||
const DEFAULT_COUNT = 1; | ||
const FILE_NAME = `mocks.json`; | ||
|
||
const TITLES = [ | ||
`Продам книги Стивена Кинга`, | ||
`Продам новую приставку Sony Playstation 5`, | ||
`Продам отличную подборку фильмов на VHS`, | ||
`Куплю антиквариат`, | ||
`Куплю породистого кота`, | ||
`Продам коллекцию журналов «Огонёк»`, | ||
`Отдам в хорошие руки подшивку «Мурзилка»`, | ||
`Продам советскую посуду. Почти не разбита`, | ||
`Куплю детские санки` | ||
]; | ||
|
||
const SENTENCES = [ | ||
`Товар в отличном состоянии.`, | ||
`Пользовались бережно и только по большим праздникам.`, | ||
`Продаю с болью в сердце...`, | ||
`Бонусом отдам все аксессуары.`, | ||
`Даю недельную гарантию.`, | ||
`Если товар не понравится — верну всё до последней копейки.`, | ||
`Это настоящая находка для коллекционера!`, | ||
`Если найдёте дешевле — сброшу цену.`, | ||
`Таких предложений больше нет!`, | ||
`При покупке с меня бесплатная доставка в черте города.`, | ||
`Кажется, что это хрупкая вещь.`, | ||
`Мой дед не мог её сломать.`, | ||
`Кому нужен этот новый телефон, если тут такое...`, | ||
`Не пытайтесь торговаться.Цену вещам я знаю.` | ||
]; | ||
|
||
const CATEGORIES = [ | ||
`Книги`, | ||
`Разное`, | ||
`Посуда`, | ||
`Игры`, | ||
`Животные`, | ||
`Журналы`, | ||
]; | ||
|
||
const OfferType = { | ||
OFFER: `offer`, | ||
SALE: `sale`, | ||
}; | ||
|
||
|
||
const SumRestrict = { | ||
MIN: 1000, | ||
MAX: 100000, | ||
}; | ||
|
||
const PictureRestrict = { | ||
MIN: 1, | ||
MAX: 16, | ||
}; | ||
|
||
const getPictureFileName = (number) => `item${number.toString().padStart(2, 0)}.jpg`; | ||
|
||
const generateOffers = (count) => ( | ||
Array(count).fill({}).map(() => ({ | ||
category: [CATEGORIES[getRandomInt(0, CATEGORIES.length - 1)]], | ||
description: shuffle(SENTENCES).slice(1, 5).join(` `), | ||
picture: getPictureFileName(getRandomInt(PictureRestrict.MIN, PictureRestrict.MAX)), | ||
title: TITLES[getRandomInt(0, TITLES.length - 1)], | ||
type: Object.keys(OfferType)[Math.floor(Math.random() * Object.keys(OfferType).length)], | ||
sum: getRandomInt(SumRestrict.MIN, SumRestrict.MAX), | ||
})) | ||
); | ||
|
||
module.exports = { | ||
name: `--generate`, | ||
run(args) { | ||
const [count] = args; | ||
let countOffer = Number.parseInt(count, 10) || DEFAULT_COUNT; | ||
|
||
if (countOffer < 1) { | ||
countOffer = DEFAULT_COUNT; | ||
} else if (countOffer > 1000) { | ||
console.error(chalk.red(`Не больше 1000 объявлений`)); | ||
process.exit(ExitCode.error); | ||
} | ||
const content = JSON.stringify(generateOffers(countOffer)); | ||
|
||
fs.writeFile(FILE_NAME, content, (err) => { | ||
if (err) { | ||
console.error(chalk.red(`Can't write data to file...`)); | ||
process.exit(ExitCode.error); | ||
} | ||
|
||
console.info(`Operation success. File created.`); | ||
process.exit(ExitCode.success); | ||
}); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
'use strict'; | ||
|
||
const chalk = require(`chalk`); | ||
|
||
module.exports = { | ||
name: `--help`, | ||
run() { | ||
const text = ` | ||
Программа запускает http-сервер и формирует файл с данными для API. | ||
Гайд: | ||
service.js <command> | ||
Команды: | ||
--version: выводит номер версии | ||
--help: печатает этот текст | ||
--generate <count> формирует файл mocks.json | ||
`; | ||
|
||
console.log(chalk.grey(text)); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
'use strict'; | ||
|
||
const help = require(`./help`); | ||
const generate = require(`./generate`); | ||
const version = require(`./version`); | ||
|
||
const Cli = { | ||
[generate.name]: generate, | ||
[help.name]: help, | ||
[version.name]: version | ||
}; | ||
|
||
module.exports = { | ||
Cli, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
'use strict'; | ||
|
||
const chalk = require(`chalk`); | ||
const packageJsonFile = require(`../../../package.json`); | ||
|
||
module.exports = { | ||
name: `--version`, | ||
run() { | ||
const version = packageJsonFile.version; | ||
console.log(chalk.blue(version)); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,18 @@ | ||
'use strict'; | ||
|
||
console.log(`Hello, world!`); | ||
const {Cli} = require(`./cli`); | ||
const { | ||
DEFAULT_COMMAND, | ||
USER_ARGV_INDEX, | ||
ExitCode | ||
} = require(`../constants`); | ||
|
||
const userArguments = process.argv.slice(USER_ARGV_INDEX); | ||
const [userCommand] = userArguments; | ||
|
||
if (userArguments.length === 0 || !Cli[userCommand]) { | ||
Cli[DEFAULT_COMMAND].run(); | ||
process.exit(ExitCode.success); | ||
} | ||
|
||
Cli[userCommand].run(userArguments.slice(1)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
'use strict'; | ||
|
||
module.exports.getRandomInt = (min, max) => { | ||
min = Math.ceil(min); | ||
max = Math.floor(max); | ||
return Math.floor(Math.random() * (max - min + 1)) + min; | ||
}; | ||
|
||
module.exports.shuffle = (someArray) => { | ||
for (let i = someArray.length - 1; i > 0; i--) { | ||
const randomPosition = Math.floor(Math.random() * i); | ||
[someArray[i], someArray[randomPosition]] = [someArray[randomPosition], someArray[i]]; | ||
} | ||
|
||
return someArray; | ||
}; |