How can I exit Inquirer prompt based on answer? - javascript

I’m working on an application that sets a series of questions to generate an employee profile. As it is intended to be recursive, the user will be asked at the beginning and the end of the prompt to exit and terminate the enquire.
const employeeQuestions = [
// Role of employee
{
type: 'rawlist',
name: 'role',
message: 'What is the role of the employee?',
choices: [
'Engineer',
'Intern',
new inquirer.Separator(),
'Finish building the team', <=== THIS IS THE ANSWER THAT SHOULD TERMINATE THE PROMPT
],
default: 3,
},
// Employee questions
{
type: 'input',
name: `employee_name`,
message: answer => `Enter name of the ${answer.role}`,
},
{
type: 'number',
name: `employee_id`,
message: answer => `Enter ${answer.role} ID`,
validate(answer) {
const valid = !isNaN(parseFloat(answer));
return valid || 'Please enter a number';
},
filter: Number,
},
{
type: 'input',
name: `employee_email`,
message: answer => `Enter ${answer.role} Email address`,
},
// Engineer questions
{
when(answer) {
return answer.role === 'Engineer';
},
type: 'input',
name: `engineer_github`,
message: 'Enter GitHub username',
},
// Intern questions
{
when(answer) {
return answer.role === 'Intern';
},
type: 'input',
name: `intern_school`,
message: 'Enter intern school',
},
// add more employees
{
type: 'confirm',
name: `add_more`,
message: 'Do you want to add another employee?', <=== THIS IS THE QUESTION THAT SHOULD TERMINATE THE PROMPT
default: true,
},
];
// # Functions
// * Inquires all over if add_more = true
function inquireAgain() {
inquirer.prompt(employeeQuestions).then(answers => {
employeesInfo.push(answers);
if (answers.add_more) {
inquireAgain();
} else {
console.log(JSON.stringify(employeesInfo, null, ' '));
}
});
}
// * Initialize the inquirer prompts
async function init() {
const inquireManager = await inquirer.prompt(managerQuestions);
employeesInfo.push(inquireManager);
inquireAgain();
}
// # Initialisation
init();
this is the closest thing I found related to terminate the prompt, but is not working for me, Thanks in advance.

Related

How do I specify options for commands?

I want to specify choices for an option for my command in Discord.js. How do I do that?
The command:
module.exports = {
name: 'gifsearch',
description: 'Returns a gif based on your search term.',
options: [{
name: 'type',
type: 'STRING',
description: 'Whether to search for gifs or stickers.',
choices: //***this is the area where I have a question***
required: true
},
{
name: 'search_term',
type: 'STRING',
description: 'The search term to use when searching for gifs.',
required: true,
}],
async execute(interaction) {
let searchTerm = interaction.options.getString('search_term')
const res = fetch(`https://api.giphy.com/v1/gifs/search?q=${searchTerm}&api_key=${process.env.giphyAPIkey}&limit=1&rating=g`)
.then((res) => res.json())
.then((json) => {
if (json.data.length <= 0) return interaction.reply({ content: `No gifs found!` })
interaction.reply({content: `${json.data[0].url}`})
})
},
};
I have read the discord.js documentation/guide and I know about the .addChoice() method, but it doesn't look like that will be compatible with my bot's current code.
The discord.js api describes this as ApplicationCommandOptionChoices.
So you basically just insert an array of this in your choices.
module.exports = {
...
choices: [
{
name: "name to display",
value: "the actual value"
},
{
name: "another option",
value: "the other value"
}
]
...
};

Hello everyone! I´am wondering why this bizarre error in the psql terminal

This model allow me to insert new users using Postman
sequelize.define('users', {
id: {
type: S.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
name: {
type: S.STRING,
allowNull: false,
validate: {
notNull: {
msg: 'Name is mandatory'
},
len: {
args: [2, 30],
msg: 'Name field must to be at least 2 characters long.'
},
isAlpha: true
}
},
lastName: {
type: S.STRING,
allowNull: false,
validate: {
notNull: {
msg: 'Lastname is mandatory.'
},
len: {
args: [2, 50],
msg: 'Lastname field must to be at least 2 characters long.'
},
isAlpha: true,
},
}
})
}
This is the express route i design
Another weird thing is that the .findOrCreate function doesn't work neither!
I saw myself forced to divide the system in .findOne and .create functions.
server.post('/', async (req, res)=>{
try {
const { name, lastName } = req.body;
if(!name || !lastName){
res.send('All fields must to be completed')
}
const user = await Users.findOne({
where: {
email: email
}
})
if(user){
return res.send('This user already exists, choose a different one!').status(100);
}
const createUser = await Users.create({
name: name,
lastName: lastName
})
return res.send(createUser)
}
catch (err) {
res.send({ data: err }).status(400);
}
})
The situation is that postman works properly but psql terminal throws the following error when i try to insert data to the model:
insert into users (name, lastName)
values('John', 'Doe', 'jdoe#gmail.com', '12345678', 'wherever');
ERROR: no existe la columna «lastname» en la relación «users»
LÍNEA 1: insert into users (name, lastName)
If you really want to make your life hard with upper case letters in your identifiers, you have to surround them with double quotes whenever you use them in SQL:
"lastName"

Information isn't being passed to an array via Mongoose, can't work out why

