All files / src expressCassandra.js

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 3571x   1x       1x 1x 1x   1x 1x   1x   1x     1x   1x 1x 1x   1x 1x   1x 1x 1x 1x     1x   1x 1x 1x     1x 8x         8x   8x 8x   8x 8x 8x 8x 8x 8x           1x 1x 1x 1x 1x 1x                 1x 1x 1x 1x 8x   1x     1x               1x   1x 1x     1x   1x 2x 2x 2x   2x   2x 2x 2x     2x 18x     2x   2x             1x   1x 1x 1x   1x 1x 1x 9x   1x   1x 1x 1x               1x   1x 1x         1x       1x   1x 1x   1x 1x 1x 9x   1x   1x 1x 1x               1x   1x 1x 1x 1x     1x   1x   1x   5x   1x   1x   1x   1x   1x   1x 672x         672x       672x   672x 672x   672x 672x   672x 670x   2x 1x 1x   1x 1x     672x 672x 20008x 20008x         672x             1x   1x 672x 672x 672x     672x       672x   672x     1x   8x       1x     2x         26x                   809x                   1x           1x                                   2x         1x                   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x   1x  
const semver = require('semver');
 
Iif (!semver.satisfies(process.version, '>=6.0.0')) {
  require('babel-polyfill');
}
 
const Promise = require('bluebird');
const _ = require('lodash');
const path = require('path');
 
let dseDriver;
try {
  // eslint-disable-next-line import/no-extraneous-dependencies, import/no-unresolved
  dseDriver = require('dse-driver');
} catch (e) {
  dseDriver = null;
}
 
const cql = Promise.promisifyAll(dseDriver || require('cassandra-driver'));
 
const ORM = Promise.promisifyAll(require('./orm/apollo'));
const readdirpAsync = Promise.promisify(require('readdirp'));
const debug = require('debug')('express-cassandra');
 
const exporter = require('./utils/exporter');
const importer = require('./utils/importer');
 
const CassandraClient = function f(options) {
  this.modelInstance = {};
  this.orm = new ORM(options.clientOptions, options.ormOptions);
  this.orm = Promise.promisifyAll(this.orm);
};
 
CassandraClient.createClient = (options) => (new CassandraClient(options));
 
CassandraClient.setDirectory = (directory) => {
  CassandraClient.directory = directory;
  return CassandraClient;
};
 
CassandraClient.syncModelFileToDB = (file, callback) => {
  Iif (!file.name.includes('Model')) {
    callback();
    return;
  }
 
  const modelName = CassandraClient._translateFileNameToModelName(file.name);
 
  Eif (modelName) {
    const fileLocation = path.join(CassandraClient.directory, file.path);
    // eslint-disable-next-line import/no-dynamic-require
    const defaultModelSchema = require(fileLocation);
    const modelSchema = defaultModelSchema.default ? defaultModelSchema.default : defaultModelSchema;
    CassandraClient.modelInstance[modelName] = CassandraClient.orm.addModel(modelName.toLowerCase(), modelSchema);
    CassandraClient.modelInstance[modelName].syncDB(callback);
    CassandraClient.modelInstance[modelName] = Promise.promisifyAll(CassandraClient.modelInstance[modelName]);
    return;
  }
 
  callback();
};
 
CassandraClient.bind = (options, cb) => {
  CassandraClient.modelInstance = {};
  CassandraClient.orm = new ORM(options.clientOptions, options.ormOptions);
  CassandraClient.orm = Promise.promisifyAll(CassandraClient.orm);
  CassandraClient.orm.initAsync()
    .then(() => readdirpAsync({
      root: CassandraClient.directory,
      fileFilter: [
        '*.js', '*.javascript', '*.jsx', '*.coffee', '*.coffeescript', '*.iced',
        '*.script', '*.ts', '*.tsx', '*.typescript', '*.cjsx', '*.co', '*.json',
        '*.json5', '*.litcoffee', '*.liticed', '*.ls', '*.node', '*.toml', '*.wisp',
      ],
    }))
    .then((fileList) => {
      const syncModelTasks = [];
      const syncModelFileToDBAsync = Promise.promisify(CassandraClient.syncModelFileToDB);
      fileList = fileList.files;
      fileList.forEach((file) => {
        syncModelTasks.push(syncModelFileToDBAsync(file));
      });
      return Promise.all(syncModelTasks);
    })
    .then(() => {
      Eif (cb) cb();
    })
    .catch((err) => {
      if (cb && _.isArray(err) && err.length > 0) cb(err[0]);
      else if (cb) cb(err);
    });
};
 
