Created
July 19, 2018 18:03
-
-
Save merlinstardust/213c7811b7d4d0db5b13834c439c4122 to your computer and use it in GitHub Desktop.
Use Proxy and Meteor Mongo to create a reactive store
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Mongo} from 'meteor/mongo'; | |
const StoreCollection = new Mongo.Collection('Store', {connection: null}); | |
const objectPrototypeKeys = Object.getOwnPropertyNames(Object.prototype); | |
const getSubId = (key, subKey) => key + subKey[0].toUpperCase() + subKey.slice(1); | |
const store = new Proxy({}, { | |
get(target, key, receiver) { | |
if (objectPrototypeKeys.includes(key)) { | |
return target[key]; | |
} | |
const result = StoreCollection.findOne({_id: key}); | |
if (result && result.namespaced) { | |
return new Proxy(result.value, { | |
get(_, subKey) { | |
const subId = getSubId(key, subKey); | |
const subResult = StoreCollection.findOne({_id: subId}); | |
return subResult && subResult.value; | |
}, | |
set(_, subKey, value) { | |
const subId = getSubId(key, subKey); | |
StoreCollection.update({_id: key}, {$set: {[`value.${subKey}`]: value}}); | |
StoreCollection.upsert({_id: subId}, {_id: subId, value}); | |
return true; | |
}, | |
}); | |
} | |
return result && result.value; | |
}, | |
set(_, key, value) { | |
if (value.constructor === Object) { | |
const object = value; | |
Object.keys(object).forEach(subKey => { | |
const subId = getSubId(key, subKey); | |
StoreCollection.upsert({_id: subId}, {_id: subId, value: object[subKey]}) | |
}); | |
StoreCollection.upsert({_id: key}, {namespaced: true, value}); | |
return true; | |
} | |
StoreCollection.upsert({_id: key}, {_id: key, value}); | |
return true; | |
}, | |
}); | |
export default store; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment