Yeoman repeat prompt based on user input - generator

For example, I want to ask the user for the type of bread:
{
type: 'list',
name: 'breadType',
message: `What type of bread do you want?`,
choices: response => {
const breadOptions = [
{
value: 'wheat',
name: 'Wheat Bread'
},
{
value: 'white',
name: 'White Bread'
}
];
return breadOptions;
},
default: 0
}
Then I'll ask for toppings based on the number of toppings they want:
{
when: response => response.breadType,
type: 'input',
name: 'numberOfToppings',
message: 'Please enter how many toppings you want: '
}
How would I prompt however many times user input for number of toppings?:
{
when: response => response.numberOfToppings,
type: 'input',
name: 'toppingChoices',
message: 'Please provide your topping(s): '
}
SAMPLE INPUT:
? Please enter how many toppings you want: 4
? Please provide your topping(s):cheese
? Please provide your topping(s):onions
? Please provide your topping(s):pickles
? Please provide your topping(s):tomatoes
I'm unfamiliar with yeoman syntax, please help.

I made a simple generator that solve your problem:
const Generator = require('yeoman-generator');
let toppings = [];
module.exports = class extends Generator {
async prompting() {
const answers = await this.prompt([
{
type: 'input',
name: 'numberOfToppings',
message: 'Please enter how many toppings you want: ',
}
]);
var length = answers.numberOfToppings;
for(var i = 0; i < length; i++) {
const answers2 = await this.prompt([
{
type: 'input',
name: 'toppings',
message: 'Please provide your topping(s):',
}
]);
toppings.push(answers2.toppings);
}
console.log('Array: ' + toppings);
}
};

Related

Is there a way to successfully loop an Angular service call

How can I successfully run the following code?
onSubmit() {
let pdfData = [
{
field_name: 'data.Date',
value: this.freshDeskData.date,
placeholder: '',
page_no: 1,
},
{
field_name: 'data.Fullname',
value: "Bob Jones",
placeholder: '',
page_no: 1,
},
];
for(let i=0;i<pdfData.length;i++){
this.signHub.addPDFInfo(pdfData[i]).subscribe((data) => {
this.responseData = data[i]
});
}
}
Add PDF Service:
addPDFInfo(pdfInfo): Observable<PDFInfo> {
return this.http.put<PDFInfo>(
`${environment.apiUrl}/api/workflow/add-text-block?package_ID=${this.package_ID.data.package_id}&current_Document_ID=${this.current_Document_ID.data.documentid}`,
pdfInfo
);
}
The service is meant to loop through the JSON object and POST the information on the selected item to populate the related field on a PDF document. However, only one field is populated via the loop. The other remains empty.
You could achieve this by using the RxJs merge-operator, eg.:
onSubmit() {
let pdfData = [
{
field_name: 'data.Date',
value: this.freshDeskData.date,
placeholder: '',
page_no: 1,
},
{
field_name: 'data.Fullname',
value: "Bob Jones",
placeholder: '',
page_no: 1,
},
];
const requests = [];
for(let i=0;i<pdfData.length;i++){
requests.push(this.signHub.addPDFInfo(pdfData[i]));
}
merge(...requests).subscribe((data) => {
this.responseData = data[i]
})
}
granted you'd need to combine the results of each "next result" (that you're currently assigning to this.responseData). A candidate to solve that issue could be the reduce-operator
But, it's difficult to give a precise answer, without having knowledge about more of your codebase.

Getting only value of custom fields in Google Suite User list