CassandraClient.bindAsync = Promise.promisify(CassandraClient.bind);
 
CassandraClient.prototype.init = function f(callback) {
  this.orm.init(callback);
};
 
CassandraClient.prototype.initAsync = Promise.promisify(CassandraClient.prototype.init);
 
CassandraClient.getTableList = function f(callback) {
  const systemClient = this.orm.get_system_client();
  const keyspace = this.orm.get_keyspace_name();
  const tables = [];
 
  systemClient.connect()
    .then(() => {
      const systemQuery = 'SELECT table_name FROM system_schema.tables WHERE keyspace_name = ?';
      debug(`Finding tables in keyspace: ${keyspace}`);
      return systemClient.execute(systemQuery, [keyspace]);
    })
    .then((result) => {
      for (let i = 0; i < result.rows.length; i++) {
        tables.push(result.rows[i].table_name);
      }
    })
    .then(() => systemClient.shutdown())
    .then(() => {
      callback(null, tables);
    })
    .catch((err) => {
      callback(err);
    });
};
 
CassandraClient.getTableListAsync = Promise.promisify(CassandraClient.getTableList);
 
CassandraClient.export = function f(fixtureDirectory, callback) {
  const systemClient = this.orm.get_system_client();
  const keyspace = this.orm.get_keyspace_name();
 
  systemClient.connect()
    .then(() => this.getTableListAsync())
    .then((tables) =>
      Promise.each(tables, (table) =>
        exporter.processTableExport(systemClient, fixtureDirectory, keyspace, table)))
    .then(() => systemClient.shutdown())
    .then(() => {
      debug('==================================================');
      debug(`Completed exporting all tables from keyspace: ${keyspace}`);
      callback();
    })
    .catch((err) => {
      debug(err);
      callback(err);
    });
};
 
CassandraClient.exportAsync = Promise.promisify(CassandraClient.export);
 
CassandraClient.import = function f(fixtureDirectory, options, callback) {
  Iif (arguments.length === 2) {
    callback = options;
    options = {};
  }
 
  const defaults = {
    batchSize: 1,
  };
 
  options = _.defaultsDeep({}, options, defaults);
 
  const systemClient = this.orm.get_system_client();
  const keyspace = this.orm.get_keyspace_name();
 
  systemClient.connect()
    .then(() => this.getTableListAsync())
    .then((tables) =>
      Promise.each(tables, (table) =>
        importer.processTableImport(systemClient, fixtureDirectory, keyspace, table, options.batchSize)))
    .then(() => systemClient.shutdown())
    .then(() => {
      debug('==================================================');
      debug(`Completed importing to keyspace: ${keyspace}`);
      callback();
    })
    .catch((err) => {
      debug(err);
      callback(err);
    });
};
 
CassandraClient.importAsync = Promise.promisify(CassandraClient.import);
 
CassandraClient.prototype.loadSchema = function f(modelName, modelSchema) {
  this.modelInstance[modelName] = this.orm.addModel(modelName, modelSchema);
  this.modelInstance[modelName] = Promise.promisifyAll(this.modelInstance[modelName]);
  return this.modelInstance[modelName];
};
 
CassandraClient.uuid = () => (cql.types.Uuid.random());
 
CassandraClient.uuidFromString = (str) => (cql.types.Uuid.fromString(str));
 
CassandraClient.uuidFromBuffer = (buf) => (new cql.types.Uuid(buf));
 
CassandraClient.timeuuid = () => (cql.types.TimeUuid.now());
 
CassandraClient.timeuuidFromDate = (date) => (cql.types.TimeUuid.fromDate(date));
 
CassandraClient.timeuuidFromString = (str) => (cql.types.TimeUuid.fromString(str));
 
