Inquirer.prompt exiting without an answer - javascript

I was wondering if anybody could help me out with an explanation as to why the below code would cause the command line to exit without waiting for an answer from the user.
init();
function init() {
loadPrompts();
}
async function loadPrompts() {
const { choice } = await inquirer.prompt([
{
type: "list",
name: "choice",
message: "What would you like to do?",
choices: [
{
name: "View All Employees",
value: "VIEW_EMPLOYEES",
},
{
name: "View All Employees By Department",
value: "VIEW_EMPLOYEES_BY_DEPARTMENT",
},
{
name: "View All Employees By Manager",
value: "VIEW_EMPLOYEES_BY_MANAGER",
},
{
name: "Add Employee",
value: "ADD_EMPLOYEE",
},
{
name: "Remove Employee",
value: "REMOVE_EMPLOYEE",
},
{
name: "Update Employee Role",
value: "UPDATE_EMPLOYEE_ROLE",
},
{
name: "Update Employee Manager",
value: "UPDATE_EMPLOYEE_MANAGER",
},
{
name: "View All Roles",
value: "VIEW_ROLES",
},
{
name: "Add Role",
value: "ADD_ROLE",
},
{
name: "Remove Role",
value: "REMOVE_ROLE",
},
{
name: "View All Departments",
value: "VIEW_DEPARTMENTS",
},
{
name: "Add Department",
value: "ADD_DEPARTMENT",
},
{
name: "Remove Department",
value: "REMOVE_DEPARTMENT",
},
{
name: "Quit",
value: "QUIT",
},
],
},
]);
switch (choice) {
case "VIEW_EMPLOYEES":
return viewEmployees();
default:
return quit();
}
}
async function viewEmployees() {
const employees = await db.findAllEmployees();
console.table(employees);
loadPrompts();
}
The aim is a simple command-line application that asks the user to select an option - then depending on what they have selected a function will be executed. But what is happening is that the application is running, showing the options then immediately exiting...

You Should use await with loadPrompts() to work synchronously;
(async function init(){
await loadPrompts();
})();

Related

How to calculate Total Amount by Change Status Debit or Credit from array in components in Vue3 JS

I have one Amount column in my table and I want to calculate total debit, total credit, total remaining amount by chnage in status of dropdown debit and credit.
if dropdown selection is debit then "Remaining=Amount-current Amount" and
if dropdown selection is credit then add amount in remaining balance, This Is My Code. Please help I'm new in Vuejs
<script>
import Breadcrumb from "primevue/breadcrumb";
import Button from "primevue/button";
import InputText from "primevue/inputtext";
import Calendar from "primevue/calendar";
import Dropdown from "primevue/dropdown";
import InputNumber from "primevue/inputnumber";
import { ref, reactive } from "vue";
import { computed } from "#vue/reactivity";
export default {
name: "CashPayementVoucher",
components: {
Button,
InputText,
Calendar,
Dropdown,
InputNumber,
Breadcrumb,
},
setup() {
const home = ref({ icon: "pi pi-home", to: "/" });
const items = ref([
{ label: "Vouchers" },
{ label: "Cash Payement Voucher" },
]);
const accountsData = ref([
{ name: "0987-12345678-1", value: "0987-12345678-1" },
{ name: "0987-12345678-2", value: "0987-12345678-2" },
{ name: "0987-12345678-3", value: "0987-12345678-3" },
{ name: "0987-12345678-4", value: "0987-12345678-4" },
{ name: "0987-12345678-5", value: "0987-12345678-5" },
]);
const projectsData = ref([
{ name: "Blue World City", value: "Blue World City" },
{ name: "Estate 92", value: "Estate 92" },
{ name: "Atlantics City", value: "Atlantics City" },
{ name: "Park View City", value: "Park View City" },
{ name: "Bahria Town", value: "Bahria Town" },
]);
const usersData = ref([
{ name: "Ali Suleman", value: "Ali Suleman" },
{ name: "Muhammad Khan", value: "Muhammad Khan" },
{ name: "Sheraz Ahemad", value: "Sheraz Ahemad" },
{ name: "Mehbob Sultan", value: "Mehboob Sultan" },
{ name: "Usama Javeed", value: "Usama javeed" },
{ name: "Shoaib Khan", value: "Shoaib Khang" },
]);
const payementType = ref([
{ name: "Debit", value: 1 },
{ name: "Credit", value: 0 },
]);
const invoice = reactive({
account: "",
date: "",
projects: "",
payeeName: "",
amount: 0,
details: [
{
account: "",
name: "",
description: "",
debit_credit: 1,
amount: 0,
},
],
totalCredit: 0,
totalDebit: 0,
difference: 0,
});
const addnewRow = () => {
invoice.details.push({
account: "",
name: "",
description: "",
debit_credit: "",
amount: 0,
});
};
const removeRow = (index) => {
invoice.details.splice(index, 1);
};
const postData = () => {
console.log("Hello I'm Here 'Cash Payement Voucher'", invoice);
};
const remaining =computed(() => {
return (
invoice.amount +
invoice.details.reduce(function (prevTotal, detail) {
let temp = detail.debit_credit > 0 ? detail.amount * -1 : detail.amount * 1;
return +prevTotal + temp;
}, 0)
);
});
return {
home,
items,
accountsData,
projectsData,
usersData,
payementType,
invoice,
addnewRow,
removeRow,
postData,
remaining
};
},
};
</script>
Image Link
https://i.stack.imgur.com/zkdOZ.png
Please on the next question insert only important code for your problem it's easier to analyze code. To solve your problem create computed property which will return data depending on dropdown choose.
computed() {
calculateValue() {
if (this.details[0].debit_credit === 'Debit') {
return //enter your equation for debit option i can't find currentAmount data
else if (this.details[0].debit_credit === 'Credit') {
return //enter your equation for credit option
}
return null
}
}
}
Then you can display calculateValue anywhere in HTML code:
<template>
<div> Balance: {{calculateValue}} </div>
</template>

