Last active
November 7, 2018 23:04
-
-
Save crobinson42/f24c3c4dda920cafde97cf28f2c17494 to your computer and use it in GitHub Desktop.
JS-Data - Proxy context issue demo (https://stackoverflow.com/posts/53197772)
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 { DataStore, Mapper } from 'js-data' | |
class ExtendedDataStore extends DataStore { | |
as(name) { | |
const props = {} | |
// const original = super.as(name) | |
const mapper = this.getMapper(name) | |
const self = this | |
// if "this" is passed instead of "self" the downstream methods fail without straightforward Error stacktrace | |
// but when using "self" as the 1st arguement, things work normal, as expected | |
const proxy = new Proxy(self, { | |
get: function(target, prop, receiver) { | |
// first try the prop on the DataStore | |
if (target[prop]) return (...args) => target[prop].apply(self, [name, ...args]) | |
// then try the mapper because we have custom props on mapper classes | |
return mapper[prop] | |
}, | |
}) | |
return proxy | |
} | |
} | |
const Store = new ExtendedDataStore() | |
Store.defineMapper('user') | |
Store.User = Store.as('user') // make a short-hand for User so we don't have to do `Store.getMapper('user').updateEmail(...)` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment