UNPKG

1.89 kBJavaScriptView Raw
1import { requestOf, clearOf, refreshOf } from "./actions";
2import { registerSaga, Apis } from "./apis";
3import makeApiSelector from "./selector";
4import { camelCaseKey } from "./lib";
5
6export { default as apiReducers, apiReducer, entitiesReducer } from "./reducer";
7export { watchApis, registerHooks } from "./saga";
8export {
9 isApi,
10 isSuccess,
11 isRequest,
12 isFailure,
13 successOf,
14 failureOf,
15 requestOf,
16} from "./actions";
17
18class 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
66export 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
84export function createApiSelector(key, schema) {
85 return makeApiSelector(key, schema);
86}
87
88export function apiSelector(key, schema) {
89 console.warn(
90 "apiSelector function is deprecated, please use createApiSelector "
91 );
92 return makeApiSelector(key, schema);
93}