SurveyJs with Laravel 8 without Larvel-surveyjs package

I want to create a survey app for my client for this I select surveyjs library to build the app.
I have created all tables like Survey, Questions, Answers, and Options now I want to pass dynamics questions and answers from database like
public function my_survey($slug)
{
$surveys = Survey::where('slug',$slug)->first();
$questions = Question::where('survey_id',$surveys->id)->with('answers')->get();
return view('user.my-survey', compact('surveys','questions'));
}
this will return the array of questions and options saved in database. and
this is Surveyjs script
Survey
.StylesManager
.applyTheme("modern");
var json = {
pages: [
{
questions: [
{
type: "matrix",
name: "Quality",
title: "Please indicate if you agree or disagree with the following statements",
columns: [
{
value: 1,
text: "Strongly Disagree"
}, {
value: 2,
text: "Disagree"
}, {
value: 3,
text: "Neutral"
}, {
value: 4,
text: "Agree"
}, {
value: 5,
text: "Strongly Agree"
}
],
rows: [
{
value: "affordable",
text: "Product is affordable"
}, {
value: "does what it claims",
text: "Product does what it claims"
}, {
value: "better then others",
text: "Product is better than other products on the market"
}, {
value: "easy to use",
text: "Product is easy to use"
}
]
}, {
type: "rating",
name: "satisfaction",
title: "How satisfied are you with the Product?",
isRequired: true,
mininumRateDescription: "Not Satisfied",
maximumRateDescription: "Completely satisfied"
}, {
type: "rating",
name: "recommend friends",
visibleIf: "{satisfaction} > 3",
title: "How likely are you to recommend the Product to a friend or co-worker?",
mininumRateDescription: "Will not recommend",
maximumRateDescription: "I will recommend"
}, {
type: "comment",
name: "suggestions",
title: "What would make you more satisfied with the Product?"
}
]
}, {
questions: [
{
type: "radiogroup",
name: "price to competitors",
title: "Compared to our competitors, do you feel the Product is",
choices: ["Less expensive", "Priced about the same", "More expensive", "Not sure"]
}, {
type: "radiogroup",
name: "price",
title: "Do you feel our current price is merited by our product?",
choices: ["correct|Yes, the price is about right", "low|No, the price is too low for your product", "high|No, the price is too high for your product"]
}, {
type: "multipletext",
name: "pricelimit",
title: "What is the... ",
items: [
{
name: "mostamount",
title: "Most amount you would every pay for a product like ours"
}, {
name: "leastamount",
title: "The least amount you would feel comfortable paying"
}
]
}
]
}, {
questions: [
{
type: "text",
name: "email",
title: "Thank you for taking our survey. Your survey is almost complete, please enter your email address in the box below if you wish to participate in our drawing, then press the 'Submit' button."
}
]
}
]
};
window.survey = new Survey.Model(json);
survey
.onComplete
.add(function (sender) {
document
.querySelector('#surveyResult')
.textContent = "Result JSON:\n" + JSON.stringify(sender.data, null, 3);
});
$("#surveyElement").Survey({model: survey});
I want to pass dynamic questions and options from laravel controller to the above script. please help me how to acheive this
In your my-survey view put questions in JSON format:
#isset($questions)
<script type="text/javascript">
window.questions= {!! $questions !!};
</script>
#endisset
In Surveyjs script put:
const json = window.questions;
window.survey = new Survey.Model(json);

