1 | import { requestOf, clearOf, refreshOf } from "./actions";
|
2 | import { registerSaga, Apis } from "./apis";
|
3 | import makeApiSelector from "./selector";
|
4 | import { camelCaseKey } from "./lib";
|
5 |
|
6 | export { default as apiReducers, apiReducer, entitiesReducer } from "./reducer";
|
7 | export { watchApis, registerHooks } from "./saga";
|
8 | export {
|
9 | isApi,
|
10 | isSuccess,
|
11 | isRequest,
|
12 | isFailure,
|
13 | successOf,
|
14 | failureOf,
|
15 | requestOf,
|
16 | } from "./actions";
|
17 |
|
18 | class Api {
|
19 | constructor(key, endpoint, schema, reduxPath) {
|
20 | this._key = key;
|
21 | this._endpoint = endpoint;
|
22 | this._schema = schema;
|
23 | this._reduxPath = camelCaseKey(reduxPath || key);
|
24 | }
|
25 |
|
26 | get endpoint() {
|
27 | return this._endpoint;
|
28 | }
|
29 |
|
30 | get key() {
|
31 | return this._key;
|
32 | }
|
33 |
|
34 | get schema() {
|
35 | return this._schema;
|
36 | }
|
37 |
|
38 | get reduxPath() {
|
39 | return this._reduxPath;
|
40 | }
|
41 |
|
42 | get actions() {
|
43 | return {
|
44 | request: (payload, meta = {}) => ({
|
45 | type: requestOf(this.key),
|
46 | key: this.key,
|
47 | payload,
|
48 | meta,
|
49 | }),
|
50 |
|
51 | clear: (meta = {}) => ({
|
52 | type: clearOf(this.key),
|
53 | key: this.key,
|
54 | meta,
|
55 | }),
|
56 |
|
57 | refresh: (meta = {}) => ({
|
58 | type: refreshOf(this.key),
|
59 | key: this.key,
|
60 | meta,
|
61 | }),
|
62 | };
|
63 | }
|
64 | }
|
65 |
|
66 | export function createApiActions(key, opts = {}) {
|
67 | if (!key) {
|
68 | throw new Error("Api need a key!");
|
69 | }
|
70 |
|
71 | if (!opts.endpoint) {
|
72 | throw new Error("Api need an endpoint function");
|
73 | }
|
74 |
|
75 | if (Apis.has(key)) {
|
76 | return Apis.get(key).actions;
|
77 | }
|
78 |
|
79 | const api = new Api(key, opts.endpoint, opts.schema, opts.reduxPath);
|
80 | registerSaga(key, api);
|
81 | return api.actions;
|
82 | }
|
83 |
|
84 | export function createApiSelector(key, schema) {
|
85 | return makeApiSelector(key, schema);
|
86 | }
|
87 |
|
88 | export function apiSelector(key, schema) {
|
89 | console.warn(
|
90 | "apiSelector function is deprecated, please use createApiSelector "
|
91 | );
|
92 | return makeApiSelector(key, schema);
|
93 | }
|