{"size": 1596, "ext": "js", "max_stars_repo_path": "components/checkpoints/checkpointsController.js", "max_stars_repo_name": "theleoad/atena", "max_stars_repo_stars_event_min_datetime": "2019-10-22T01:08:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-22T01:08:18.000Z", "max_issues_repo_path": "components/checkpoints/checkpointsController.js", "max_issues_repo_name": "theleoad/atena", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "components/checkpoints/checkpointsController.js", "max_forks_repo_name": "theleoad/atena", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.5675675676, "max_line_length": 64, "alphanum_fraction": 0.6315789474}
import errors from '../errors'
import dal from './checkpointsDAL'

const file = 'Checkpoints | Controller'

const getAll = async () => {
  try {
    return dal.findAll()
  } catch (e) {
    errors._throw(file, 'getAll', e)
  }
}

const getById = async checkpointId => {
  try {
    return dal.findOne({ _id: checkpointId })
  } catch (e) {
    errors._throw(file, 'getById', e)
  }
}

const create = async data => {
  try {
    const { level, xp, rewards, totalEngagedUsers } = data
    const checkpoint = {
      level: level,
      xp: xp,
      rewards: rewards.filter(item => item.length > 0),
      totalEngagedUsers: totalEngagedUsers
    }
    return dal.save(checkpoint)
  } catch (e) {
    errors._throw(file, 'create', e)
  }
}

const update = async (checkpointId, data) => {
  try {
    const { level, xp, rewards, totalEngagedUsers } = data
    const checkpoint = await dal.findOne({ _id: checkpointId })

    if (!checkpoint) return { error: 'Checkpoint not found' }

    checkpoint.level = level
    checkpoint.xp = xp
    checkpoint.rewards = rewards.filter(item => item.length > 0)
    checkpoint.totalEngagedUsers = totalEngagedUsers

    return dal.save(checkpoint)
  } catch (e) {
    errors._throw(file, 'update', e)
  }
}

const remove = async checkpointId => {
  try {
    const checkpoint = await dal.findOne({ _id: checkpointId })

    if (!checkpoint) return { error: 'Checkpoint not found' }

    return dal.deleteOne({ _id: checkpointId })
  } catch (e) {
    errors._throw(file, 'delete', e)
  }
}

export default {
  getAll,
  getById,
  create,
  update,
  remove
}