json filter nested array with javascript

I want to pull with javascript: {"subNav0", "subNav1", "subNav2", "subNav3", "subNav4", "subNav5"}.
my json:
var data = {
"menus":{
"GrandparentNav0":{
"name":"TopNav",
"items":[
{
"name":"ParentNav0",
"iconClass":"",
"items":[
{
"name":"ParentNav1",
"iconClass":"",
"items":[
{
"name":"subNav0",
"iconClass":""
},
{
"name":"subNav1",
"iconClass":""
},
{
"name":"subNav2",
"iconClass":""
},
{
"name":"subNav3",
"iconClass":""
},
{
"name":"subNav4",
"iconClass":""
},
{
"name":"subNav5",
"iconClass":""
}
]
},
]
}
]
}
},
};
i know basic filter of an array:
data .forEach(function(o) {
o.variable = o.variable.filter(s => s.value == value);
});
I dont know how to get through menus, GrandparentNav0 to pull the subNav(s)
By "pull the subNav(s)" do you mean like accessing it through something like bracket notation?
let subNavs = data['menus']['GrandparentNav0']['items'][0]['items']
console.log(subNavs)
/* would return
[
{
"name": "subNav0",
"iconClass": ""
},
{
"name": "subNav1",
"iconClass": ""
},
{
"name": "subNav2",
"iconClass": ""
},
{
"name": "subNav3",
"iconClass": ""
},
{
"name": "subNav4",
"iconClass": ""
},
{
"name": "subNav5",
"iconClass": ""
}
]
*/
Here is a solution using object-scan. This might be overkill for your requirements, however as you run into other use cases it's a Swiss army knife that makes these types of data interactions very clean
// const objectScan = require('object-scan');
const data = { menus: { GrandparentNav0: { name: 'TopNav', items: [ { name: 'ParentNav0', iconClass: '', items: [ { name: 'ParentNav1', iconClass: '', items: [ { name: 'subNav0', iconClass: '' }, { name: 'subNav1', iconClass: '' }, { name: 'subNav2', iconClass: '' }, { name: 'subNav3', iconClass: '' }, { name: 'subNav4', iconClass: '' }, { name: 'subNav5', iconClass: '' } ] } ] } ] } } };
const result = objectScan(['menus.GrandparentNav0.items[0].items[0].items[*].name'], { reverse: false, rtn: 'value' })(data);
console.log(result);
// => [ 'subNav0', 'subNav1', 'subNav2', 'subNav3', 'subNav4', 'subNav5' ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#14.0.0"></script>
Disclaimer: I'm the author of object-scan

Ignore error when importing users to Google Suite

