{"size": 1560, "ext": "js", "max_stars_repo_path": "src/controllers/session.controller.js", "max_stars_repo_name": "meetKazuki/sessions-manager", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/controllers/session.controller.js", "max_issues_repo_name": "meetKazuki/sessions-manager", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/controllers/session.controller.js", "max_forks_repo_name": "meetKazuki/sessions-manager", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.4406779661, "max_line_length": 74, "alphanum_fraction": 0.6096153846}
import { ApplicationError, NotFoundError } from '../helpers/error';
import models from '../models';
import paginator from '../helpers/paginator';

const { Session } = models;

export default {
  getAllSessions: async (request, response) => {
    const { user, query: { page = 1, limit = 10 } } = request;
    const { data, count } = await paginator(Session, {
      where: { userId: user.id },
      page,
      limit,
    });

    return response.status(200).json({
      status: 'success',
      message: 'sessions retrieved for user',
      sessions: data,
      count,
      page: +page,
      limit: +limit,
    });
  },

  logoutSession: async (request, response) => {
    const { user, params: { sessionId } } = request;

    const session = await Session.findByPk(sessionId);
    if (!session) {
      throw new NotFoundError(`session with ${sessionId} does not exist`);
    }
    if (session.userId !== user.id) {
      throw ApplicationError(403, 'operation is forbidden');
    }

    await Session.destroy({ where: { id: sessionId } });

    return response.status(200).json({
      status: 'success',
      message: 'session has been logged-out',
    });
  },

  logoutAllSessions: async (request, response) => {
    const { user } = request;

    const sessions = await Session.findAll();
    if (!sessions) throw new NotFoundError('no session(s) for this user');

    await Session.destroy({ where: { userId: user.id } });

    return response.status(200).json({
      status: 'success',
      message: 'session history cleared',
    });
  },
};
