<commit_before>/*
 * Retro Game Night
 * Copyright (c) 2015 <NAME>, <NAME>, <NAME>
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */
"use strict"

import appconfig from '../config/appconfig'

function handleError(res, error) {
  console.log("error", error)
}

export default (app, rethinkdb) => {
  app.route('/challenges/all')
    .get(listChallenges)           // List all challenges
  app.route('/challenges/new')
    .post(createChallenge)         // Create a new challenge
    .get(createChallenge)
  app.route('/challenges/:id')
    .get(getChallenge)             // Get a specific challenge
    .put(updateChallenge)          // Update a specific challenge
    .delete(deleteChallenge)       // Delete a specific challenge

  function listChallenges(req, res, next) {
    rethinkdb.connect(appconfig.rethinkdb, (err, conn) => {
      rethinkdb.table('challenges').orderBy({index: "createdAt"}).run(conn, (error, cursor) => {
          if (error) {
              handleError(res, error) 
              next()
          }
          else {
              // Retrieve all the todos in an array
              cursor.toArray((error, result) => {
                  if (error) {
                      handleError(res, error) 
                  }
                  else {
                      // Send back the data
                      res.json(result)
                  }
              })
          }
      })
    })
  }

  function getChallenge(req, res, next) {
    const challengeID = req.params.id;
    rethinkdb.connect(appconfig.rethinkdb, (err, conn) => {
      rethinkdb.table('challenges').get(challengeID).run(conn, (error, result) => {
        if(error) {
          handleError(res, error) 
          next()
        }
        res.json(result)
      })
    })
  }

  function createChallenge(req, res, next) {
      const challenge = {}
      challenge.trial = req.body.trial || "Unnamed Trial"
      //challenge.goal = req.body.goal || "10000"
      challenge.issuer = req.body.issuer || "Anonymous"
      challenge.player = req.body.player || "Anonymous"
      challenge.challengeStatus = req.body.challengeStatus || "Pending"
      challenge.createdAt = rethinkdb.now()
      challenge.lastUpdated = rethinkdb.now()     // Set the field `createdAt` to the current time
      rethinkdb.connect(appconfig.rethinkdb, (err, conn) => {
        rethinkdb.table('challenges').insert(challenge, {returnChanges: true}).run(conn, (error, result) => {
            if (error) {
                handleError(res, error) 
                next()
            }
            else if (result.inserted !== 1) {
                handleError(res, new Error("Document was not inserted."))
                next()
            }
            else {
                res.json(result.changes[0].new_val)
            }
        })
      })
  }

  function updateChallenge(req, res, next) {
    const challengeID = req.params.id
    const challenge = {}
    let currentChallenge = {}
    rethinkdb.connect(appconfig.rethinkdb, (err, conn) => {
      rethinkdb.table('challenges').get(challengeID).run(conn, (error, result) => {
        if(error) {
          handleError(res, error) 
          next()
        }
        else {
          currentChallenge = result
          challenge.trial = req.body.trial || currentChallenge.trial
          //challenge.goal = req.body.goal || currentChallenge.goal
          challenge.issuer = req.body.issuer || currentChallenge.issuer
          challenge.player = req.body.player || currentChallenge.player
          challenge.challengeStatus = req.body.challengeStatus || currentChallenge.challengeStatus
          challenge.lastUpdated = rethinkdb.now()
          rethinkdb.connect(appconfig.rethinkdb, (err, conn) => {
            rethinkdb.table('challenges').get(challengeID).update(challenge, {returnChanges: true}).run(conn, (error, result) => {
              if(error) {
                //handleError(res, error) 
                throw error
                next()
              }
              else {
                res.json(result.changes[0].new_val)
              }
            })
          })
        }
      })
    })
  }

  /*
   * Delete a todo item.
   */
  function deleteChallenge(req, res, next) {
    const challengeID = req.params.id

    rethinkdb.connect(appconfig.rethinkdb, (err, conn) => {
      rethinkdb.table('challenges').get(challengeID).delete().run(conn, (error, result) => {
        if(error) {
          handleError(res, error) 
          next()
        }
        else {
          res.json({success: true})
        }
      })
    })
  }
}<commit_msg>Refactored `challenge-routes` to use Promises<commit_after>/*
 * Retro Game Night
 * Copyright (c) 2015 <NAME>, <NAME>, <NAME>
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */
"use strict"

