I"m using inquirer.js to build a commandline employee database. Is it possible to populate the choices array dynamically from a sql database in inquirer.js?
for example
inquirer.prompt([
{ type: 'list',
message: "Choose department to add Role to",
name: "department",
choices: [
`SELECT * FROM departments`
]
}
])
deparments is the table I want to acceess I'd want it to return the list of all departments as the choices
I actually ran into this exact problem recently and have a functioning solution!!
Inquirer's choices key can be defined using a function but expects the function to return an array of objects; each object represents a choice and has a
name:
key to be shown to the user as an option for the choice, and avalue:
key which will be what inquirer stores as the answer value in the answer object (like a number, string, or boolean etc.). Here is an example of a structure the choices key expects to be returned from the function:Make sure that you check the data that your function returns and ensure that you have this format so that inquirer's choice key accepts it!
Here is how I implemented it with a database:
I am using a .promise() on my connection so that I can use async/await syntax. Here is my connection setup for mysql2:
Here is the particular question object that has
choices:
being defined by a function calleddepartmentChoices()
that is getting all the department choices from mysql database. Make sure this is defined in an async function as well so you can useawait
.Here is the function definition. I chose to use async/await for the database query for easy of readability. You should probably wrap it in a try/catch for better error handling and best practices. Notice I used an alias
value
for the id as this is the value I want to use for thevalue:
key in the choice object.name
did not need an alias as it is the value I want stored under thename:
key in the choice object.This is the array this function will return from my database: