Exemple #1
0
app.post('/save_colonies/:token', express.bodyParser(), function(request, response) {
	console.log("hello!");
	var update_request = r.table('plates').get(request.params.token).update({colonies: request.body.colonies, clustering_params: request.body.clustering_params});

	reql(update_request)
	.then(function(reql_res) {
		response.writeHead(200, {'Content-Type': 'application/json'});
		response.end(JSON.stringify(reql_res));
	}).error(function (err) {
		response.writeHead(496, {'Content-Type': 'application/json'});
		response.end(JSON.stringify({'error': 'database threw error, see dberror', dberror: err}));
	}).catch(function (err) {
		response.writeHead(496, {'Content-Type': 'application/json'});
		response.end(JSON.stringify({'error': 'database threw error, see dberror', dberror: err}));
	});

});
Exemple #2
0
r.connect(rConfig, function(connErr, conn){
	if(connErr){
		throw new Error(connErr);
	}
	r.table("heroes").filter(function(hero){
		return r.expr(search).keys().map(function(key){
			return hero(key).match(r.expr("(?i)").add(r.expr(search)(key))).ne(null)
		}).reduce(function(left, right){
			return left.and(right)
		});
	}).orderBy(r.asc('id')).coerceTo("array").run(conn, function(reqlErr, heros){
		conn.close(); // close the connection
		if(reqlErr){ throw new Error(reqlErr); }

		console.log(heros);
	});
});
			r.connect(config, function(err, conn) {
				r.table(TABLE).filter(r.row('id').eq(ID)).
				    run(conn, function(err, cursor) {
				        if (err) throw err;
				        cursor.toArray(function(err, result) {
							should.equal(record.co2, result[0].co2, 'Data validation failed. Field: co2');
							should.equal(record.is_normal, result[0].is_normal, 'Data validation failed. Field: is_normal');
							should.equal(record.quality, result[0].quality, 'Data validation failed. Field: quality');
							should.equal(record.random_data, result[0].random_data, 'Data validation failed. Field: random_data');
							should.equal(moment(record.reading_time).format('YYYY-MM-DDTHH:mm:ss.SSSSZ'),
								moment(result[0].reading_time).format('YYYY-MM-DDTHH:mm:ss.SSSSZ'),  'Data validation failed. Field: reading_time');
							should.equal(record.temp, result[0].temp, 'Data validation failed. Field: temp');

							done();
				        });
				    });
			});
Exemple #4
0
 .then(function(conn)
  { r.table('IssuedTask')
     .insert(emitTask)
     .run(conn)
     .then(function(result)
     { emitTask.id = result.generated_keys[0]; 
      _.map(NamesActor, function(actorName)
      {
       r.table('Sessions')
        .filter({'username':actorName , online:true })
        .run(conn)
        .then(function(result){ return result.toArray();})
        .then(function(result)
        { _.map(result,function(s){ socketio.sockets.connected[s.socketid].emit('sendtask', emitTask) }); })  
      });
     });
   })
Exemple #5
0
 }, function(err, res) {
     if (err) {
         return reject(err);
     }
     console.log(source, 'uploaded')
     r.table('flat').insert({
         key: source.substring(source.indexOf('db') + 2).slice(0, -5),
         value: fs.readFileSync(source).toString('utf-8')
     }, {
         conflict: 'replace'
     }).run(r.conn).then(function(resilt) {
         console.log(source, 'saved to database')
         return resolve();
     }).catch(function(e) {
         return reject(e)
     })
 })
  onConnect(function(err, connection) {
    r.table('uber')
      .changes()
      .run(connection, function(err, cursor) {
        if (err) return

        cursor.on('error', function(error) {
          console.error('err: ', error);
        })

        cursor.on('data', function(event) {
          if (!event.new_val) emitEvent('remove', event.old_val);
          if (!event.old_val) emitEvent('save', event.new_val)
          if (event.old_val && event.new_val) emitEvent('save', event.new_val)
        })
      });
  })
Exemple #7
0
                connection(function(err, conn) {
                        if(err) {
                                console.log("[LOGERR] %s:%s", err.name, err.msg);
                                return callback(err);
                        }

                        r.table("mainaccounts").filter({email: email}).limit(1).update({pass: hash}).run(conn, function(err, res) {
                                if(res && res.replaced === 1) {
                                        callback(true);
                                }
                                else {
                                        callback(false);
                                }
                                release(conn);
                        }
                );
        });
