


/**
 * 
 * @param {import("express").Request} req 
 */
async function all(req) {
  /** @type {sessionStore} */
  let store = req.sessionStore;
  return new Promise((done, reject) => {
    store.all((err, sessions) => {
      if (err) reject(err)
      else done(sessions);
    })
  })
}

/**
 * 
 * @param {import("express").Request} req 
 * @param {*} id session id
 * @returns 
 */
async function destroy(req, id) {
  /** @type {sessionStore} */
  let store = req.sessionStore;
  return new Promise((done, reject) => {
    store.destroy(id, (err, sessions) => {
      if (err) reject(err)
      else done();
    })
  })
}

/**
 * 根据用户id清空session
 * @param {import("express").Request} req    
 * @param {*} uid  user id
 */
async function destroyUser(req, uid) {
  let sessions = await all(req);
  let userSessions = sessions.filter(ses => ses.user && ses.user._id == uid);
  for (var i = 0; i < userSessions.length; i++) {
    await destroy(req, userSessions[i].id);
  }
}



module.exports = { all, destroy, destroyUser }