import appconfig from '../config/appconfig'

function handleError(res, error) {
  console.log("error", error)
}

export default (app, rethinkdb) => {
  app.route('/challenges/all')
    .get(listChallenges)           // List all challenges
  app.route('/challenges/new')
    .post(createChallenge)         // Create a new challenge
    .get(createChallenge)
  app.route('/challenges/:id')
    .get(getChallenge)             // Get a specific challenge
    .put(updateChallenge)          // Update a specific challenge
    .delete(deleteChallenge)       // Delete a specific challenge

  function listChallenges(req, res, next) {
    let connection = null
    rethinkdb.connect(appconfig.rethinkdb)
      .then(conn => {
        connection = conn
        return rethinkdb
          .table('challenges')
          .orderBy({index: "createdAt"})
          .run(connection)
      })
      .then(cursor => cursor.toArray())
      .then(result => res.json(result))
      .then(() => connection.close())
      .error(error => handleError(res, error))
  }

  function getChallenge(req, res, next) {
    let connection = null
    const challengeID = req.params.id;
    rethinkdb.connect(appconfig.rethinkdb)
      .then(conn => {
        connection = conn
        return rethinkdb
          .table('challenges')
          .get(challengeID)
          .run(conn)
      })
      .then(result => res.json(result))
      .then(() => connection.close())
      .error(error => handleError(res, error))
  }

  function createChallenge(req, res, next) {
      let connection = null
      const challenge = {}
      challenge.trial = req.body.trial || "Unnamed Trial"
      //challenge.goal = req.body.goal || "10000"
      challenge.issuer = req.body.issuer || "Anonymous"
      challenge.player = req.body.player || "Anonymous"
      challenge.challengeStatus = req.body.challengeStatus || "Pending"
      challenge.createdAt = rethinkdb.now()
      challenge.lastUpdated = rethinkdb.now()     // Set the field `createdAt` to the current time
      rethinkdb.connect(appconfig.rethinkdb)
        .then(conn => {
          connection = conn
          return rethinkdb
            .table('challenges')
            .insert(challenge, {returnChanges: true})
            .run(connection)
        })
        .then(result => {
          if (result.inserted !== 1) {
              handleError(res, new Error("Document was not inserted."))
          } else {
              return res.json(result.changes[0].new_val)
          }
        })
        .then(() => connection.close())
        .error(error => handleError(res, error))
  }

  function updateChallenge(req, res, next) {
    const challengeID = req.params.id
    let connection = null
    rethinkdb.connect(appconfig.rethinkdb)
      .then(conn => {
        connection = conn
        return rethinkdb
          .table('challenges')
          .get(challengeID)
          .run(connection)
      })
      .then(result => {
        const challenge = {}
        const currentChallenge = result
        challenge.trial = req.body.trial || currentChallenge.trial
        //challenge.goal = req.body.goal || currentChallenge.goal
        challenge.issuer = req.body.issuer || currentChallenge.issuer
        challenge.player = req.body.player || currentChallenge.player
        challenge.challengeStatus = req.body.challengeStatus || currentChallenge.challengeStatus
        challenge.lastUpdated = rethinkdb.now()
        return challenge
      })
      .then(challenge => rethinkdb
        .table('challenges')
        .get(challengeID)
        .update(challenge, {returnChanges: true})
        .run(connection)
      )
      .then(result => res.json(result.changes[0].new_val))
      .then(() => connection.close())
      .error(error => handleError(res, error))
  }

  /*
   * Delete a todo item.
   */
  function deleteChallenge(req, res, next) {
    const challengeID = req.params.id
    let connection = null
    rethinkdb.connect(appconfig.rethinkdb)
      .then(conn => {
        connection = conn
        return rethinkdb
          .table('challenges')
          .get(challengeID)
          .delete()
          .run(connection)
      })
      .then(() => res.json({success: true}))
      .then(() => connection.close())
      .error(error => handleError(res, error))
  }
}
{'fraction_non_alphanumeric': 0.12721191195511436, 'fraction_numerical': 0.002589555459646094, 'mean_word_length': 2.0480105228543244, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '633887', 'n_tokens_mistral': 2806, 'n_tokens_neox': 2602, 'n_words': 558}