router.post('/newevent', function(req, res) {
    console.log(req.body);
   
    var newEvent = {
        title: req.body.name,
        note: req.body.description,
        location_name: req.body.location,
        urgency: req.body.urgency,
        required_manpower: req.body.required_manpower,
        available_manpower: 0,
        signups: [],
        general_requirements: getArray(req.body)
    }
    r.table('event').insert(newEvent).run(dbConnection, function() {
        res.redirect('/'); 
    });
});
Exemple #9
0
 r.tableList().run(conn).then(list => {
   if (list.indexOf("guilds") > -1) {
     r.table("guilds").filter({guild_id: g}).run(conn, (e, re) => {
       if (re._responses.length === 0) {
         var guild = documentTemplate.guild;
         guild["guild_id"] = g;
         r.table("guilds").insert(guild).run(conn, (e, re2) => {return res(re2);});
       } else return res(re);
     });
   } else {
     r.tableCreate("guilds").run(conn).then(tab => {
       var guild = documentTemplate.guild;
       guild["guild_id"] = g;
       r.table("guilds").insert(guild).run(conn, (e, re) => {return res(re);});
     });
   }
 });
 r.db(dbConfig.db).tableCreate('collection1').run(rcon.conn, function(err, resultDb) {
   // adding new measurement
   r.table('collection1').insert([{
       path: 'measurements/tests/get/id/1'
     }, {
       path: 'measurements/tests/get/id/2'
     }, {
       path: 'measurements/tests/get/id/3'
     }, {
       path: 'measurements/tests/get/id/4'
     }])
     .run(rcon.conn, function(err, result) {
       if (err) return done(err);
       ids = result.generated_keys;
       done();
     });
 });
Exemple #11
0
    // gets an observation between two unix times (epoch1, epoch2)
    // returns a stream
    function get (observation, epoch1, epoch2) {
      var cursorS = streamFrom(
        r.table(tableName)
          .between(
            r.epochTime(epoch1),
            r.epochTime(epoch2),
            {index: 'timestamp'}
          )
          .filter({type: observation})
      )

      return cursorS.flatMap(cursor => {
        return Kefir.fromNodeCallback(cb => {
          cursor.toArray(cb)
        })
      })
    }
 it('should passthrough handshake', function (done) {
   var self = this
   var opts = {
     whitelist: [
       r.table('test-table').get('hey')
     ],
     db: this.db
   }
   var validator = createValidator(opts, false)
   this.writeStream.pipe(validator).on('data', function (_handshakeBuf) {
     // write to real socket
     self.__socketWrite(_handshakeBuf)
     if (validator.handshakeComplete) {
       done()
     }
   })
 })
