Skip to content

Commit b46d1c8

Browse files
committed
bonus-task-working
1 parent 8a0bb0f commit b46d1c8

File tree

4 files changed

+122
-88
lines changed

4 files changed

+122
-88
lines changed

package-lock.json

Lines changed: 16 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
"@faker-js/faker": "^7.6.0"
1919
},
2020
"dependencies": {
21-
"chalk": "^5.2.0"
21+
"chalk": "^5.2.0",
22+
"moment": "^2.29.4",
23+
"sane-email-validation": "^3.0.1"
2224
}
2325
}

src/task-bonus.js

Lines changed: 53 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,86 @@
1-
import { generateRandomUserDataString as newEntry } from "./generateRandomUserDataString.js";
21
import c from "chalk";
32
import { writeFile, mkdir, readFile } from "node:fs/promises";
43
import readline from "node:readline/promises";
4+
import { validate } from "./validations.js";
5+
56
const fileName = "registration.json";
67
const dirPath = new URL("./../database/task-bonus", import.meta.url).pathname;
7-
8-
let rl = readline.createInterface({ input: process.stdin, output: process.stdout });
8+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
9+
/// close program by clearing console on ctrl+c
910
rl.on("SIGINT", closeProgram); //doesn't work on process.on('SIGINT') SIGINT is emitted on ctrl+c press
1011

11-
async function mainFunc() {
12-
console.log(c.dim("Exit: Ctrl + C"));
13-
console.log(c.yellow.bold("Enter your details: "));
14-
let details = await getUserDetails();
15-
let currentData = JSON.parse(await readFileData());
16-
console.log(typeof currentData, currentData);
17-
currentData.push(details);
18-
console.log(currentData);
19-
await writeDataToFile(JSON.stringify(currentData));
20-
closeProgram(c.green("Duomenys faile sėkmingai išsaugoti"));
21-
}
12+
/// Intro messages
13+
printIntro();
14+
15+
/// Get registration inputs
16+
let details = await getUserDetails();
17+
18+
/// Read adn parse current file data
19+
let currentData = JSON.parse(await readFileData());
20+
21+
/// Append new data to array
22+
currentData.push(details);
23+
24+
/// Save new updated array to file as json
25+
await writeDataToFile(JSON.stringify(currentData));
26+
27+
/// Log Success message
28+
closeProgram(c.green("Duomenys faile sėkmingai išsaugoti"));
2229

2330
async function getUserDetails() {
2431
let userDetails = {
25-
name: await getValidInput.name(),
26-
lastName: await getValidInput.lastName(),
27-
password: await getValidInput.password(),
28-
email: await getValidInput.email(),
29-
birthday: await getValidInput.birthday(),
32+
name: await getValidInput("Your name: ", [validate.isMaxLength(50)]),
33+
lastName: await getValidInput("Your last name ", [validate.isMaxLength(50)]),
34+
password: await getValidInput("Your password: ", [validate.isMinLength(9), validate.isMaxLength(50)]),
35+
email: await getValidInput("Your email address: ", [validate.isValidEmail]),
36+
birthday: await getValidInput("Your birthday YYYY-MM-DD: ", [validate.isValidBirthdayFormat]),
3037
};
3138
return userDetails;
3239
}
3340

