From bea0c1ff64d551035f1b4af748887055e63a7569 Mon Sep 17 00:00:00 2001 From: Ben Chambule Date: Thu, 22 Aug 2024 14:29:30 +0200 Subject: [PATCH] add: default processors --- index.js | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 131 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 225603b..f61b1a2 100644 --- a/index.js +++ b/index.js @@ -3,8 +3,13 @@ export { FORM, INFORMATION, + Message, - Lottus + Lottus, + + create_options_processor, + create_input_processor, + create_form_processor } const FORM = "FORM"; @@ -194,4 +199,129 @@ class Lottus { return result; } +} + + +Message.prototype.header = ""; +Message.prototype.body = ""; +Message.prototype.footer = "Powered by Lottus"; + + +Message.prototype.addOption = function addOption(key, label, next, params){ + if(!this.form){ + this.form = {options: new Map()}; + } + + if(!this.form.options){ + this.form.options = new Map(); + } + + if(key === undefined || key === null){ + key = this.form.options.size + 1; + } + + if(!label){ + throw new Error("Argument label cannot be null nor empty"); + } + + this.form.options.set(key.toString(), {label, next, params}); +} + + +Message.prototype.addInput = function addInput(name, type, next){ + if(!this.form){ + this.form = {input: {name, type, next}}; + } + + if(!this.form.input){ + this.form = {input: {name, type, next}}; + } +} + + +function create_options_processor(bot){ + async function create_options_processor(req, res){ + const options = req.form?.options; + + if(options){ + const option = options.get(req.prompt.toString()); + + if(option){ + req.selected_option = option; + let next = req.form?.next; + + if(req.selected_option.next){ + next = req.selected_option.next; + } + + return await bot.redirect(next, req); + } else { + res.error = "You selected an invalid option"; + } + } + + return res; + } + + return create_options_processor; +} + + +function create_input_processor(bot){ + async function input_processor(req, res){ + const input = req.form?.input; + + if(input){ + req.input = input; + // let next = req.form?.next; + return await bot.redirect(input.next, req); + } else { + res.error = "You selected an invalid option"; + } + + return res; + } + + return input_processor; +} + + +function create_form_processor(bot){ + async function form_processor(req, res){ + const options = req.form?.options; + const input = req.form?.input; + + if(options){ + const option = options.get(req.prompt); + + if(option){ + req.selected_option = option; + let next = req.form?.next; + + if(req.selected_option.next){ + next = req.selected_option.next; + } + + return await bot.redirect(next, req); + } else { + res.error = "You selected an invalid option"; + } + } + + if(input){ + req.input = input; + + let next = req.form?.next; + + return await bot.redirect(next, req); + } + + if(!res.error){ + res.error = "The form has no input nor options"; + } + + return res; + } + + return form_processor; } \ No newline at end of file