How to use rethinkdb - 10 common examples

To help you get started, we’ve selected a few rethinkdb examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github davidgljay / nametag / horizon / cli / src / migrate.js View on Github external
function validateMigration () {
  // check that `${project}_internal` exists
  const project = this.options.project_name
  const internalNotFound = `Database named '${project}_internal' wasn't found`
  const tablesHaveHzPrefix = `Some tables in ${project} have an hz_ prefix`
  const checkForHzTables = r.db('rethinkdb')
          .table('table_config')
          .filter({ db: project })('name')
          .contains((x) => x.match('^hz_'))
          .branch(r.error(tablesHaveHzPrefix), true)
  const waitForCollections = r.db(`${project}_internal`)
          .table('collections')
          .wait({ timeout: 30 })
          .do(() => r.db(project).tableList())
          .forEach((tableName) =>
            r.db(project).table(tableName).wait({ timeout: 30 })
          )

  return Promise.resolve().then(() => {
    white('Validating current schema version')
    return r.dbList().contains(`${project}_internal`)
      .branch(true, r.error(internalNotFound))
github rethinkdb / horizon / cli / src / migrate.js View on Github external
function validateMigration() {
  // check that `${project}_internal` exists
  const project = this.options.project_name;
  const internalNotFound = `Database named '${project}_internal' wasn't found`;
  const tablesHaveHzPrefix = `Some tables in ${project} have an hz_ prefix`;
  const checkForHzTables = r.db('rethinkdb')
          .table('table_config')
          .filter({ db: project })('name')
          .contains((x) => x.match('^hz_'))
          .branch(r.error(tablesHaveHzPrefix), true);
  const waitForCollections = r.db(`${project}_internal`)
          .table('collections')
          .wait({ timeout: 30 })
          .do(() => r.db(project).tableList())
          .forEach((tableName) =>
            r.db(project).table(tableName).wait({ timeout: 30 })
          );

  return Promise.resolve().then(() => {
    white('Validating current schema version');
    return r.dbList().contains(`${project}_internal`)
      .branch(true, r.error(internalNotFound))
github rethinkdb / rethinkdb-example-nodejs / benford / crawler.js View on Github external
}, function(err, conn) {
        if (err) {
            failedAttempts++;
            console.log("Attempt: "+failedAttempts)
            console.error("Could not open a connection to rethinkdb\n"+err.message);

            return setTimeout(init, failedAttempts*5000);
        }

        // Initialize the table with first the database
        r.dbCreate(config.rethinkdb.db).run(conn, function(err, result) {
            // If the database already exists, we'll get an error here, but we'll just keep going
            r.db(config.rethinkdb.db).tableCreate('benford').run(conn, function(err, result) {
                // If the table already exists, we'll get an error here, but we'll just keep going

                var seeds = [];
                for(var i=1; i<10; i++) {
                    seeds.push({id: ""+i, value: 0}); // Note: We use the digit value as the primary key and save it as a string
                }
                r.db(config.rethinkdb.db).table('benford').insert(seeds).run(conn, function(err, result) {
                    // If the database was already initialized, the inserts will not be executed since RethinkDB
                    // does not allow redundant primary keys (`id`)
                    listen();
                });
            });
        });
    });
github jmdobry / RequelPro / src / RequelPro / models / table.js View on Github external
} else if (operator === '<') {
          clause = clause.lt(value);
        } else if (operator === '>=') {
          clause = clause.ge(value);
        } else if (operator === '<=') {
          clause = clause.le(value);
        } else if (operator === 'in') {
          clause = r.expr(value).contains(clause);
        } else if (operator === 'is null') {
          clause = clause.eq(null);
        }
        rql = rql.filter(clause);
      }
      if (options.sort) {
        if (options.direction === 'desc') {
          rql2 = rql.orderBy(r.desc(options.sort));
        } else {
          rql2 = rql.orderBy(options.sort);
        }
      }
      if (!rql2) {
        rql2 = rql;
      }
      return store.utils.Promise.all([
        // filtered, skipped, ordered and limited data
        connection.run(rql2.skip(Table.TABLE_PAGE_SIZE * (parseInt(options.page, 10) - 1)).limit(Table.TABLE_PAGE_SIZE).coerceTo('ARRAY')),
        // count query does not need the skip, orderBy, or limit
        connection.run(rql.count())
      ]).then(results => {
        return {
          data: results[0],
          count: results[1]
github codehangar / reqlpro / app / services / rethinkdb.service.js View on Github external
if (start) {
        tableData = yield r.db(db).table(table).between(start, r.maxval, {
          leftBound: "open",
          index: index
        })
          .orderBy({
            index: index
          }).limit(5).run(conn);
      } else if (end) {
        // TODO: This doesn't work, as it start over from "zero" position
        tableData = yield r.db(db).table(table).between(r.minval, end, {
          rightBound: "open",
          index: index
        })
          .orderBy({
            index: r.desc(index)
          }).limit(5).run(conn);
      } else {
        tableData = yield r.db(db).table(table).orderBy({
          index: index || 'id'
        }).limit(5).run(conn);
      }
      resolve(tableData);
    }).catch(function(err) {
      reject(err);
github Exynize / exynize-rest / src / pipes / runner / runner.js View on Github external
e => {
            logger.error('[OUT] error in pipline:', e);
            // if executed in production - push error to persistent db log
            promises.push(PipelineLog.create({
                pipeline: id,
                sessionId,
                data: {
                    type: 'error',
                    error: e,
                },
                added_on: r.now(), // eslint-disable-line
            }));
            // schedule exit
            logger.debug('[OUT] scheduling exit...');
            clean().forEach(p => promises.push(p));
            delayedExit({
                status: 'error',
                message: e.message || JSON.stringify(e)
            });
        }, () => {
            logger.debug('[OUT] pipeline done, scheduling exit');
github hyperledger / sawtooth-core / families / track_and_trade / server / scripts / bootstrap_database.js View on Github external
.then(conn => {
    console.log(`Creating "${NAME}" database...`)
    r.dbList().contains(NAME).run(conn)
      .then(dbExists => {
        if (dbExists) throw new Error(`"${NAME}" already exists`)
        return r.dbCreate(NAME).run(conn)
      })
      .then(res => {
        console.log('Creating "users" table...')
        return r.db(NAME).tableCreate('users', {
          primaryKey: 'publicKey'
        }).run(conn)
      })
      .then(res => {
        // The usernames table is used to quickly ensure unique usernames
        console.log('Creating "usernames" table...')
        return r.db(NAME).tableCreate('usernames', {
          primaryKey: 'username'
        }).run(conn)
github hyperledger / sawtooth-core / extensions / mktplace / navigator / server / lib / mktplace / service / offer_service.js View on Github external
var secondaryFilters = [];
        // filter this first, as it is more specific than assets
        if (opts.filter.holdingId) {
            secondaryFilters.push(r.or(r.row('input')('id').eq(opts.filter.holdingId),
                                       r.row('output')('id').eq(opts.filter.holdingId)));
        } else if (opts.filter.assetId) {
            secondaryFilters.push(r.or(r.row('input')('asset').eq(opts.filter.assetId),
                                       r.row('output')('asset').eq(opts.filter.assetId)));
        } else if (opts.filter.inputAssetId) {
            secondaryFilters.push(r.row('input')('asset').eq(opts.filter.inputAssetId));
        } else if (opts.filter.outputAssetId) {
            secondaryFilters.push(r.row('output')('asset').eq(opts.filter.outputAssetId));
        }

        if (secondaryFilters.length > 0) {
            query = query.filter(r.and(r.args(secondaryFilters)));
        }

        if (opts.count) {
            return query.count();
        }

        if (opts.sort) {
            query = query.orderBy(opts.sort);
        }

        if (opts.limit && opts.page && opts.page > 0) {
            query = query.skip(opts.limit * opts.page);
        }

        if (opts.limit) {
            query = query.limit(opts.limit);
github wfjsw / osiris-groupindexer / plugins / gpindex_countmember.js View on Github external
async function refreshOnGetDetail(msg, result, bot) {
    try {
        let gid = parseInt(result[1])
        if (gid > 0) return
        const record = await comlib.getRecord(gid)
        if (!record) return
        // if (!record.type == 'channel' && !record.is_public) return
        let member_count = 0
        try {
            member_count = await bot.getChatMembersCount(gid)
        } catch (e) {
            member_count = await tmeassist.getMemberCount(record.is_public ? `https://t.me/${record.username}` : record.invite_link)
            if (!member_count) member_count = require('rethinkdb').literal()
        }
        return await comlib.silentUpdate(gid, {
            member_count
        })
    } catch (e) {
        console.error(e.message)
    }
}
github ktbartholomew / tic-tac-toe / bot / index.js View on Github external
var r = require('rethinkdb');
var WebSocket = require('ws');

var ws = new WebSocket('wss://tictac.io/live/');
var conn = null;

r.connect({host: process.env.DB_HOST, db: 'tictactoe'})
.then(function (connection) {
  conn = connection;
});

var emptyGrid = [[null, null, null],[null, null, null],[null, null, null]];

var currentGame = {
  id: null,
  team: null,
  grid: emptyGrid,
  winner: null,
  frames: []
};

var gridToFrame = function (grid) {
  // convert a 2-dimensional grid array to a 9-character string of only [0-2]

rethinkdb

This package provides the JavaScript driver library for the RethinkDB database server for use in your node application.

Unknown
Latest version published 4 years ago

Package Health Score

60 / 100
Full package analysis