Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove underscore + modernize code base #248

Merged
merged 10 commits into from
Oct 21, 2019
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ node_modules
npm-debug.log
*.sublime-workspace
.vscode
.idea
.npm
9 changes: 9 additions & 0 deletions advices.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import './insert.js'
import './update.js'
import './remove.js'
import './upsert.js'
import './find.js'
import './findone.js'

// Load after all advices have been defined
import './users-compat.js'
23 changes: 23 additions & 0 deletions client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { CollectionHooks} from './collection-hooks.js'

CollectionHooks.getUserId = function getUserId () {
let userId

Tracker.nonreactive(() => {
userId = Meteor.userId && Meteor.userId()
})

if (userId == null) {
userId = CollectionHooks.defaultUserId
}

return userId
}

import './advices';

export {
CollectionHooks
};
154 changes: 48 additions & 106 deletions collection-hooks.js
Original file line number Diff line number Diff line change
@@ -1,84 +1,57 @@
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { EJSON } from 'meteor/ejson';
import { LocalCollection } from 'meteor/minimongo';

/* global Package Meteor Mongo LocalCollection CollectionHooks _ EJSON */
/* eslint-disable no-proto, no-native-reassign, no-global-assign */

// Relevant AOP terminology:
// Aspect: User code that runs before/after (hook)
// Advice: Wrapper code that knows when to call user code (aspects)
// Pointcut: before/after
const advices = {}

var advices = {}
var Tracker = (Package.tracker && Package.tracker.Tracker) || Package.deps.Deps
var publishUserId = Meteor.isServer && new Meteor.EnvironmentVariable()

