UNPKG

apollo-passport-rethinkdbdash

Version:
479 lines (400 loc) 15.8 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); require('regenerator-runtime/runtime'); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** Class implementing the Apollo Passport DBDriver interface */ var RethinkDBDashDriver = function () { /** * Returns a DBDriver instance (for use by Apollo Passport). Parameters are * driver-specific and should be clearly specificied in the README. * This documents the RethinkDBDash DBDriver specifically, although some * *options* are relevant for all drivers. * * @param {rethinkdbdash} r, e.g. var r = require('rethinkdbdash')(); * * @param {string} options.userTableName default: 'users' * @param {string} options.configTableName default: 'apolloPassportConfig' * @param {string} options.dbName default: current database */ function RethinkDBDashDriver(r) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, RethinkDBDashDriver); this.r = r; this.userTableName = options.userTableName || 'users'; this.configTableName = options.configTableName || 'apolloPassportConfig'; this.dbName = options.dbName || r._poolMaster && r._poolMaster._options.db; this.db = r.db(this.dbName); this.readySubs = []; // don't await the init, run async if (options.init !== false) this._init(); } /** * Internal method, documented for benefit of driver authors. Most important * is to call fetchConfig() (XXX unfinished), but may also assert that all * tables exist, and run ready callbacks. */ _createClass(RethinkDBDashDriver, [{ key: '_init', value: function _init() { return regeneratorRuntime.async(function _init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return regeneratorRuntime.awrap(this._assertTableExists(this.userTableName)); case 2: this.users = this.db.table(this.userTableName); _context.next = 5; return regeneratorRuntime.awrap(this._assertTableExists(this.configTableName)); case 5: this.config = this.db.table(this.configTableName); this.initted = true; while (this.readySubs.length) { this.readySubs.shift().call(); } case 8: case 'end': return _context.stop(); } } }, null, this); } /** * Internal method, documented for benefit of driver authors. An awaitable * promise that returns if the driver is ready (or when it becomes ready). */ }, { key: '_ready', value: function _ready() { var _this = this; return new Promise(function (resolve) { if (_this.initted) resolve();else _this.readySubs.push(resolve); }); } ////////////////// // DB UTILITIES // ////////////////// /** * Internal method, documented for benefit of driver authors. Asserts (and * awaits) that the given table name exists. This is a convenience for the * user but with RethinkDB **there is no safe way to do this** other than * creating the table in advance (outside of the app). It's fine if the * table is created with only one app instance running, which is usually * the case for initial setup. * * @param {string} name - the name of the table to assert */ }, { key: '_assertTableExists', value: function _assertTableExists(name) { return regeneratorRuntime.async(function _assertTableExists$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.prev = 0; _context2.next = 3; return regeneratorRuntime.awrap(this.db.tableCreate(name).run()); case 3: _context2.next = 9; break; case 5: _context2.prev = 5; _context2.t0 = _context2['catch'](0); if (!(_context2.t0.msg !== 'Table `' + this.dbName + '.' + name + '` already exists.')) { _context2.next = 9; break; } throw _context2.t0; case 9: case 'end': return _context2.stop(); } } }, null, this, [[0, 5]]); } ////////////////// // CONFIG TABLE // ////////////////// /** * Retrieves _all_ configuration from the database. * @return {object} A nested dictionary arranged by type, i.e. * * ```js * { * service: { // type * facebook: { // id * ...data // value (de-JSONified if from non-document DB) * } * } * } * ``` */ }, { key: 'fetchConfig', value: function fetchConfig() { var results, out; return regeneratorRuntime.async(function fetchConfig$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return regeneratorRuntime.awrap(this._ready()); case 2: _context3.next = 4; return regeneratorRuntime.awrap(this.config.run()); case 4: results = _context3.sent; out = {}; results.forEach(function (row) { if (!out[row.type]) out[row.type] = {}; out[row.type][row.id] = row; }); return _context3.abrupt('return', out); case 8: case 'end': return _context3.stop(); } } }, null, this); } /** * Creates or updates the key with the given value. * NoSQL databases can store the destructured value as part of the record. * Fixed-schema databases should JSON-encode the 'value' column. * * @param {string} type - e.g. "service" * @param {string} id - e.g. "facebook" * @param {object} value - e.g. { id: 1, ...profile } */ }, { key: 'setConfigKey', value: function setConfigKey(type, id, value) { return regeneratorRuntime.async(function setConfigKey$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return regeneratorRuntime.awrap(this._ready()); case 2: _context4.next = 4; return regeneratorRuntime.awrap(this.config.insert(_extends({ type: type, id: id }, value))); case 4: case 'end': return _context4.stop(); } } }, null, this); } /////////// // USERS // /////////// /** * Given a user record, save it to the database, and return its given id. * NoSQL databases should store the entire object, schema-based databases * should honor the 'emails' and 'services' keys and store as necessary * in another table. * * @param {object} user * * { * emails: [ { address: "me@me.com" } ], * services: [ { facebook: { id: 1, ...profile } } ] * ...anyOtherDataForUserRecordAtCreationTimeFromAppHooks * } * * @return {string} the id of the inserted user record */ }, { key: 'createUser', value: function createUser(user) { var id, result; return regeneratorRuntime.async(function createUser$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return regeneratorRuntime.awrap(this._ready()); case 2: id = user.id; _context5.next = 5; return regeneratorRuntime.awrap(this.users.insert(user)); case 5: result = _context5.sent; if (!id) id = result.generated_keys[0]; return _context5.abrupt('return', id); case 8: case 'end': return _context5.stop(); } } }, null, this); } /** * Fetches a user record by id. Schema-based databases should merge * appropriate user-data from e.g. `user_emails` and `user_services`. * * @param {string} id - the user record's id * * @return {object} user object in the same format expected by * {@link RethinkDBDashDriver#createUser}, or *null* if none found. */ }, { key: 'fetchUserById', value: function fetchUserById(userId) { return regeneratorRuntime.async(function fetchUserById$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return regeneratorRuntime.awrap(this._ready()); case 2: return _context6.abrupt('return', this.users.get(userId).run()); case 3: case 'end': return _context6.stop(); } } }, null, this); } /** * Given a single "email" param, returns the matching user record if one * exists, or null, otherwise. * * @param {string} email - the email address to search for, e.g. "me@me.com" * * @return {object} user object in the same format expected by * {@link RethinkDBDashDriver#createUser}, or *null* if none found. */ }, { key: 'fetchUserByEmail', value: function fetchUserByEmail(email) { var results; return regeneratorRuntime.async(function fetchUserByEmail$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; return regeneratorRuntime.awrap(this._ready()); case 2: _context7.next = 4; return regeneratorRuntime.awrap(this.users.filter(this.r.row('emails').contains(function (row) { return row('address').eq(email); })).limit(1).run()); case 4: results = _context7.sent; return _context7.abrupt('return', results[0] || null); case 6: case 'end': return _context7.stop(); } } }, null, this); } /** * Returns a user who has *either* a matching email address or matching * service record, or null, otherwise. * * @param {string} service - name of the service, e.g. "facebook" * @param {string} id - id of the service record, e.g. "152356242" * @param {string} email - the email address to search for, e.g. "me@me.com" * * @return {object} user object in the same format expected by * {@link RethinkDBDashDriver#createUser}, or *null* if none found */ }, { key: 'fetchUserByServiceIdOrEmail', value: function fetchUserByServiceIdOrEmail(service, id, email) { var results; return regeneratorRuntime.async(function fetchUserByServiceIdOrEmail$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.next = 2; return regeneratorRuntime.awrap(this._ready()); case 2: _context8.next = 4; return regeneratorRuntime.awrap(this.users.filter(this.r.or(this.r.row('services')(service)('id').eq(id).default(false), this.r.row('emails').contains({ address: email }).default(false))).limit(1).run()); case 4: results = _context8.sent; return _context8.abrupt('return', results[0] || null); case 6: case 'end': return _context8.stop(); } } }, null, this); } /** * Given a userId, ensures the user record contains the given email * address, and updates it with optional data. * * @param {string} userId - the id of the user to assert * @param {string} email - the email address to ensure exists * @param {object} data - optional, e.g. { type: 'work', verified: true } */ }, { key: 'assertUserEmailData', value: function assertUserEmailData(userId, email, data) { return regeneratorRuntime.async(function assertUserEmailData$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _context9.next = 2; return regeneratorRuntime.awrap(this._ready()); case 2: _context9.next = 4; return regeneratorRuntime.awrap(this.users.get(userId).update(function (row) { return { emails: row('emails').default([]).filter(row('emails').default([]).contains({ address: email }).not()).append(_extends({ address: email }, data)) }; })); case 4: case 'end': return _context9.stop(); } } }, null, this); } /** * Given a userId, ensure the user record contains the given service * record, and updates it with the given data. * * @param {string} userId - the id of the user to assert * @param {string} service - the name of the service, e.g. "facebook" * @param {object} data - e.g. { id: "4321", displayName: "John Sheppard" } */ }, { key: 'assertUserServiceData', value: function assertUserServiceData(userId, service, data) { return regeneratorRuntime.async(function assertUserServiceData$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: _context10.next = 2; return regeneratorRuntime.awrap(this._ready()); case 2: _context10.next = 4; return regeneratorRuntime.awrap(this.users.get(userId).update({ services: _defineProperty({}, service, data) })); case 4: case 'end': return _context10.stop(); } } }, null, this); } // Not sure if we need this anymore, since fetch*() functions return // normalized data. But let's see. }, { key: 'mapUserToServiceData', value: function mapUserToServiceData(user, service) { return user && user.services && user.services[service]; } }]); return RethinkDBDashDriver; }(); exports.default = RethinkDBDashDriver;