diff --git a/examples/sessions.js b/examples/sessions.js index f495eae..030c25d 100644 --- a/examples/sessions.js +++ b/examples/sessions.js @@ -3,6 +3,7 @@ import { lottus, form_processor, InMemorySessionManager, process_w_session, form (async function () { const bot = create_bot(); const session_manager = new InMemorySessionManager(); + session_manager.delete_after(1); let input = ["", "1", "0", "2"]; @@ -19,6 +20,15 @@ import { lottus, form_processor, InMemorySessionManager, process_w_session, form console.log(await process_request(bot, session_manager, identifier, {prompt: i})); } + + input = ["", "1", "0", "2"]; + + setTimeout(function(){}, 3); + for(const i of input){ + const identifier = "841234567"; + + console.log(await process_request(bot, session_manager, identifier, {prompt: i})); + } })(); async function process_request(bot, session_manager, msisdn, request){ diff --git a/index.js b/index.js index d7ef6e7..7d07e59 100644 --- a/index.js +++ b/index.js @@ -729,14 +729,38 @@ function format_message(message, parameters){ class InMemorySessionManager { #sessions = new Map(); + #delete_after = 1000 * 60 * 5; + + /** + * + * @param {number} ms + */ + delete_after(ms){ + this.#delete_after = ms; + } /** * * @param {string} identifier - * @returns {object} + * @returns {object | null} */ get(identifier){ - return this.#sessions.get(identifier); + const session = this.#sessions.get(identifier); + if(!session){ + return null + } + + const created_at = session.created_at; + const now = new Date(); + const diff_time = Math.abs(now - created_at); + + if(this.#delete_after && diff_time > this.#delete_after){ + this.close(identifier); + + return null; + } + + return session; } /** @@ -746,7 +770,7 @@ class InMemorySessionManager { * @param {object} parameters */ save(identifier, message, parameters){ - this.#sessions.set(identifier, {message: message, parameters: parameters}); + this.#sessions.set(identifier, {message: message, parameters: parameters, created_at: new Date()}); } /**