Apologies if this has been answered before, I have checked other answers and can't work it out from those.
I have a set of information that I would like placed into an array named "teamDetails". Here is the relevant /post item from server.js:
app.post('/create', (req, res) => {
console.log('Post command received');
console.log(req.body);
console.log(req.body.data.teamDetails[0]);
//We need to push the variable below, 'teamDetails', as an object into an array of the same name
var teamDetailsObj = {
// Modified for Postman
"teamName": req.body.data.teamDetails[0].teamName,
"teamNameShort": req.body.data.teamDetails[0].teamNameShort,
"teamfounded": req.body.data.teamDetails[0].teamFounded,
"teamHome": req.body.data.teamDetails[0].teamHome
};
console.log(teamDetails);
var newTeam = new Team({
"data.added": new Date(),
"data.entry": req.body.data.entry
});
newTeam.save().then((doc) => {
console.log("This is newTeam.data: " + newTeam.data);
console.log("This is teamDetailsObj: " + teamDetailsObj);
newTeam.data.teamDetails.push(teamDetailsObj);
var teamId = doc.id;
res.render('success.hbs', {teamId});
console.log("Team Added - " + teamId);
}, (e) => {
res.status(400).send(e);
});
});
Here is my team.js model:
var mongoose = require('mongoose');
var ObjectID = mongoose.Schema.Types.ObjectId;
var Mixed = mongoose.Schema.Types.Mixed;
var Schema = mongoose.Schema;
var Team = mongoose.model('Team', {
data: {
entry: {
type: String,
default: "USER.INPUT"
},
added: {
type: Date,
default: Date.Now
},
teamDetails: [
{
teamName: {
type: String,
trim: true,
required: true,
default: "First Team"
},
teamNameShort: {
type: String,
trim: true,
uppercase: true,
maxlength: 3,
required: true
},
teamFounded: {
type: Number,
maxlength: 4
},
teamHomeCity: {
type: String
}
}
]
}
});
module.exports = {Team};
Lastly, the sample data I'm trying to inject via Postman:
{
"data": {
"entry": "Postman.Entry",
"teamDetails": [
{
"teamName": "Test Teamname",
"teamNameShort": "TTN",
"teamFounded": "1986",
"teamHome": "London",
"players": [
{
"player1Name": "Test Player 1",
"player1Position": "Forward",
"player1Nationality": "GBR"
},
{
"player2Name": "Test Player 2",
"player2Position": "Defender",
"player2Nationality": "UKR"
},
{
"player3Name": "Test Player 3",
"player3Position": "Goaltender",
"player3Nationality": "IRL",
"captain": true
}
],
"coachingStaff": {
"headCoach": "Derp McHerpson",
"teamManager": "Plarp McFlarplarp"
}
}
]
}
}
(Disregard the players section, it's another kettle of fish)
As a result of using my code above, the resulting entry for teamDetails is just an empty array. I just can't get my code to push the teamDetailsObj into it.
Any help anyone can provide is appreciated.
It looks like you add teamObjDetails AFTER saving it with newTeam.save().then( ... )
I'm not a lot familiar with Mongoose but I don't see how could the team details could be present if not added before saving.
Let me know if it changes something !
A. G

How to prevent the following Vue watch from triggering an infinite loop?

I have an object that looks like this:
visitorInfo: {
name: {
name: 'Name',
value: '',
isInvalid: false,
errors: []
},
email: {
name: 'Email address',
value: '',
validation: {
isRequired: true
},
errors: []
},
phone: {
name: 'Phone number',
value: '',
errors: []
}
},
I'm using watch to add error messages when the value of the fields changes (e.g. when the user is typing in a form):
fields: {
handler (fields) {
Object.entries(fields).forEach(([key, value]) => {
const field = fields[key]
const isRequired = field.validation.isRequired && field.value
if (isRequired) {
field.errors.push({
errorType: 'isRequired',
message: 'This field is required.'
})
}
})
},
deep: true
}
But as you can see there's a problem. This bit
field.errors.push({
errorType: 'isRequired',
message: 'This field is required.'
})
Will trigger an endless lop since it's modifying fields.
How to solve this issue?
Since vue cannot detect if you directly modify an array element, this might help:
field.errors[field.errors.length] = {
errorType: 'isRequired',
message: 'This field is required.'
};
Another option would be to simply check if the error has already been reported:
if (isRequired && !field.errors.length) { ... }
The downside of this is that it will still trigger the watcher an unnecessary 2nd time.
Let me know how it goes.

Returning a value with node inquirer package

I'm attempting to use the node.js inquirer package to run a simple flashcard generator. I'm having trouble getting the syntax to return the checkbox the user clicked. So, once the user makes a choice, I'd like to be able to log the result of that choice. Currently this console.log() returns "undefined".
Any help appreciated!
inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
{
name: "Create a Basic Card"
},
{
name: "Create a Cloze Card"
},
{
name: "Run the flashcards!"
}
]
}
]).then(function(answers){
console.log(answers.typeOfCard[0])
});
const inquirer = require('inquirer');
inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
"Create a Basic Card",
"Create a Cloze Card",
"Run the flashcards!"
]
}
]).then(function(answers){
console.log(answers.typeOfCard);
});
choices should just be an array of strings. You will then be returned an array containing the selected items, ex:
[ 'Create a Cloze Card', 'Run the flashcards!' ]
Hope that helps!
const inquirer = require("inquirer");
console.clear();
const main = async() => {
const readCardChoise = () => {
const read = new Promise((resolve, reject) => {
inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
{
name: "Create a Basic Card"
},
{
name: "Create a Cloze Card"
},
{
name: "Run the flashcards!"
}
],
validate(answer) {
if (answer.length < 1) {
return 'You must choose at least one card.';
}
return true;
},
}])
.then((answers) => {
resolve(answers.typeOfCard);
});
});
return read;
}
const cadSelect = await readCardChoise();
console.log(cadSelect)
}
main();

Categories

Resources