-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
108 lines (92 loc) · 2.72 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import Vue from "vue";
import { ActionContext, Payload, CommitOptions, DispatchOptions } from "vuex";
const NOTHING: any = undefined;
type TMutation<P> = Payload & { payload: P };
type TFactory<V, P = V> = (payload: V) => TMutation<P>;
type TMutationHandler<P, S> = (state: S, payload: P) => void;
type TContext<S, R> = Omit<Omit<ActionContext<S, R>, "commit">, "dispatch"> & {
commit: (data: TMutation<any>, options?: CommitOptions) => void;
dispatch: (data: TMutation<any>, options?: DispatchOptions) => Promise<any>;
};
type TActionHandler<P, S, R, V> = (ctx: TContext<S, R>, payload: P) => V;
/**
* Action (mutation) instance factory
* @param type Action (mutation) type
* @param payload Action (mutation) payload
*/
export function action<P>(type: string, payload: P = NOTHING): TMutation<P> {
return { type, payload };
}
/**
* Append typesafe mutation to store
*/
export function useMutation<S>() {
return function <V, P>(
factory: TFactory<V, P>,
handler: TMutationHandler<P, S>
) {
const type = factory(null as any).type;
return {
[type]: handler,
};
};
}
/**
* Append typesafe action to store
*/
export function useAction<S, R>() {
return function <V, P, O>(
factory: TFactory<V, P>,
handler: TActionHandler<P, S, R, O>
) {
const type = factory(null as any).type;
return {
[type](ctx: ActionContext<S, R>, payload: P) {
function commit(data: TMutation<P>, options?: CommitOptions) {
ctx.commit(data.type, data.payload, options);
}
function dispatch(data: TMutation<P>, options?: DispatchOptions) {
return ctx.dispatch(data.type, data.payload, options);
}
return handler({ ...ctx, commit, dispatch }, payload);
},
};
};
}
/**
* Append typesafe getter to component computed
*/
export function mapGetter<S, R>(selector: (root: R) => S) {
return function <V>(getter: (s: S) => V) {
return function (this: Vue) {
const store: S = selector(this.$store.state);
return getter(store);
};
};
}
/**
* Append typesafe mutation to component methods
*/
export function mapMutation<V, P>(factory: TFactory<V, P>) {
return function (this: Vue, payload: V, options?: CommitOptions) {
const mutationInstance = factory(payload);
return this.$store.commit(
mutationInstance.type,
mutationInstance.payload,
options
);
};
}
/**
* Append typesafe action to component methods
*/
export function mapAction<V, P>(factory: TFactory<V, P>) {
return function (this: Vue, payload: V, options?: DispatchOptions) {
const actionInstance = factory(payload);
return this.$store.dispatch(
actionInstance.type,
actionInstance.payload,
options
);
};
}