I have made Custom Fields in my Users in Google Suite.
Category: Foresatt
Among them:
Name: 'foresatt epost', type:email, number: multiple values
I would like to list these values using Google Script. I used this:
https://developers.google.com/admin-sdk/directory/v1/quickstart/apps-script
To write this code:
function listUsers() {
var optionalArgs = {
customer: 'my_customer',
maxResults: 10,
orderBy: 'email',
projection: 'custom',
customFieldMask:'Foresatt'
};
var response = AdminDirectory.Users.list(optionalArgs);
var users = response.users;
if (users && users.length > 0) {
Logger.log('Users:');
for (i = 0; i < users.length; i++) {
var user = users[i];
var foresatt = user.customSchemas;
Logger.log('%s (%s)', user.primaryEmail, user.name.fullName, foresatt);
}
} else {
Logger.log('No users found.');
}
}
That works, but I would like to get only the values. What I get now:
{Foresatt={
foresatt_mob=[{value=X#X#X#X#, type=work}, {type=work, value=X#X#X#X#}, {type=work, value=X#X#X#X#}],
foresatt_epost=[{value=xx#xx.no, type=work}, {type=work, value=xy#xx.no}, {value=yy#xx.no, type=work}],
foresatt_navn=[{type=work, value=Xx}, {value=Xy, type=work}, {type=work, value=Yy}]
}
}
What I would like to get: xx#xx.no, xy#xx.no, yy#xx.no
I have tried several things, but I'm afraid I'm not experienced enough.
var epost = foresatt.foresatt_epost;
Results in: TypeError: Cannot read property 'foresatt_epost'
var epost = foresatt('foresatt_epost');
Results in: TypeError: foresatt is not a function
Please advise me, how do I get only the values fram the field 'foresatt epost'?
I believe your goal as follows.
You want to retrieve the values of xx#xx.no, xy#xx.no, yy#xx.no from the following object:
const object = {
Foresatt: {
foresatt_mob: [
{ value: "X#X#X#X#",type: "work"},
{ value: "X#X#X#X#",type: "work"},
{ value: "X#X#X#X#",type: "work"},
],
foresatt_epost: [
{ value: "xx#xx.no", type: "work"},
{ value: "xy#xx.no", type: "work"},
{ value: "yy#xx.no", type: "work"},
],
foresatt_navn: [
{ type: "work", value: "Xx"},
{ type: "work", value: "Xy"},
{ type: "work", value: "Yy"},
]
}
}
In this case, the values can be retrieved from the object.Foresatt.foresatt_epost array.
Sample script:
const object = {}; //Your object
const res = object.Foresatt.foresatt_epost.map(e => e.value);
console.log(res) // Outputs: [ 'xx#xx.no', 'xy#xx.no', 'yy#xx.no' ]
If user.customSchemas is the above object, the script is as follows.
var foresatt = user.customSchemas;
const res = foresatt.Foresatt.foresatt_epost.map(e => e.value);
console.log(res)
If you want to retrieve the value as a comma separated string, you can use res.join(",").
References:
map()
Note:
If there is no guarantee your property will exist in your object, you can do (object.property||[]).map(...) instead of object.property.map(...) to avoid the error Uncaught TypeError: Cannot read property 'forEach' of undefined.

How to get data from database in array format using node js and MySql

I am using node.js as server language and Mysql as database so I am running query and getting data from database but is is showing in format like this
[ BinaryRow { name: 'Dheeraj', amount: '77.0000' },
BinaryRow { name: 'Raju', amount: '255.0000' } ]
What I want is
['Dheeraj', 77.0000],
['Raju', 66255.000030],
This what I am doing in my backend (node.js):
My model:
static getChartData(phoneNo, userType) {
let sql = 'select businessname as name,sum(billamt) amount from cashbackdispdets where consphoneno =' + phoneNo + ' group by businessid order by tstime desc limit 10'
return db.execute(sql, [phoneNo]);
My controller:
exports.getColumnChart = function(req, res) {
const phoneNo = req.body.userId
const userType = req.body.userType
console.log(phoneNo)
dashboardModule.getChartData(phoneNo, userType)
.then(([rows]) => {
if (rows.length > 0) {
console.log(rows)
return res.json(rows)
} else {
console.log("error")
return res.status(404).json({ error: 'Phone No. already taken' })
}
})
.catch((error) => {
console.log(error)
return res.status(404).json({ error: 'Something went wrong !!' })
})
}
I am sending this data to Ui and when I am receiving it on UI it is in the form of object inside array which is not the required data type I want
axios().post('/api/v1/Dashboard/DashboardColumnChart',this.form)
.then(res=>{
console.log(res.data)
debugger
this.chartData= res.data
})
The above code consoles on browser like
I am not getting any idea how o do it should I do it with backend or with front end and how
Nodejs will send you a JSON response if you want to change it. It is better to change or maniuplate it in a Front end framework. But if you want to change it in backend as you have asked Make sure that the rows is in the format that you want to recive.
let data = [
{ "name": "Dheeraj", "amount": "77.0000" },
{ "name": "Raju", "amount": "255.0000" }
]
// empty array to store the data
let testData = [];
data.forEach(element => {
testData.push(element.name)
});
You can format it using array.map and Object.values. map functions loops over each element and returns a modified element according to the callback provided. Object.values simply returns all the values of an object in an array.
const data = [ { "name": "Dheeraj", "amount": "77.0000" }, { "name": "Raju", "amount": "255.0000" } ];
const formattedData = data.map(obj => Object.values(obj));
console.log("Initial Data: ", data);
console.log("Formatted Data: ", formattedData);
// Map function example
const a = [1,2,3]
const mappedA = a.map(e => e * 2)
console.log(a, " mapped to: ", mappedA);
// Object.values example
const b = { firstName: 'John', lastName: 'Doe', number: '120120' }
console.log(Object.values(b));

Typescript convert an array to JSON

I have a complicated data structure that I need to convert to JSON. The problem is that my field names and values are in an array.
For instance, I have the following (simplified from my code base):
let SampleData = [
{ Field: 'Key', Value: '7'},
{ Field: 'City', Value: 'Some City'},
{ Field: 'Description', Value: 'Some Description'}
];
Basically my data is an array where the first element is the database column name, and the second element is the data in the column. I am trying to get a JSON object that is:
{ Key: 7, City: 'Some City', Description: 'Some Description' }
My real code has the fields and data is structures within the object, so I cannot simply use an Object.create() or Object.assign() as far as I can get working.
I have tried looping through to build a simple string and then use the JSON.parse to break it apart, but this seems like a lot of overhead for something I would have thought would be simpler.
As you asked, here's how to do it:
Mapping the array to an object
Converting the object to JSON
let array = [{
Field: 'Key',
Value: '7'
},
{
Field: 'City',
Value: 'Some City'
},
{
Field: 'Description',
Value: 'Some Description'
}
];
// #1 Mapping the array to an object...
let obj = {};
array.forEach(item => obj[item.Field] = item.Value);
// #2 Converting the object to JSON...
let json = JSON.stringify(obj);
console.log(json);
Bonus (ES6 + reduce):
const obj = array.reduce((acc, { Field, Value }) => ({ ...acc, [Field]: Value }), {});
you can try the below approach . I have used spread operator(ES6) and Object.assign to create the object ,then converted it into json string.
let SampleData = [
{ Field: 'Key', Value: '7'},
{ Field: 'City', Value: 'Some City'},
{ Field: 'Description', Value: 'Some Description'}
];
let obj = Object.assign(...SampleData.map( x => Object.values(x)).map(y => ({[y[0]]: y[1]})));
console.log(obj);
//{ Key: "7", City: "Some City", Description: "Some Description" }
console.log(JSON.stringify(obj));
I had a similar requirement and here is how I achieved it.
var ranges: segmentRange[] = new Array(2);
ranges[0] = { minimumPercentage: 50, maximumPercentage: 60 };
ranges[1] = { minimumPercentage: 30, maximumPercentage: 40 };
const segmentRanges = { segmentRanges: ranges };
return JSON.stringify(segmentRanges);
Output:
{"segmentRanges":[{"minimumPercentage":50,"maximumPercentage":60},{"minimumPercentage":30,"maximumPercentage":40}]}
HTH,

MongoDB: How to insert complex schema

I'm building a "Test" system. each test has some questions.
Each question has answers.
I'm getting a JSON to create the question from another server as:
{
requestType: 'CreateNewQuestion',
questionId: 17447,
subject: "Math",
subsubject: "Heshbon",
questionText: "1+4 Equels?",
answers: [{text : "2",rightAnswer : false},
{text : "35",rightAnswer : false},
{text : "5",rightAnswer : true},
{text : "9",rightAnswer : false}]
}
I built 2 Schemas:
module.exports = mongoose.model('Answer' ,
{
text: String,
rightAnswer: Boolean
}
);
And
module.exports = mongoose.model('Question' ,
{
questionId: Number,
subject: String,
subsubject: String,
questionText: String,
answerTimeAvg: Number,
fastestAnswer: Number,
answers: [{ type : mongoose.Types.ObjectId, ref: 'Answer' }]
}
);
I made a function that get the JSON and try to save it like:
var QuestionSchema = require('./schemas/question');
var AnswerSchema = require('./schemas/answer');
CreateNewQuestion: function (message) {
var information = {
questionId: message.questionId,
subject: message.subject,
subsubject: message.subsubject,
}
//Save Question
var record = new QuestionSchema(information);
record.save(function (err) {});
}
How can I create the Answers object and populate them into the question?
I tried couple of things but keep getting error,
What is the proper way?
I tried to read in "mongoosejs.com/docs" but the site is down :(
I needed to change the model to:
module.exports = mongoose.model('Question' ,
{
subject: String,
subsubject: String,
questionText: String,
answerTimeAvg: Number,
fastestAnswer: Number,
answers: [{ type : mongoose.Schema.Types.ObjectId, ref: 'Answer' }]
} );
And save the answers first, and than use the IDs:
CreateNewQuestion: function (message) {
////////////////////////
// Saving the answers //
////////////////////////
var answers = message.answers;
var answers_ids = [];
for(var i in answers) {
var answer = new AnswerSchema(answers[i]);
answer.save();
answers_ids.push(answer._id);
}
/////////////////////////
// Saving the question //
/////////////////////////
var information = {
subject: message.subject,
subsubject: message.subsubject,
questionText: message.questionText,
answerTimeAvg: 0,
fastestAnswer: 0,
answers: answers_ids
}
var record = new QuestionSchema(information);
record.save(function (err) {
if (err) {
console.log("Bad = " + err);
var result = "bad";
message.sendReplay({result: result});
}
else {
var result = "AllGood";
message.sendReplay({result: result});
}
});
},