Exemple #13
0
 .then(connection =>
   rethink.table('pipelines')
     .orderBy({ index: 'id' })
     .map(pipeline =>
       pipeline.merge(pipeline =>
         ({
           steps: pipeline('steps').map(step =>
             step.merge({
               computations: step('computations').map(compId =>
                 rethink.table('computations').get(compId)
               )
             })
           )
         })
       )
     )
     .run(connection)
Exemple #14
0
    client.query(queryString, [tablename], function(err, results) {
      var savedTimestamp = results.rows[0].last_used;
      dbMethods.checkandUpdateTimestamp(tablename, savedTimestamp);

      if (results.rows[0].custom) {
        var dbColumns = results.rows[0].columns;
        var dbDataTypes = results.rows[0].datatypes;

        dbMethods.matchDataTypes(req.body, dbColumns, dbDataTypes, function(
          err,
          passes
        ) {
          if (passes) {
            r
              .table(tablename)
              .insert(req.body)
              .run(connection, function(err, response) {
                if (err) {
                  console.log(err);
                }
                res.sendStatus(200);
              });
          } else {
            var errorMessage =
              'Incorrect data type for ' +
              err.column +
              '. Expected: ' +
              err.expected +
              '. Received: ' +
              err.received;
            res.status(400).send(errorMessage);
          }
        });
      } else {
        r
          .table(tablename)
          .insert(req.body)
          .run(connection, function(err, response) {
            if (err) {
              console.log(err);
            }
            res.sendStatus(200);
          });
      }
    });
Exemple #15
0
      return withDb(reply, (conn) => {
        return r.table('users')
          .get(username)
          .run(conn)
          .then((user) => {
            if (user == null) {
              throw new Error(`Couldn't find user '${username}'`)
            }

            let otherBoards = R.filter((board) => {
              return !R.any((projectPlan) => {
                return projectPlan.id === board.id
              }, user.projectPlans)
            }, boards)
            logger.debug(`Non-added boards:`, otherBoards)
            return otherBoards
          })
      })
Exemple #16
0
        onConnect(function(err, conn) {
            r.table('toys').get(req.query.id).run(conn, function(err, toy) {
                var pattern = /\s/g;
                var name = toy.name.toLowerCase().replace(pattern, '_');
                var dir = path.join(__dirname, 'public/images/monsters', name);
                
                var photos = fs.readdirSync(dir);

                var newPhotos = photos.map(function(photo) {
                    return path.join('images/monsters', name, photo);
                });
                toy.photos = newPhotos;

                res.json(toy);

                conn.close();
            });
        });
Exemple #17
0
 update = function(u, cb){
   r.table(config.db.userTable).filter({'email':u.email}).run(dbConnection()).then(function(cursor) {
     return cursor.toArray();
   }).then(function(result) {
     if(result.length > 0) {
       var ori = result[0];
       for (i in u) {
         ori[i] = u[i];
       }
       r.table(config.db.userTable).replace(ori).run(dbConnection()).then(function(a, b){
         cb(null, 'done');
       });
     }else{
       //TODO user not exist, should not happend
         cb('user not exist', null);
     }
   });
 };
  jwt.verify(token, 'need a better secret', function(err, decoded) {
    if (err) return fn(null, null);

    r.table('users').get(decoded.id).
      run(connection, function(err, result) {
        if (err) throw err;

        if (!result) {
          return fn(null, null);
        }

        if (result.token == token) {
          return fn(null, decoded);
        } else {
          return fn(null, null);
        }
      })
  });
Exemple #19
0
    r.connect(conf, function(error, conn){
      if(error) { // Wystąpił błąd przy połączeniu z bazą danych
        callback(error)
        return
      }

      if(params.id) { // Pobierz krotkę o danym numerze id
        r.table('APITokens').get(params.id).run(conn, function(err, row){
          if(err) {
            callback(err)
          } else if(!row) {
            callback(404)
          } else {
            callback(null, row)
          }
        })
      }
    })
Exemple #20
0
export const handler = async function ({ user, accessToken, post }) {
  let { id } = await fetch(`https://graph.facebook.com/me?access_token=${accessToken}`).then((res) => res.json())

  if (id !== user) {
    throw new Error('Author does not match access token!')
  }

  let conn = await r.connect(DB)

  let dbPost = r.table('posts').get(post)

  let likeIndices = await dbPost.getField('likes').offsetsOf(user).run(conn)
  if (!likeIndices.length) return {succes: false}

  await dbPost.update({likes: r.row('likes').deleteAt(likeIndices[0])}).run(conn)

  return { success: true }
}
Exemple #21
0
							r.table('authors').insert(insert_mock_data()).run(connection, function(err, result) {
							    if (err){
							    	throw err;
							    }else{
						  		// send random data from authors table with limit 20
						  			r.table('authors').sample(20).run(connection, function(err, cursor) {
								    if (err) throw err;
								    	cursor.toArray(function(err, result) {
									        if (err){
									        	console.log(err);
									        	throw err
									        }else{
									        	res.json(result);
									    	}
								    	});
						  			});
							    }
							});
Exemple #22
0
router.get("/scan/:id", function(req, res) {
 	r.table('members').get(req.params.id).run(req._rdbConn, function(error, value) {
        if (error) {
            handleError(res, error);
        }  else {
        	if (value != null) {
        		r.table('purchases').insert({memberid: req.params.id, amount: config.express.sodaCost, timestamp: new Date()}).run(req._rdbConn, function(error, value) {
			        if (error) {
			        	handleError(res, error);
			        }
        			res.send("1");
			    });
        	} else {
        		res.send("0");
        	}
        }
    });
});
 function(connection, callback) {
   rethinkdb.table('poll').get(pollData.id).run(connection, function(err, result) {
     if (err) { return callback(true, "Error fetching polls to database") }
     for(var pollCounter = 0; pollCounter < result.polls.length; pollCounter++) {
       if(result.polls[pollCounter].option === pollData.option) {
         result.polls[pollCounter].vote += 1;
         break;
       }
     }
     rethinkdb.table('poll').get(pollData.id).update(result).run(connection,function(err,result) {
       connection.close();
       if(err) {
         return callback(true,"Error updating the vote");
       }
       callback(null,result);
     });
   });
 }
Exemple #24
0
	      r.db('test').tableList().contains('authors').run(connection).then(function(table_exist) {
	      	// check table exist in test db
			  	if(table_exist){
			  		// send random data from authors table with limit 20
			  			r.table('authors').sample(20).run(connection, function(err, cursor) {
					    if (err) throw err;
					    	cursor.toArray(function(err, result) {
						        if (err){
						        	console.log(err);
						        	throw err
						        }else{
						        	res.json(result);
						    	}
					    	});
			  			});
				}else{
					// if table does not exist create table
					r.db('test').tableCreate('authors').run(connection, function(err, result) {
					    if (err){
					    	throw err;
					    }else{
					    	// insert some dummy data to table
							r.table('authors').insert(insert_mock_data()).run(connection, function(err, result) {
							    if (err){
							    	throw err;
							    }else{
						  		// send random data from authors table with limit 20
						  			r.table('authors').sample(20).run(connection, function(err, cursor) {
								    if (err) throw err;
								    	cursor.toArray(function(err, result) {
									        if (err){
									        	console.log(err);
									        	throw err
									        }else{
									        	res.json(result);
									    	}
								    	});
						  			});
							    }
							});
					    }
					})
				}
			});
Exemple #25
0
app.post('/posts/:id/comments', authenticate, function(req, res, next) {
  comment = {
    post_id: req.params.id,
    content: req.body.content,
    by: req.metaData
  }

  r.table('comments')
  .insert(comment, {returnChanges: true})
  .run(connRethinkdb)
  .then(function(result) {
    if (result.inserted !== 1) {
      handleError(res, next)(new Error("Document was not inserted.")); 
    } else {
      res.json(result.changes[0].new_val);
    }
  }).error(handleError(res))
  .finally(next);
});
Exemple #26
0
        join: function (conn, coll, criteria, sb) {
            console.log('JOIN! coll: ' + JSON.stringify(coll));
            console.log('JOIN! criteria: ' + JSON.stringify(criteria));
            console.log('JOIN! conn: ' + JSON.stringify(conn));
            console.log('JOIN! sb: ' + JSON.stringify(sb));
            console.dir(sb);
            var conn = connections[conn];
            var parent = r.table(coll).get(criteria.where.id);

            async.each(criteria.joins, function(item, callback) {

                var children = r.table(item.child).getAll(criteria.where.id, {index: item.childKey}).run(conn, function(err, cursor) {
                    if(err)
                        return callback(err);
                    cursor.toArray(function(err, results) {
                        if(err)
                            return callback(err);
                        var childrenObject = new Object();
                        childrenObject[item.alias] = results;
                        parent = parent.merge(childrenObject);
                        console.log(results);
                        callback(null);
                    });
                });
            }, function(err) {
                if(err)
                    return sb(err);
                parent.run(conn, function(err, result) {
                    if(err)
                        return sb(err);
                    // cursor.toArray(function(err, results) {
                    //  if(err)
                    //      return sb(err);
                    //  return sb(results);
                    // });
                    console.log('RESULT: ' + JSON.stringify(result));
                    console.log('SB: '+JSON.stringify(sb));
                    return sb.success(result);


                });
            });
        },
Exemple #27
0
dbapi.lookupUserByAdbFingerprint = function(fingerprint) {
  return db.run(r.table('users').getAll(fingerprint, {
      index: 'adbKeys'
    })
    .pluck('email', 'name', 'group'))
    .then(function(cursor) {
      return cursor.toArray()
    })
    .then(function(groups) {
      switch (groups.length) {
        case 1:
          return groups[0]
        case 0:
          return null
        default:
          throw new Error('Found multiple users for same ADB fingerprint')
      }
    })
}
Exemple #28
0
 promisedConn.then(conn => {
   r.table(__self__.tableName).filter({ "key": doc.query.key }).limit(1).run(conn, (err, cursor) => {
     if (err) {
       reject(err);
       conn.close();
     }
     cursor.toArray().then(results => {
       if (results && !results.length) {
         r.table(__self__.tableName).insert({ "key": doc.query.key, "val": doc.query.val, "ttl": __self__.ttl, "timestamp": r.now() }).run(conn, (err) => {
           if (err) {
             reject(err);
           }
           resolve(doc);
           __self__.refresh(conn);
         });
       }
     }).error(__self__.throwErr);
   });
 }).error(__self__.throwErr);
Exemple #29
0
api.getCaptures = function getCaptures(opts, callback) {
  r.table(table)
    .orderBy(r.desc('createdAt'))
    .limit(100)
    .run(conn, function(err, cursor) {
      if (err) {
        return callback(err);
      }
      cursor.toArray(function(err, result) {
        if (err) {
          return callback(err);
        }
        _.each(result, function(capture) {
          capture.fromNow = moment(capture.createdAt).fromNow();
        });
        return callback(null, result);
      });
    })
}
Exemple #30
0
function startChangefeed(io, pollId) {
	rethink.table(pollsTable)
		.get(pollId)
		//.pluck('question', 'options') //TODO: .get().pluck().changes() doesn't work. Only works without pluck, even though the docs say otherwise.
		.changes({includeInitial: true})
		.run(connection, function(error, cursor) {
			cursor.on("data", function(data) {
				var updateData = [];

				data.new_val.options.forEach(function(option) {
					updateData.push(option.votes);
				});

				io.to(pollId).emit('update_data', {
					updateData: updateData
				});
			})
		})
}