Skip to content

Instantly share code, notes, and snippets.

@hexnickk
Last active March 22, 2019 15:02
Show Gist options
  • Select an option

  • Save hexnickk/7f078115257f8cf42bfd5273f3500a90 to your computer and use it in GitHub Desktop.

Select an option

Save hexnickk/7f078115257f8cf42bfd5273f3500a90 to your computer and use it in GitHub Desktop.
ngxs ctx.resetState
import { SetState } from './tmpState.actions';
import { State, Action } from '@ngxs/store';
let myDefaults: any;
// get default state
const stateHandler = {
apply: function (target, thisArg, argumentsList) {
myDefaults = argumentsList[0].defaults;
return target.apply(thisArg, argumentsList);
}
}
// patch actual method call
const methodHandler = {
apply: function (target, thisArg, argumentsList) {
const setState = argumentsList[0].setState;
argumentsList[0].resetState = function () {
setState(myDefaults);
};
return target.apply(thisArg, argumentsList);
}
}
// patch decorator method extractor
const reducerHandler = {
apply: function (target, thisArg, argumentsList) {
const fn = argumentsList[2].value;
// patch method call
argumentsList[2].value = new Proxy(fn, methodHandler);
return target.apply(thisArg, argumentsList);
}
};
// patch decorator call
const decoratorHandler = {
apply: function (target, thisArg, argumentsList) {
return new Proxy(target.apply(thisArg, argumentsList), reducerHandler);
}
};
const ProxyState = new Proxy(State, stateHandler);
const ProxyAction = new Proxy(Action, decoratorHandler);
@ProxyState<string[]>({
name: 'state',
defaults: [],
})
export class TmpState {
@ProxyAction(SetState)
setState(ctx: any, action: SetState) {
ctx.resetState();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment