@equinor/fusion-observable
Version:
56 lines • 2.16 kB
JavaScript
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* taken from https://github.com/reduxjs/redux-toolkit/tree/master/packages/toolkit/src
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function createAction(type, prepareAction) {
function actionCreator(...args) {
if (prepareAction) {
const prepared = prepareAction(...args);
if (!prepared) {
throw new Error('prepareAction did not return an object');
}
return {
type,
payload: prepared.payload,
...('meta' in prepared && { meta: prepared.meta }),
...('error' in prepared && { error: prepared.error }),
};
}
return { type, payload: args[0] };
}
actionCreator.toString = () => `${type}`;
actionCreator.type = type;
actionCreator.match = (action) => action.type === type;
return actionCreator;
}
export const actionSuffixDivider = '::';
export const matchActionSuffix = (suffix) => new RegExp(`${actionSuffixDivider}${suffix}$`);
/**
* Extracts the base type from an action type string.
*
* The action type string is expected to be in the format `${baseType}${actionSuffixDivider}${actionSuffix}`,
* where `${actionSuffixDivider}` is a special character that separates the base type from the action suffix.
*
* This function returns the `baseType` part of the action type string.
*
* @param type - The action type string to extract the base type from.
* @returns The base type of the action type string, or `never` if the input string does not match the expected format.
*/
export function getBaseType(type) {
return type.replace(matchActionSuffix('\\w+$'), '');
}
/**
* Returns the action type of the actions created by the passed
* `createAction()`-generated action creator (arbitrary action creators
* are not supported).
*
* @param action The action creator whose action type to get.
* @returns The action type used by the action creator.
*
* @public
*/
export function getType(actionCreator) {
return `${actionCreator}`;
}
//# sourceMappingURL=create-action.js.map