Skip to content

Instantly share code, notes, and snippets.

@wumanho
Created July 11, 2021 14:45
Show Gist options
  • Save wumanho/0a116247e31e905f8354cf163bf05df9 to your computer and use it in GitHub Desktop.
Save wumanho/0a116247e31e905f8354cf163bf05df9 to your computer and use it in GitHub Desktop.
c.js
const {Command} = require('commander');
const api = require('./api')
const program = new Command();
const inquirer = require('inquirer');
program
.option('-l, --list', '查看所有任务')
.action(async (options, command) => {
if (options.list) {
await listAll()
} else {
await operation()
}
})
program.command('add <taskName>')
.description('添加一个任务,请勿使用空格')
.action((taskName) => {
api.add(taskName)
})
program.command('clear')
.description('清空所有任务')
.action(() => {
api.clear()
})
program.parse(process.argv);
async function operation() {
let taskList = await api.listAll()
if(taskList.length<1){
console.log(`目前还没有数据,请使用 cli add<taskName> 命令添加`)
api.close()
return
}
inquirer.prompt(
{
type: 'list',
name: 'index',
message: '选择你的任务',
choices: [...taskList.map((task, index) => {
return {name: `${task.done ? '[x]' : '[_]'} ${index + 1} - ${task.title}`, value: index.toString()}
}), {name: '+ 创建任务', value: '-2'}, {name: '退出', value: '-1'}]
})
.then((answer) => {
askForAction(answer, taskList)
});
}
async function askForAction(answer, taskList) {
const index = parseInt(answer.index)
if (index >= 0) {
//选中了一个任务
inquirer.prompt({
type: 'list',
name: 'action',
message: '选择你的操作',
choices: [
{name: '标记为完成', value: 'done'},
{name: '标记为未完成', value: 'notDone'},
{name: '修改标题', value: 'update'},
{name: '删除', value: 'delete'},
{name: '退出', value: 'quit'},
]
}).then(answer2 => {
actions(answer2, index, taskList)
})
} else if (index === -2) {
//创建任务
inquirer.prompt({
type: 'input',
name: 'newTitle',
message: '请输入任务名称',
}).then(res => {
api.add(res.newTitle)
})
}else{
api.close()
}
}
async function actions(answer2, index, taskList) {
switch (answer2.action) {
case 'quit':
api.close()
break;
case 'done':
api.updateStatus(taskList[index]._id,true)
break;
case 'notDone':
api.updateStatus(taskList[index]._id,false)
break;
case 'update':
inquirer.prompt({
type: 'input',
name: 'newTitle',
message: '新的标题',
default: taskList[index].title
}).then(res => {
api.updateTitle(taskList[index]._id, res.newTitle)
})
break;
case 'delete':
api.delete(taskList[index]._id)
break;
}
}
async function listAll() {
const res = await api.listAll()
if(res.length<1){
console.log(`目前还没有数据,请使用 cli add<taskName> 命令添加`)
api.close()
return
}
res.forEach((task, index) => {
console.log(`${res.done ? '[x]' : '[]'} ${index + 1} - ${task.title}`)
})
api.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment