import Fluxxor from 'fluxxor'; import _ from 'lodash'; var BusinessStore = Fluxxor.createStore({ actions: { RECEIVE_MANAGED_BUSINESSES: 'onReceiveManagedBusinesses' }, initialize() { this.businesses = {}; this.managedIds = {}; }, onReceiveManagedBusinesses({ userId, businesses }) { this.businesses = _.assign({}, this.businesses, _.indexBy(businesses, 'id')); this.managedIds[userId] = _.pluck(businesses, 'id'); this.emit('change'); }, getById(id) { return this.businesses[id]; }, getManaged(userId) { return _.map(this.managedIds[userId], this.getById, this); } }); module.exports = BusinessStore;
.spread(function (role, _heroes, _items) { heroes = _heroes; bag = _items; role.team = _.pluck(heroes, "id"); return role; });
subscribe: function (req, records, contexts) { // If a request object was sent, get its socket, otherwise assume a socket was sent. var socket = sails.sockets.parseSocket(req); if (!socket) { return sails.log.warn('`Model.subscribe()` called by a non-socket request. Only requests originating from a connected socket may be subscribed. Ignoring...'); } var self = this; // Subscribe to class room to hear about new records if (!records) { sails.log.warn('Missing or empty second argument `records`. API is `.subscribe(request, records [, contexts])`.'); STRINGFILE.logDeprecationNotice( 'Model.subscribe(socket, null, ...)', STRINGFILE.get('links.docs.sockets.pubsub'), sails.log.debug) && STRINGFILE.logUpgradeNotice(STRINGFILE.get('upgrade.classrooms'), [], sails.log.debug); this.watch(req); return; } contexts = contexts || this.autosubscribe; if (!contexts) { sails.log.warn("`subscribe` called without context on a model with autosubscribe:false. No action will be taken."); return; } if (contexts === true || contexts == '*') { contexts = this.getAllContexts(); } else if (sails.util.isString(contexts)) { contexts = [contexts]; } // If the subscribing socket is using the legacy (v0.9.x) socket SDK (sails.io.js), // always subscribe the client to the `legacy_v0.9` context. // if (sails.config.sockets['backwardsCompatibilityFor0.9SocketClients'] && socket.handshake) { // var sdk = app.getSDKMetadata(socket.handshake); // var isLegacySocketClient = sdk.version === '0.9.0'; // if (isLegacySocketClient) { // contexts.push('legacy_v0.9'); // } // } // Subscribe to model instances records = self.pluralize(records); var ids = _.pluck(records, this.primaryKey); _.each(ids,function (id) { _.each(contexts, function(context) { sails.log.silly( 'Subscribed to the ' + self.globalId + ' with id=' + id + '\t(room :: ' + self.room(id, context) + ')' ); sails.sockets.join( socket, self.room(id, context) ); }); }); },
/** * Get the Rectangles representing the geohash grid * * @return {LatLngRectangles[]} */ _getDataRectangles() { if (!this._geoJson) return []; return _.pluck(this._geoJson.features, 'properties.rectangle'); };
getExtensions: function () { return _.flatten(_.union(_.pluck(this.handlers, 'extensions'), defaults.extensions)); },
var _updateFiles = function(context) { if(!context) { _updateFiles('client'); _updateFiles('server'); return; } var enabledmods = _.sortBy( _.filter( _.toArray(installed) ,function(mod) { return mod.enabled !== false && mod.context === context; } ) ,function(mod) { return mod.priority } ); // mods/pamm/uimodlist jsAddLogMessage("Processing " + context + " scenes", 4); var globalmodlist = []; var scenemodlist = {}; var scenes = context === 'server' ? [] : ["armory", "building_planets", "connect_to_game", "game_over", "icon_atlas", "live_game", "live_game_econ", "live_game_hover", "load_planet", "lobby", "matchmaking", "new_game", "replay_browser", "server_browser", "settings", "social", "special_icon_atlas", "start", "system_editor", "transit"] // deprecated _.each(scenes, function(scene) { scenemodlist[scene] = []; }); // temp fix for PA Stats => all scenes must be initialized by empty an array _.each(enabledmods, function(mod) { // deprecated global_mod_list at modinfo root if(mod.global_mod_list) { globalmodlist = globalmodlist.concat(mod.global_mod_list); } // deprecated scenes at modinfo root _.each(scenes, function(scene) { if(mod[scene]) { if(!scenemodlist[scene]) scenemodlist[scene] = [] scenemodlist[scene] = scenemodlist[scene].concat(mod[scene]); } }); // scenes if(mod.scenes) { _.each(mod.scenes, function(modlist, scene) { if(scene === "global_mod_list") { globalmodlist = globalmodlist.concat(modlist); } else { if(!scenemodlist[scene]) scenemodlist[scene] = [] scenemodlist[scene] = scenemodlist[scene].concat(modlist); } }); } }); var pamm_path, uimodlist; var mount_order = _.pluck( enabledmods,'identifier'); // may be modified for server mods switch ( context ) { case 'server': pamm_path = paths.pamm_server; // server version of ui_mod_list.js loads local client copy of ui_mod_list_for_server.js then merges server scenes into client scenes uimodlist = "var global_server_mod_list = " + JSON.stringify(globalmodlist, null, 4) + ";\n\nvar scene_server_mod_list = " + JSON.stringify(scenemodlist, null, 4) + ";\n\ntry { \n\nloadScript('coui://ui/mods/ui_mod_list_for_server.js');\n\ntry { global_mod_list = _.union( global_mod_list, global_server_mod_list ) } catch (e) { console.log(e); } ;\n\ntry { _.forOwn( scene_server_mod_list, function( value, key ) { if ( scene_mod_list[ key ] ) { scene_mod_list[ key ] = _.union( scene_mod_list[ key ], value ) } else { scene_mod_list[ key ] = value } } ); } catch (e) { console.log(e); } \n\n\} catch (e) {\n\nconsole.log(e);\n\nvar global_mod_list = global_server_mod_list;\n\nvar scene_mod_list = scene_server_mod_list;\n\n}\n\n"; // for server mods we only enable the PA Server Mod Manager if there are other server mods enabled that use scenes var sceneCount = globalmodlist.length + _.flatten( _.values( scenemodlist ) ).length; jsAddLogMessage( 'Found ' + sceneCount + ' server mod scenes', 4); if ( sceneCount == 0 ) { jsAddLogMessage( 'Disabling PA Server Mod Manager as not needed', 4); mount_order = _.without( mount_order, PAMM_SERVER_MOD_IDENTIFIER ); } else { jsAddLogMessage( 'Enabling PA Server Mod Manager', 4); } break; case 'client': pamm_path = paths.pamm; uimodlist = "var global_mod_list = " + JSON.stringify(globalmodlist, null, 4) + ";\n\nvar scene_mod_list = " + JSON.stringify(scenemodlist, null, 4) + ";"; // extra copy of client ui_mod_list.js that can be loaded by server version of ui_mod_list.js for merging fs.writeFileSync( path.join(pamm_path, 'ui/mods/ui_mod_list_for_server.js' ) ,uimodlist ,{ encoding: 'utf8' } ); // mods/pamm/modlist jsAddLogMessage("Writing mods_list.json", 4); fs.writeFileSync( path.join(pamm_path, 'ui/mods/mods_list.json') ,JSON.stringify(installed, null, 4) ,{ encoding: 'utf8' } ); break; default: jsAddLogMessage("Unknown context " + context, 4); } // some error checking if ( ! pamm_path ) { return; } if ( uimodlist ) { jsAddLogMessage("Writing " + context + " ui_mod_list.js", 4); fs.writeFileSync( path.join(pamm_path, 'ui/mods/ui_mod_list.js' ) ,uimodlist ,{ encoding: 'utf8' } ); } // mods/mods.json jsAddLogMessage("Writing " + context + " mods.json", 4); var mods = { mount_order:mount_order }; fs.writeFileSync( path.join(pa.modspath[context], 'mods.json') ,JSON.stringify(mods, null, 4) ,{ encoding: 'utf8' } ); };
.pipe(concat(function(files) { callback(bowerDeps.js .concat(_.pluck(files, 'path')) .concat(htmlFiles) .concat(specFiles)); }));
.then(function (results) { // here convert the params and headers from array to map var headers = _.zipObject(_.pluck(results.headers, 'name'), _.pluck(results.headers, 'value')); var params = _.zipObject(_.pluck(results.params, 'name'), _.pluck(results.params, 'value')); var body = results.body; var path = results.path; var key; if (self.cache) { key = self.config.rest_method + urlS + path + JSON.stringify(headers) + JSON.stringify(params) + body; } if (self.cache) { var v = self.cache.get(key); if (v) { return fulfill(v); } } // to check any option visit // https://github.com/request/request#requestoptions-callback var rpOptions = { method: self.config.rest_method, uri: url.parse(url.resolve(urlS, path)), headers: headers, timeout: timeout || 5000, transform: function (body, resp) { var msg; var data = { results: {} }; if (resp.statusCode !== self.config.rest_resp_status_code) { msg = 'Invalid response status code: [' + resp.statusCode + '] Expected: [' + self.config.rest_resp_status_code + ']'; self._logFailedRequestDetails(msg, null, resp); throw new Error(msg); } // TODO: change this once we support xml resp or text resp var json; try { json = JSON.parse(body); } catch (e) { msg = 'Error while parsing body as JSON. Details: ' + e.message; self._logFailedRequestDetails(msg, e, resp); throw new Error(msg); } // extract subset of the data only if user specified jsonpath expression if (self.config.rest_resp_restriction_path && self.config.rest_resp_restriction_path !== '') { try { data.results = jsonpath.query(json, self.config.rest_resp_restriction_path); } catch (e) { msg = 'Error while executing the JSONPath expression. Details: ' + e.message; self._logFailedRequestDetails(msg, e, resp); throw new Error(msg); } } else { data.results = json; } if (self.cache) { self.cache.set(key, data, maxAge); } return data; } }; if (username && password) { rpOptions.auth = { // as they might be encrypted make sure to call populateParameters username: self.config.datasource.datasourceClazz.populateParameters('${username}'), password: self.config.datasource.datasourceClazz.populateParameters('${password}'), sendImmediately: false }; } if (self.config.rest_method === 'GET') { rpOptions.qs = params; } else if (self.config.rest_method === 'POST') { rpOptions.body = body; // WARNING: do not set rpOptions.json = true/false; even for json content // rather ask user to set correct Content-Type: application/json header } rp(rpOptions).then(function (resp) { fulfill(resp); }).catch(function (err) { var msg = 'Rest request failed: ' + JSON.stringify(rpOptions.uri, null, ' ') + '.\nDetails: ' + err.message; self._logFailedRequestDetails(msg, err, null); reject(new Error(msg)); }); });
sails.sockets.subscribers = function(roomName) { return _.pluck(sails.io.sockets.clients(roomName), 'id'); };
return Post.forge({id: newPost.id}).fetch({withRelated: ['tags'], transacting: options.transacting}).then(function (post) { var tagOps = []; // remove all existing tags from the post // _.omit(options, 'query') is a fix for using bookshelf 0.6.8 // (https://github.com/tgriesser/bookshelf/issues/294) tagOps.push(post.tags().detach(null, _.omit(options, 'query'))); if (_.isEmpty(self.myTags)) { return Promise.all(tagOps); } return ghostBookshelf.collection('Tags').forge().query('whereIn', 'name', _.pluck(self.myTags, 'name')).fetch(options).then(function (existingTags) { var doNotExist = [], createAndAttachOperation; existingTags = existingTags.toJSON(); doNotExist = _.reject(self.myTags, function (tag) { return _.any(existingTags, function (existingTag) { return existingTag.name === tag.name; }); }); // Create tags that don't exist and attach to post _.each(doNotExist, function (tag) { createAndAttachOperation = ghostBookshelf.model('Tag').add({name: tag.name}, options).then(function (createdTag) { createdTag = createdTag.toJSON(); // _.omit(options, 'query') is a fix for using bookshelf 0.6.8 // (https://github.com/tgriesser/bookshelf/issues/294) return post.tags().attach(createdTag.id, _.omit(options, 'query')); }); tagOps.push(createAndAttachOperation); }); // attach the tags that already existed _.each(existingTags, function (tag) { // _.omit(options, 'query') is a fix for using bookshelf 0.6.8 // (https://github.com/tgriesser/bookshelf/issues/294) tagOps.push(post.tags().attach(tag.id, _.omit(options, 'query'))); }); return Promise.all(tagOps); }); });
.end(function(err, res){ should.not.exist(err); var body = JSON.parse(res.text); _.pluck(body.people, "name").should.eql(["Wally", "Dilbert"]); done(); });
appStore.getProducts().map(product => { let latestPrices = _.pluck(product.stores, 'latestPrice.amount'); expect(latestPrices).to.eql([12, 13, 100, 130.7, Number.MAX_VALUE, Number.MAX_VALUE]); });
appStore.getProducts().map(product => { let priceChanges = _.pluck(product.stores, 'priceChangePercentage'); expect(priceChanges).to.eql([-14, 18, 0, 0, 0, 0]); });
appStore.getProducts().map(product => { let priceChanges = _.pluck(product.stores, 'priceChangeNumeric'); expect(priceChanges).to.eql([-2, 2, 0, 0, Number.MAX_VALUE, 0]); });
.then(function (resp) { return _.pluck(resp.hits.hits, '_id'); });
* * @param object The song object */ remove(song) { this.state.songs = _.difference(this.state.songs, [song]); }, /** * Like a bunch of songs. * * @param array An array of songs to like */ like(songs, cb = null) { this.state.songs = _.union(this.state.songs, songs); http.post('interaction/batch/like', { ids: _.pluck(songs, 'id') }, data => { _.each(songs, song => song.liked = true); if (cb) { cb(); } }); }, /** * Unlike a bunch of songs. * * @param array An array of songs to unlike */ unlike(songs, cb = null) { this.state.songs = _.difference(this.state.songs, songs);
__handleChangeEventOccur: function (selected) { this.props.onChange(selected.id || _.pluck(selected, 'id')); }
}).then(function(completions) { lessons = completions && completions.length ? _.pluck(completions, 'LessonId') : []; percentage = completions && completions.length ? Math.round((completions.length/numQuizzes)*100) : 0; deferred.resolve([lessons, percentage]); }).catch(function(err) {
}).then(function(resp) { _passes = resp; _mockPassFilenames = _.pluck(resp, 'filename'); console.log('GOT PASSES', resp); done(); });
headers: function (item) { var headers = item.request.header; return _.map(_.object(_.pluck(headers, 'key'), _.pluck(headers, 'value')), function (value, key) { return key + ': ' + value; }).join('\n'); },
module.exports = function query ( /* classifier|tuples, data|criteria [, criteria] */ ) { // Embed an `INDEX_IN_ORIG_DATA` for each tuple to remember its original index // within `data`. At the end, we'll lookup the `INDEX_IN_ORIG_DATA` for each tuple // and expose it as part of our results. var INDEX_IN_ORIG_DATA = '.(ørigindex)'; var tuples, classifier, data, criteria; // If no classifier is provided, and data was specified as an array // instead of an object, infer tuples from the array if (_.isArray(arguments[0]) && !arguments[2]) { tuples = arguments[0]; criteria = arguments[1]; } // If all three arguments were supplied: // get tuples of type `classifier` (i.e. SELECT * FROM __________) // and clone 'em. else { classifier = arguments[0]; data = arguments[1]; criteria = arguments[2]; tuples = data[classifier]; } // Clone tuples to avoid dirtying things up tuples = _.cloneDeep(tuples); // Embed `INDEX_IN_ORIG_DATA` in each tuple _.each(tuples, function(tuple, i) { tuple[INDEX_IN_ORIG_DATA] = i; }); // Ensure criteria object exists criteria = criteria || {}; // Query and return result set using criteria tuples = _where(tuples, criteria.where); tuples = _sort(tuples, criteria.sort); tuples = _skip(tuples, criteria.skip); tuples = _limit(tuples, criteria.limit); tuples = _select(tuples, criteria.select); // TODO: // tuples = _groupBy(tuples, criteria.groupBy); // Grab the INDEX_IN_ORIG_DATA from each matched tuple // this is typically used to update the tuples in the external source data. var originalIndices = _.pluck(tuples, INDEX_IN_ORIG_DATA); // Remove INDEX_IN_ORIG_DATA from each tuple-- // it is no longer needed. _.each(tuples, function(tuple) { delete tuple[INDEX_IN_ORIG_DATA]; }); return { results: tuples, indices: originalIndices }; };
var values = _.map(series, function (ser) { return _.pluck(ser.data, 'y'); });
loyaltyPlugin.prototype.processData = function(rows, cb ) { var idsonly = lodash.pluck(rows, 'uid'); cb(null, lodash.without(idsonly, 0)); }
indexer.addBatchToIndex = function (indexes, batch, batchOptions, callbacky) { var salt = 0; if (!_.isArray(batch) && _.isPlainObject(batch)) { batch = [batch]; } //generate IDs if none are present and stringify numeric IDs batch.map(function (doc) { if (!doc.id) doc.id = (++salt) + '-' + hash(doc); doc.id = doc.id + ''; // stringify ID }); deleter.deleteBatch(_.pluck(batch, 'id'), indexes, function (err) { var dbInstructions = []; batch.forEach(function (doc) { var docIndexEntries = []; if (err) log.warn(err); if (!_.isPlainObject(doc)) return callbacky(new Error('Malformed document'), {}); doc = removeInvalidFields(doc); batchOptions = _.defaults(batchOptions, options); if (batchOptions.fieldsToStore == 'all') batchOptions.fieldsToStore = Object.keys(doc); log.info('indexing ' + doc.id); docIndexEntries.push({ type: 'put', key: 'DOCUMENT○' + doc.id + '○', value: _.pick(doc, batchOptions.fieldsToStore) }); var freqsForComposite = []; //put document frequencies in here _.forEach(doc, function (field, fieldName) { var fieldOptions = _.defaults(_.find(batchOptions.fieldOptions, 'fieldName', fieldName) || {}, batchOptions.defaultFieldOptions); if (fieldName == 'id') fieldOptions.stopwords = ''; // because you cant run stopwords on id field else fieldOptions.stopwords = batchOptions.stopwords; if (_.isArray(field)) field = field.join(' '); // make filter fields searchable var v = tv.getVector(field + '', { separator: batchOptions.separator, stopwords: fieldOptions.stopwords, nGramLength: fieldOptions.nGramLength }); v.push(['*', 1]); //can do wildcard searh on this field var freq = tf.getTermFrequency(v, { scheme: 'doubleLogNormalization0.5', weight: fieldOptions.weight }); if (fieldOptions.searchable) freqsForComposite.push(freq); var deleteKeys = []; if (fieldOptions.fieldedSearch) { freq.forEach(function (item) { batchOptions.filters.forEach(function (filter) { _.forEach(doc[filter], function (filterKey) { docIndexEntries.push({ type: 'put', key: 'TF○' + fieldName + '○' + item[0] + '○' + filter + '○' + filterKey, value: [doc.id] }); docIndexEntries.push({ type: 'put', key: 'RI○' + fieldName + '○' + item[0] + '○' + filter + '○' + filterKey, value: [[item[1], doc.id]] }); }); }); docIndexEntries.push({ type: 'put', key: 'TF○' + fieldName + '○' + item[0] + '○○', value: [doc.id] }); docIndexEntries.push({ type: 'put', key: 'RI○' + fieldName + '○' + item[0] + '○○', value: [[item[1], doc.id]] }); }); }; }); //generate * field _(freqsForComposite) .flatten() .sort() .reduce(function (prev, item) { if (!prev[0]) prev.push(item); else if (item[0] == _.last(prev)[0]) { _.last(prev)[1] = _.last(prev)[1] + item[1]; } else prev.push(item); return prev; }, []) .forEach(function (item) { batchOptions.filters.forEach(function (filter) { _.forEach(doc[filter], function (filterKey) { docIndexEntries.push({ type: 'put', key: 'TF○*○' + item[0] + '○' + filter + '○' + filterKey, value: [doc.id] }); docIndexEntries.push({ type: 'put', key: 'RI○*○' + item[0] + '○' + filter + '○' + filterKey, value: [[item[1], doc.id]] }); }); }); docIndexEntries.push({ type: 'put', key: 'TF○*○' + item[0] + '○○', value: [doc.id] }); docIndexEntries.push({ type: 'put', key: 'RI○*○' + item[0] + '○○', value: [[item[1], doc.id]] }); }); docIndexEntries.push({ type: 'put', key: 'DELETE-DOCUMENT○' + doc.id, value: _.pluck(docIndexEntries, 'key') }); dbInstructions.push(docIndexEntries); }); dbInstructions.push({ type: 'put', key: 'DOCUMENT-COUNT', value: batch.length }); dbInstructions = _(dbInstructions) .flatten() .sortBy('key') .reduce(function (prev, item) { if (item.key.substring(0, 6) == 'DELETE') prev.push(item); else if (item.key.substring(0, 8) == 'DOCUMENT') prev.push(item); else if (item.key.substring(0, 2) == 'RI') { if (item.key == _.last(prev).key) _.last(prev).value.push(item.value[0]); else prev.push(item); } else if (item.key.substring(0, 2) == 'TF') { if (item.key == _.last(prev).key) _.last(prev).value = _.last(prev).value.concat(item.value); else prev.push(item); } return prev; }, []); async.map( dbInstructions, function (item, callback) { indexes.get(item.key, function (err, val) { if (item.key.substring(0, 2) == 'TF') { if (val) item.value = item.value.concat(val); item.value = item.value.sort(); } else if (item.key.substring(0, 2) == 'RI') { if (val) item.value = item.value.concat(val); item.value = item.value.sort(function (a, b) { return b[0] - a[0]; }); } else if (item.key == 'DOCUMENT-COUNT') { if (val) item.value = +val + +(item.value); } return callback(null, item); }); }, function (err, mergeDbInstructions) { // console.log(JSON.stringify(mergeDbInstructions, null, 2)) indexes.batch(mergeDbInstructions, function (err) { if (err) log.warn('Ooops!', err); else log.info('batch indexed!'); return callbacky(null); }); }); }); };
getTypes: function () { return _.flatten(_.union(_.pluck(this.handlers, 'types'), defaults.types)); },
batch.forEach(function (doc) { var docIndexEntries = []; if (err) log.warn(err); if (!_.isPlainObject(doc)) return callbacky(new Error('Malformed document'), {}); doc = removeInvalidFields(doc); batchOptions = _.defaults(batchOptions, options); if (batchOptions.fieldsToStore == 'all') batchOptions.fieldsToStore = Object.keys(doc); log.info('indexing ' + doc.id); docIndexEntries.push({ type: 'put', key: 'DOCUMENT○' + doc.id + '○', value: _.pick(doc, batchOptions.fieldsToStore) }); var freqsForComposite = []; //put document frequencies in here _.forEach(doc, function (field, fieldName) { var fieldOptions = _.defaults(_.find(batchOptions.fieldOptions, 'fieldName', fieldName) || {}, batchOptions.defaultFieldOptions); if (fieldName == 'id') fieldOptions.stopwords = ''; // because you cant run stopwords on id field else fieldOptions.stopwords = batchOptions.stopwords; if (_.isArray(field)) field = field.join(' '); // make filter fields searchable var v = tv.getVector(field + '', { separator: batchOptions.separator, stopwords: fieldOptions.stopwords, nGramLength: fieldOptions.nGramLength }); v.push(['*', 1]); //can do wildcard searh on this field var freq = tf.getTermFrequency(v, { scheme: 'doubleLogNormalization0.5', weight: fieldOptions.weight }); if (fieldOptions.searchable) freqsForComposite.push(freq); var deleteKeys = []; if (fieldOptions.fieldedSearch) { freq.forEach(function (item) { batchOptions.filters.forEach(function (filter) { _.forEach(doc[filter], function (filterKey) { docIndexEntries.push({ type: 'put', key: 'TF○' + fieldName + '○' + item[0] + '○' + filter + '○' + filterKey, value: [doc.id] }); docIndexEntries.push({ type: 'put', key: 'RI○' + fieldName + '○' + item[0] + '○' + filter + '○' + filterKey, value: [[item[1], doc.id]] }); }); }); docIndexEntries.push({ type: 'put', key: 'TF○' + fieldName + '○' + item[0] + '○○', value: [doc.id] }); docIndexEntries.push({ type: 'put', key: 'RI○' + fieldName + '○' + item[0] + '○○', value: [[item[1], doc.id]] }); }); }; }); //generate * field _(freqsForComposite) .flatten() .sort() .reduce(function (prev, item) { if (!prev[0]) prev.push(item); else if (item[0] == _.last(prev)[0]) { _.last(prev)[1] = _.last(prev)[1] + item[1]; } else prev.push(item); return prev; }, []) .forEach(function (item) { batchOptions.filters.forEach(function (filter) { _.forEach(doc[filter], function (filterKey) { docIndexEntries.push({ type: 'put', key: 'TF○*○' + item[0] + '○' + filter + '○' + filterKey, value: [doc.id] }); docIndexEntries.push({ type: 'put', key: 'RI○*○' + item[0] + '○' + filter + '○' + filterKey, value: [[item[1], doc.id]] }); }); }); docIndexEntries.push({ type: 'put', key: 'TF○*○' + item[0] + '○○', value: [doc.id] }); docIndexEntries.push({ type: 'put', key: 'RI○*○' + item[0] + '○○', value: [[item[1], doc.id]] }); }); docIndexEntries.push({ type: 'put', key: 'DELETE-DOCUMENT○' + doc.id, value: _.pluck(docIndexEntries, 'key') }); dbInstructions.push(docIndexEntries); });
publish: function (models, eventName, context, data, req) { var self = this; // If the event name is an object, assume we're seeing `publish(models, data, req)` if (typeof eventName === 'object') { req = context; context = null; data = eventName; eventName = null; } // Default to the event name being the model identity if (!eventName) { eventName = this.identity; } // If the context is an object, assume we're seeing `publish(models, eventName, data, req)` if (typeof context === 'object' && context !== null) { req = data; data = context; context = null; } // Default to using the message context if (!context) { sails.log.warn('`Model.publish` should specify a context; defaulting to "message". Try `Model.message` instead?'); context = 'message'; } // If a request object was sent, get its socket, otherwise assume a socket was sent. var socketToOmit = (req && req.socket ? req.socket : req); // If no models provided, publish to the class room if (!models) { STRINGFILE.logDeprecationNotice( 'Model.publish(null, ...)', STRINGFILE.get('links.docs.sockets.pubsub'), sails.log.debug) && STRINGFILE.logUpgradeNotice(STRINGFILE.get('upgrade.classrooms'), [], sails.log.debug); sails.log.silly('Published ', eventName, ' to ', self.classRoom()); self.broadcast( self.classRoom(), eventName, data, socketToOmit ); return; } // Otherwise publish to each instance room else { models = this.pluralize(models); var ids = _.pluck(models, this.primaryKey); if ( ids.length === 0 ) { sails.log.warn('Can\'t publish a message to an empty list of instances-- ignoring...'); } _.each(ids,function eachInstance (id) { var room = self.room(id, context); sails.log.silly("Published ", eventName, " to ", room); self.broadcast( room, eventName, data, socketToOmit ); // Also broadcasts a message to the legacy instance room (derived by // using the `legacy_v0.9` context). // Uses traditional eventName === "message". // Uses traditional message format. if (sails.config.sockets['backwardsCompatibilityFor0.9SocketClients']) { var legacyRoom = self.room(id, 'legacy_v0.9'); var legacyMsg = _.cloneDeep(data); legacyMsg.model = self.identity; if (legacyMsg.verb === 'created') { legacyMsg.verb = 'create'; } if (legacyMsg.verb === 'updated') { legacyMsg.verb = 'update'; } if (legacyMsg.verb === 'destroyed') { legacyMsg.verb = 'destroy'; } self.broadcast( legacyRoom, 'message', legacyMsg, socketToOmit ); } }); } },
.map(function (series) { return _.pluck(series, '_input.z'); })
_.each(changes, function(val, key) { // If value wasn't changed, do nothing if (val == previous[key]) return; // Find an association matching this attribute var association = _.find(this.associations, {alias: key}); // If the attribute isn't an assoctiation, return if (!association) return; // Get the associated model class var ReferencedModel = sails.models[association.type == 'model' ? association.model : association.collection]; // Bail if this attribute isn't in the model's schema if (association.type == 'model') { var previousPK = _.isObject(previous[key]) ? previous[key][ReferencedModel.primaryKey] : previous[key]; var newPK = _.isObject(val) ? val[this.primaryKey] : val; if (previousPK == newPK) return; // Get the inverse association definition, if any reverseAssociation = _.find(ReferencedModel.associations, {collection: this.identity, via: key}) || _.find(ReferencedModel.associations, {model: this.identity, via: key}); if (!reverseAssociation) {return;} // If this is a to-many association, do publishAdd or publishRemove as necessary // on the other side if (reverseAssociation.type == 'collection') { // If there was a previous value, alert the previously associated model if (previous[key]) { ReferencedModel.publishRemove(previousPK, reverseAssociation.alias, id, req, {noReverse:true}); } // If there's a new value (i.e. it's not null), alert the newly associated model if (val) { ReferencedModel.publishAdd(newPK, reverseAssociation.alias, id, req, {noReverse:true}); } } // Otherwise do a publishUpdate else { var pubData = {}; // If there was a previous association, notify it that it has been nullified if (previous[key]) { pubData[reverseAssociation.alias] = null; ReferencedModel.publishUpdate(previousPK, pubData, req, {noReverse:true}); } // If there's a new association, notify it that it has been linked if (val) { pubData[reverseAssociation.alias] = id; ReferencedModel.publishUpdate(newPK, pubData, req, {noReverse:true}); } } } else { // Get the reverse association definition, if any reverseAssociation = _.find(ReferencedModel.associations, {collection: this.identity, via: key}) || _.find(ReferencedModel.associations, {model: this.identity, alias: association.via}); if (!reverseAssociation) {return;} // If we can't get the previous PKs (b/c previous isn't populated), bail if (typeof(previous[key]) == 'undefined') return; // Get the previous set of IDs var previousPKs = _.pluck(previous[key], ReferencedModel.primaryKey); // Get the current set of IDs var updatedPKs = _.map(val, function(_val) { if (_.isObject(_val)) { return _val[ReferencedModel.primaryKey]; } else { return _val; } }); // Find any values that were added to the collection var addedPKs = _.difference(updatedPKs, previousPKs); // Find any values that were removed from the collection var removedPKs = _.difference(previousPKs, updatedPKs); // If this is a to-many association, do publishAdd or publishRemove as necessary // on the other side if (reverseAssociation.type == 'collection') { // Alert any removed models _.each(removedPKs, function(pk) { ReferencedModel.publishRemove(pk, reverseAssociation.alias, id, req, {noReverse:true}); }); // Alert any added models _.each(addedPKs, function(pk) { ReferencedModel.publishAdd(pk, reverseAssociation.alias, id, req, {noReverse:true}); }); } // Otherwise do a publishUpdate else { // Alert any removed models _.each(removedPKs, function(pk) { var pubData = {}; pubData[reverseAssociation.alias] = null; ReferencedModel.publishUpdate(pk, pubData, req, {noReverse:true}); }); // Alert any added models _.each(addedPKs, function(pk) { var pubData = {}; pubData[reverseAssociation.alias] = id; ReferencedModel.publishUpdate(pk, pubData, req, {noReverse:true}); }); } } }, this);
/** * Update song data. * * @param {Array.<Object>} songs An array of song * @param {Object} data * @param {?Function} successCb * @param {?Function} errorCb */ update(songs, data, successCb = null, errorCb = null) { if (!userStore.current.is_admin) { return; } http.put('songs', { data, songs: _.pluck(songs, 'id'), }, response => { response.data.forEach(song => { this.syncUpdatedSong(song); }); if (successCb) { successCb(); } }, () => { if (errorCb) { errorCb(); } }); },