Skip to content

Commit

Permalink
add: delete_afer on InMemorySessionManager
Browse files Browse the repository at this point in the history
  • Loading branch information
benchambule committed Aug 28, 2024
1 parent 9916353 commit f12aee0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
10 changes: 10 additions & 0 deletions examples/sessions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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"];

Expand All @@ -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){
Expand Down
30 changes: 27 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand All @@ -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()});
}

/**
Expand Down

0 comments on commit f12aee0

Please sign in to comment.