CassandraClient.timeuuidFromBuffer = (buf) => (new cql.types.TimeUuid(buf));
 
CassandraClient.maxTimeuuid = (date) => (cql.types.TimeUuid.max(date));
 
CassandraClient.minTimeuuid = (date) => (cql.types.TimeUuid.min(date));
 
CassandraClient.prototype.doBatch = function f(queries, options, callback) {
  Iif (arguments.length === 2) {
    callback = options;
    options = {};
  }
 
  const defaults = {
    prepare: true,
  };
 
  options = _.defaultsDeep({}, options, defaults);
 
  const randomModel = this.modelInstance[Object.keys(this.modelInstance)[0]];
  const beforeHooks = [];
 
  let batchResult;
  Promise.all(beforeHooks)
    .then(() => {
      if (queries.length > 1) {
        return randomModel.execute_batchAsync(queries, options);
      }
      if (queries.length > 0) {
        debug('single query provided for batch request, applying as non batch query');
        return randomModel.execute_queryAsync(queries[0].query, queries[0].params, options);
      }
      debug('no queries provided for batch request, empty array found, doing nothing');
      return {};
    })
    .then((response) => {
      batchResult = response;
      for (let i = 0; i < queries.length; i++) {
        const afterHookResponse = queries[i].after_hook();
        Iif (afterHookResponse !== true) {
          callback(afterHookResponse);
          return;
        }
      }
      callback(null, batchResult);
    })
    .catch((err) => {
      callback(err);
    });
};
 
CassandraClient.prototype.doBatchAsync = Promise.promisify(CassandraClient.prototype.doBatch);
 
CassandraClient.doBatch = function f(queries, options, callback) {
  Eif (arguments.length === 2) {
    callback = options;
    options = {};
  }
 
  const defaults = {
    prepare: true,
  };
 
  options = _.defaultsDeep({}, options, defaults);
 
  CassandraClient.prototype.doBatch.call(CassandraClient, queries, options, callback);
};
 
CassandraClient.doBatchAsync = Promise.promisify(CassandraClient.doBatch);
 
CassandraClient._translateFileNameToModelName = (fileName) => (
  fileName.slice(0, fileName.lastIndexOf('.')).replace('Model', '')
);
 
Object.defineProperties(CassandraClient, {
  consistencies: {
    get() {
      return cql.types.consistencies;
    },
  },
  datatypes: {
    get() {
      return cql.types;
    },
  },
  driver: {
    get() {
      return cql;
    },
  },
  instance: {
    get() {
      return CassandraClient.modelInstance;
    },
  },
  close: {
    get() {
      return CassandraClient.orm.close;
    },
  },
  closeAsync: {
    get() {
      return Promise.promisify(CassandraClient.orm.close);
    },
  },
});
 
 
Object.defineProperties(CassandraClient.prototype, {
  consistencies: {
    get() {
      return cql.types.consistencies;
    },
  },
  datatypes: {
    get() {
      return cql.types;
    },
  },
  driver: {
    get() {
      return cql;
    },
  },
  instance: {
    get() {
      return this.modelInstance;
    },
  },
  close: {
    get() {
      return this.orm.close;
    },
  },
  closeAsync: {
    get() {
      return Promise.promisify(this.orm.close);
    },
  },
});
 
CassandraClient.prototype.uuid = CassandraClient.uuid;
CassandraClient.prototype.uuidFromString = CassandraClient.uuidFromString;
CassandraClient.prototype.uuidFromBuffer = CassandraClient.uuidFromBuffer;
CassandraClient.prototype.timeuuid = CassandraClient.timeuuid;
CassandraClient.prototype.timeuuidFromDate = CassandraClient.timeuuidFromDate;
CassandraClient.prototype.timeuuidFromString = CassandraClient.timeuuidFromString;
CassandraClient.prototype.timeuuidFromBuffer = CassandraClient.timeuuidFromBuffer;
CassandraClient.prototype.maxTimeuuid = CassandraClient.maxTimeuuid;
CassandraClient.prototype.minTimeuuid = CassandraClient.minTimeuuid;
 
CassandraClient.prototype._translateFileNameToModelName = CassandraClient._translateFileNameToModelName;
 
module.exports = CassandraClient;