CollectionHooks = {
export const CollectionHooks = {
defaults: {
before: {insert: {}, update: {}, remove: {}, upsert: {}, find: {}, findOne: {}, all: {}},
after: {insert: {}, update: {}, remove: {}, find: {}, findOne: {}, all: {}},
all: {insert: {}, update: {}, remove: {}, find: {}, findOne: {}, all: {}}
},
directEnv: new Meteor.EnvironmentVariable(),
directOp: function directOp (func) {
directOp(func) {
return this.directEnv.withValue(true, func)
},
hookedOp: function hookedOp (func) {
hookedOp(func) {
return this.directEnv.withValue(false, func)
}
}

CollectionHooks.getUserId = function getUserId () {
var userId

if (Meteor.isClient) {
Tracker.nonreactive(function () {
userId = Meteor.userId && Meteor.userId()
})
}

if (Meteor.isServer) {
try {
// Will throw an error unless within method call.
// Attempt to recover gracefully by catching:
userId = Meteor.userId && Meteor.userId()
} catch (e) {}

if (userId == null) {
// Get the userId if we are in a publish function.
userId = publishUserId.get()
}
}

if (userId == null) {
userId = CollectionHooks.defaultUserId
}

return userId
}

CollectionHooks.extendCollectionInstance = function extendCollectionInstance (self, constructor) {
// Offer a public API to allow the user to define aspects
// Example: collection.before.insert(func);
_.each(['before', 'after'], function (pointcut) {
_.each(advices, function (advice, method) {
['before', 'after'].forEach(function (pointcut) {
Object.entries(advices).forEach(function ([method, advice]) {
if (advice === 'upsert' && pointcut === 'after') return

Meteor._ensure(self, pointcut, method)
Meteor._ensure(self, '_hookAspects', method)

self._hookAspects[method][pointcut] = []
self[pointcut][method] = function (aspect, options) {
var len = self._hookAspects[method][pointcut].push({
aspect: aspect,
const len = self._hookAspects[method][pointcut].push({
aspect,
options: CollectionHooks.initOptions(options, pointcut, method)
})

return {
replace: function (aspect, options) {
replace(aspect, options) {
self._hookAspects[method][pointcut].splice(len - 1, 1, {
aspect: aspect,
options: CollectionHooks.initOptions(options, pointcut, method)
})
},
remove: function () {
remove() {
self._hookAspects[method][pointcut].splice(len - 1, 1)
}
}
Expand All @@ -92,31 +65,30 @@ CollectionHooks.extendCollectionInstance = function extendCollectionInstance (se
self.hookOptions = EJSON.clone(CollectionHooks.defaults)

// Wrap mutator methods, letting the defined advice do the work
_.each(advices, function (advice, method) {
var collection = Meteor.isClient || method === 'upsert' ? self : self._collection
Object.entries(advices).forEach(function ([method, advice]) {
const collection = Meteor.isClient || method === 'upsert' ? self : self._collection

// Store a reference to the original mutator method
var _super = collection[method]
const _super = collection[method]

Meteor._ensure(self, 'direct', method)
self.direct[method] = function () {
var args = arguments
self.direct[method] = function (...args) {
return CollectionHooks.directOp(function () {
return constructor.prototype[method].apply(self, args)
})
}

collection[method] = function () {
collection[method] = function (...args) {
if (CollectionHooks.directEnv.get() === true) {
return _super.apply(collection, arguments)
return _super.apply(collection, args)
}

// NOTE: should we decide to force `update` with `{upsert:true}` to use
// the `upsert` hooks, this is what will accomplish it. It's important to
// realize that Meteor won't distinguish between an `update` and an
// `insert` though, so we'll end up with `after.update` getting called
// even on an `insert`. That's why we've chosen to disable this for now.
// if (method === "update" && _.isObject(arguments[2]) && arguments[2].upsert) {
// if (method === "update" && Object(args[2]) === args[2] && args[2].upsert) {
// method = "upsert";
// advice = CollectionHooks.getAdvice(method);
// }
Expand All @@ -132,46 +104,38 @@ CollectionHooks.extendCollectionInstance = function extendCollectionInstance (se
} : self._hookAspects[method] || {},
function (doc) {
return (
_.isFunction(self._transform)
typeof self._transform === 'function'
? function (d) { return self._transform(d || doc) }
: function (d) { return d || doc }
)
},
_.toArray(arguments),
args,
false
)
}
})
}

CollectionHooks.defineAdvice = function defineAdvice (method, advice) {
CollectionHooks.defineAdvice = (method, advice) => {
advices[method] = advice
}

CollectionHooks.getAdvice = function getAdvice (method) {
return advices[method]
}
CollectionHooks.getAdvice = method => advices[method];

CollectionHooks.initOptions = function initOptions (options, pointcut, method) {
return CollectionHooks.extendOptions(CollectionHooks.defaults, options, pointcut, method)
}
CollectionHooks.initOptions = (options, pointcut, method) =>
CollectionHooks.extendOptions(CollectionHooks.defaults, options, pointcut, method);

CollectionHooks.extendOptions = function extendOptions (source, options, pointcut, method) {
options = _.extend(options || {}, source.all.all)
options = _.extend(options, source[pointcut].all)
options = _.extend(options, source.all[method])
options = _.extend(options, source[pointcut][method])
return options
}
CollectionHooks.extendOptions = (source, options, pointcut, method) =>
({...options, ...source.all.all, ...source[pointcut].all, ...source.all[method], ...source[pointcut][method]});

CollectionHooks.getDocs = function getDocs (collection, selector, options) {
var findOptions = {transform: null, reactive: false} // added reactive: false
const findOptions = {transform: null, reactive: false} // added reactive: false

/*
// No "fetch" support at this time.
if (!this._validators.fetchAllFields) {
findOptions.fields = {};
_.each(this._validators.fetch, function(fieldName) {
this._validators.fetch.forEach(function(fieldName) {
findOptions.fields[fieldName] = 1;
});
}
Expand All @@ -187,8 +151,8 @@ CollectionHooks.getDocs = function getDocs (collection, selector, options) {
if (!options.multi) {
findOptions.limit = 1
}

_.extend(findOptions, _.omit(options, 'multi', 'upsert'))
const { multi, upsert, ...rest } = options
Object.assign(findOptions, rest);
}

// Unlike validators, we iterate over multiple docs, so use
Expand All @@ -202,9 +166,9 @@ CollectionHooks.getDocs = function getDocs (collection, selector, options) {
// case this code changes.
CollectionHooks.getFields = function getFields (mutator) {
// compute modified fields
var fields = []
const fields = []
// ====ADDED START=======================
var operators = [
const operators = [
'$addToSet',
'$bit',
'$currentDate',
Expand All @@ -221,19 +185,19 @@ CollectionHooks.getFields = function getFields (mutator) {
]
// ====ADDED END=========================

_.each(mutator, function (params, op) {
Object.entries(mutator).forEach(function ([op, params]) {
// ====ADDED START=======================
if (_.contains(operators, op)) {
if (operators.includes(op)) {
// ====ADDED END=========================
_.each(_.keys(params), function (field) {
Object.keys(params).forEach(function (field) {
// treat dotted fields as if they are replacing their
// top-level part
if (field.indexOf('.') !== -1) {
field = field.substring(0, field.indexOf('.'))
}

// record the field we are trying to change
if (!_.contains(fields, field)) {
if (!fields.includes(field)) {
fields.push(field)
}
})
Expand All @@ -248,9 +212,8 @@ CollectionHooks.getFields = function getFields (mutator) {
}

CollectionHooks.reassignPrototype = function reassignPrototype (instance, constr) {
var hasSetPrototypeOf = typeof Object.setPrototypeOf === 'function'

if (!constr) constr = typeof Mongo !== 'undefined' ? Mongo.Collection : Meteor.Collection
const hasSetPrototypeOf = typeof Object.setPrototypeOf === 'function'
constr = constr || Mongo.Collection

// __proto__ is not available in < IE11
// Note: Assigning a prototype dynamically has performance implications
Expand All @@ -265,22 +228,20 @@ CollectionHooks.wrapCollection = function wrapCollection (ns, as) {
if (!as._CollectionConstructor) as._CollectionConstructor = as.Collection
if (!as._CollectionPrototype) as._CollectionPrototype = new as.Collection(null)

var constructor = as._CollectionConstructor
var proto = as._CollectionPrototype
const constructor = as._CollectionConstructor
const proto = as._CollectionPrototype

ns.Collection = function () {
var ret = constructor.apply(this, arguments)
ns.Collection = function (...args) {
const ret = constructor.apply(this, args)
CollectionHooks.extendCollectionInstance(this, constructor)
return ret
}

ns.Collection.prototype = proto
ns.Collection.prototype.constructor = ns.Collection

for (var prop in constructor) {
if (constructor.hasOwnProperty(prop)) {
ns.Collection[prop] = constructor[prop]
}
for (let prop of Object.keys(constructor)) {
ns.Collection[prop] = constructor[prop]
}
}

Expand All @@ -293,22 +254,3 @@ if (typeof Mongo !== 'undefined') {
CollectionHooks.wrapCollection(Meteor, Meteor)
}

if (Meteor.isServer) {
var _publish = Meteor.publish
Meteor.publish = function (name, handler, options) {
return _publish.call(this, name, function () {
// This function is called repeatedly in publications
var ctx = this
var args = arguments
return publishUserId.withValue(ctx && ctx.userId, function () {
return handler.apply(ctx, args)
})
}, options)
}

// Make the above available for packages with hooks that want to determine
// whether they are running inside a publish function or not.
CollectionHooks.isWithinPublish = function isWithinPublish () {
return publishUserId.get() !== undefined
}
}
29 changes: 13 additions & 16 deletions find.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,32 @@
/* global CollectionHooks _ */
import { CollectionHooks } from './collection-hooks';

CollectionHooks.defineAdvice('find', function (userId, _super, instance, aspects, getTransform, args, suppressAspects) {
var self = this
var ctx = {context: self, _super: _super, args: args}
var ret, abort

// args[0] : selector
// args[1] : options

args[0] = instance._getFindSelector(args)
args[1] = instance._getFindOptions(args)
CollectionHooks.defineAdvice('find', function (userId, _super, instance, aspects, getTransform, args, suppressAspects) {
const ctx = {context: this, _super, args}
const selector = instance._getFindSelector(args)
const options = instance._getFindOptions(args)
let ret
let abort

// before
if (!suppressAspects) {
_.each(aspects.before, function (o) {
var r = o.aspect.call(ctx, userId, args[0], args[1])
aspects.before.forEach((o) => {
const r = o.aspect.call(ctx, userId, selector, options)
if (r === false) abort = true
})

if (abort) return instance.find(undefined)
}

function after (cursor) {
const after = (cursor) => {
if (!suppressAspects) {
_.each(aspects.after, function (o) {
o.aspect.call(ctx, userId, args[0], args[1], cursor)
aspects.after.forEach((o) => {
o.aspect.call(ctx, userId, selector, options, cursor)
})
}
}

ret = _super.apply(self, args)
ret = _super.call(this, selector, options)
after(ret)

return ret
Expand Down
Loading