budibase/packages/client/src/state/eventHandlers.js

57 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-09-23 07:08:06 +02:00
import { setState } from "./setState";
import { getState } from "./getState";
2019-09-22 06:02:33 +02:00
import {
isArray, isUndefined
} from "lodash/fp";
2019-09-23 07:08:06 +02:00
import { createApi } from "../api";
import {
getNewChildRecordToState, getNewRecordToState
} from "./coreHandlers";
2019-09-22 06:02:33 +02:00
export const EVENT_TYPE_MEMBER_NAME = "##eventHandlerType";
2019-10-03 07:12:13 +02:00
export const eventHandlers = (store,coreApi,rootPath) => {
2019-09-22 06:02:33 +02:00
const handler = (parameters, execute) => ({
execute, parameters
});
2019-10-03 07:12:13 +02:00
const setStateWithStore = (path, value) => setState(store, path, value);
2019-10-18 18:32:03 +02:00
let currentState;
store.subscribe(s => {
currentState = s;
});
2019-09-23 07:08:06 +02:00
const api = createApi({
2019-10-03 07:12:13 +02:00
rootPath:rootPath,
2019-10-18 18:32:03 +02:00
setState: setStateWithStore,
getState: (path, fallback) => getState(currentState, path, fallback)
2019-09-23 07:08:06 +02:00
});
2019-09-22 06:02:33 +02:00
const setStateHandler = ({path, value}) => setState(store, path, value);
return {
2019-09-23 07:08:06 +02:00
"Set State": handler(["path", "value"], setStateHandler),
"Load Record": handler(["recordKey", "statePath"], api.loadRecord),
"List Records": handler(["indexKey", "statePath"], api.listRecords),
"Save Record": handler(["statePath"], api.saveRecord),
"Get New Child Record": handler(
["recordKey", "collectionName", "childRecordType", "statePath"],
2019-10-18 18:32:03 +02:00
getNewChildRecordToState(coreApi, setStateWithStore)),
2019-09-23 07:08:06 +02:00
"Get New Record": handler(
["collectionKey", "childRecordType", "statePath"],
2019-10-18 18:32:03 +02:00
getNewRecordToState(coreApi, setStateWithStore)),
2019-09-26 06:40:58 +02:00
"Authenticate": handler(["username", "password"], api.authenticate)
2019-09-22 06:02:33 +02:00
};
};
export const isEventType = prop =>
isArray(prop)
&& prop.length > 0
&& !isUndefined(prop[0][EVENT_TYPE_MEMBER_NAME]);