34-
const getValidInput = {
35-
name: async function () {
36-
let name = "";
37-
let errorMsg = "";
38-
while (!name) {
39-
if (errorMsg) console.log(c.red(errorMsg));
40-
name = (await rl.question(c.bgBlue.bold("Your name:") + " ")).trim();
41-
if (!name) {
42-
errorMsg = "Name can't be empty";
43-
}
44-
}
45-
return name;
46-
},
47-
lastName: async function () {
48-
let lastName = "";
49-
let errorMsg = "";
50-
while (!lastName) {
51-
if (errorMsg) console.log(c.red(errorMsg));
52-
lastName = (await rl.question(c.bgBlue.bold("Your last name:") + " ")).trim();
53-
if (!lastName) {
54-
errorMsg = "Last name can't be empty";
55-
}
41+
async function getValidInput(questionStr, validateArr = []) {
42+
validateArr = [validate.isNotEmpty, ...validateArr]; //add default check for empty values
43+
let input = "";
44+
let errorMsg = "";
45+
while (!input) {
46+
if (errorMsg) console.log(c.red(errorMsg));
47+
let rawInput = (await rl.question(c.bgBlue.bold(questionStr))).trim();
48+
try {
49+
validateArr.forEach((validateFunc) => {
50+
input = "";
51+
input = validateFunc(rawInput);
52+
});
53+
} catch (validationError) {
54+
errorMsg = validationError.message;
5655
}
57-
return lastName;
58-
},
59-
password: async function () {
60-
let password = "";
61-
let errorMsg = "";
62-
while (!password) {
63-
if (errorMsg) console.log(c.red(errorMsg));
64-
password = (await rl.question(c.bgBlue.bold("Your password:") + " ")).trim();
65-
if (!password) {
66-
errorMsg = "Password can't be empty";
67-
}
68-
}
69-
return password;
70-
},
71-
email: async function () {
72-
let email = "";
73-
let errorMsg = "";
74-
while (!email) {
75-
if (errorMsg) console.log(c.red(errorMsg));
76-
email = (await rl.question(c.bgBlue.bold("Your email address:") + " ")).trim();
77-
if (!email) {
78-
errorMsg = "Email can't be empty";
79-
}
80-
}
81-
return email;
82-
},
83-
birthday: async function () {
84-
let birthday = "";
85-
let errorMsg = "";
86-
while (!birthday) {
87-
if (errorMsg) console.log(c.red(errorMsg));
88-
birthday = (await rl.question(c.bgBlue.bold("Your birthday:") + " ")).trim();
89-
if (!birthday) {
90-
errorMsg = "Birthday can't be empty";
91-
}
92-
}
93-
return birthday;
94-
},
95-
};
96-
mainFunc();
56+
}
57+
return input;
58+
}
9759

9860
async function writeDataToFile(data) {
9961
try {
10062
await mkdir(dirPath, { recursive: true });
101-
await writeFile(`${dirPath}/${fileName}`, data); ///kelias ne nuo sito failo, bet nuo project rooto??...
102-
// console.log(c.green("Duomenys faile sėkmingai išsaugoti"));
63+
await writeFile(`${dirPath}/${fileName}`, data);
10364
} catch (err) {
104-
console.error(err);
65+
console.error(c.red(err.message));
10566
}
10667
}
10768

10869
async function readFileData() {
10970
try {
110-
// await mkdir(dirPath, { recursive: true });
11171
return await readFile(`${dirPath}/${fileName}`);
11272
} catch (err) {
113-
console.log("chould add empty");
11473
return "[]"; //if file empty or not created
11574
}
11675
}
76+
77+
function printIntro() {
78+
console.clear();
79+
console.log(c.yellow.bold(` REGISTRATION`));
80+
console.log(c.dim("Exit: Ctrl + C"));
81+
console.log(c.yellow.bold("Enter your details: "));
82+
}
83+
11784
function closeProgram(msg = "") {
11885
// console.clear(); //to clear password and read history from logs. doesn't clear all console, only visible area
11986
// https://stackoverflow.com/questions/8813142/clear-terminal-window-in-node-js-readline-shell

src/validations.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { isNotEmail } from "sane-email-validation";
2+
import moment from "moment";
3+
export const validate = {
4+
isNotEmpty: function (value) {
5+
if (!value) {
6+
throw new Error("Can't be empty");
7+
}
8+
return value;
9+
},
10+
isValidEmail: function (value) {
11+
if (isNotEmail(value)) {
12+
throw new Error("Provide valid email address");
13+
}
14+
return value;
15+
},
16+
isValidBirthdayFormat: function (value) {
17+
if (!moment(value, "YYYY-MM-DD", true).isValid()) {
18+
throw new Error("Use YYYY-MM-DD format and provide real date");
19+
}
20+
let yearNow = new Date().getFullYear();
21+
let inputYear = new Date(value).getFullYear();
22+
let age = yearNow - inputYear;
23+
if (age < 0) {
24+
throw new Error("Your birthday can't be in a future");
25+
}
26+
if (age > 150) {
27+
throw new Error(`Congratulation for reaching ${age} years age, but this application was not designed for that yet. Please contact us personally.`);
28+
}
29+
if (age < 13) {
30+
throw new Error("You must be at least 13 years old to register");
31+
}
32+
return value;
33+
},
34+
isMaxLength: function (len) {
35+
return function (value) {
36+
if (value.length > len) {
37+
throw new Error(`Max ${len} characters`);
38+
}
39+
return value;
40+
};
41+
},
42+
isMinLength: function (len) {
43+
return function (value) {
44+
if (value.length < len) {
45+
throw new Error(`Min ${len} characters`);
46+
}
47+
return value;
48+
};
49+
},
50+
};

0 commit comments

Comments
 (0)