I am importing users to Google Suite from a Google sheet using Google Apps Script. I have made "custom attributes" in Google Admin Console, some of them are set to type email. Everything works great except when one user lack those email addresses.
My users are kids, and the emailaddresses are to the kid's parents. One kid might have 1 parent and 1 email. Other kids have 4 parents and 4 emails.
If all variables (epost1, epost2, epost3 and epost4) are filled with email-addresses the user is added. If one of the variables are empty, the script stops with the following message:
GoogleJsonResponseException: API call to directory.users.insert failed
with error: Invalid Input: custom_schema (line 272, file
"nyeMedlemmer")
I tried to put an if-statement in the code, but that was not possible. Is there a way I can tell the script to just ignore those errors?
My code (after the variables are set):
var user = {
primaryEmail: epost,
name: {
givenName: fmnavn,
familyName: etternavn
},
addresses: [
{
type: "home",
formatted: adr
},
{
type: "other",
formatted: adr2
},
{
type: "home",
postalCode: postnr
}
],
phones: [
{
value: mobil,
type: "home"
}
],
emails: [
{
address: epostPriv,
type: "home"
}
],
recoveryEmail: epost1,
locations: [
{
floorName: grad,
type: "desk",
area: "desk"
}
],
gender: {
type: kjonn
},
orgUnitPath: "/Speidere/Stifinnere/"+tropp,
customSchemas: {
Personlig_informasjon: {
skole: skolen,
hensyn: hensynet,
bursdag: dato
},
Innmeldingssvar: {
hjelpe_til: hjelpen,
teste: testen,
merknad: merknaden,
bilde: bildet,
samtykke: samtykket,
innmeldingsdato: innmeldingsdatoen
},
Foresatt: {
foresatt_navn: [
{
value: navn1
},
{
value: navn2,
},
{
value: navn3
},
{
value: navn4
}
],
foresatt_epost: [
{
value: epost1
},
{
value: epost2
},
{
value: epost3
},
{
value: epost4
}
],
foresatt_mob: [
{
value: mobil1
},
{
value: mobil2
},
{
value: mobil3
},
{
value: mobil4
}
]
},//foresatt
},//CustomSchemas
password: passord
}; //var user
user = AdminDirectory.Users.insert(user);
Sometimes all I need is a little break away from the code... I suddenly dawned on my that I could do the if earlier in code:
var epostForesatt = "{value:"+ epost1+"}";
if (epost2 != '') {
var epostForesatt = epostForesatt + ",{value:"+ epost2+"}";
}
if (epost3 != '') {
var epostForesatt = epostForesatt + ",{value:"+ epost3+"}";
}
if (epost4 != '') {
var epostForesatt = epostForesatt + ",{value:"+ epost4+"}";
}
And then later in, down in "var user customSchemas" I edit the code to to use this variable.
Foresatt: {
foresatt_navn: [
{
value: navn1
},
{
value: navn2,
},
{
value: navn3
},
{
value: navn4
}
],
foresatt_epost: [epostForesatt],

Input prompt with options yeoman

I'm new to programming, and I'm creating a generator with yeoman-generator. How do I go through an array of objects and select the option I choose? I tried it but it didn't work. can you help me?
prompting() {
const prompts = [
{
type: 'checkbox',
name: 'database',
message: 'Select Database support:',
choices: [
{
name: 'H2',
value: 'h2',
}, {
name: 'HSQLDB',
value: 'hsqldb'
}, {
name: 'Apache Derby',
value: 'derby'
},
]
return this.prompt(prompts).then(answers => {
this.database = answers.database;
const hasDataBase = db => this.database.indexOf(db) !== -1;
this.h2 = hasDataBase('h2');
this.hsqldb = hasDataBase('hsql');
this.derby = hasDataBase('derby');
});
}
]}
This is the format it can take (from their example page https://yeoman.io/authoring/user-interactions.html). I tested this myself and it works.
var Generator = require('yeoman-generator');
module.exports = class extends Generator {
async prompting() {
const prompts = await this.prompt([
{
type: 'checkbox',
name: 'database',
message: 'Select Database support:',
choices: [
{
name: 'H2',
value: 'h2',
}, {
name: 'HSQLDB',
value: 'hsqldb'
}, {
name: 'Apache Derby',
value: 'derby'
}
]
}]);
this.log("database", prompts.database);
}
};

Categories