dense-redux-actions
Version:
A simpler way to handle action types and actions creators for Redux.
63 lines (62 loc) • 2.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class ActionCreator {
constructor(actionType) {
if (!this.isString(actionType) || actionType.length === 0) {
throw new Error('ActionType needs to be a non empty string');
}
this.type = actionType;
}
isString(str) {
return Object.prototype.toString.call(str) === '[object String]';
}
isObject(obj) {
return typeof obj === 'object' && obj !== null;
}
payload(action) {
if (!this.isObject(action)) {
throw new Error("Can't extract a payload from something that isn't an action");
}
if (action.type !== this.type) {
throw new Error(`Can't extract a payload. Expected action of type ${this.type} got ${action.type}`);
}
return action._payload;
}
unpack(action) {
if (!this.isObject(action)) {
throw new Error("Can't unpack from something that isn't an action");
}
if (action.type !== this.type) {
throw new Error(`Can't unpack action. Expected action of type ${this.type} got ${action.type}`);
}
return { payload: action._payload, meta: action._meta };
}
meta(action) {
if (!this.isObject(action)) {
throw new Error("Can't extract a metadata from something that isn't an action");
}
if (action.type !== this.type) {
throw new Error(`Can't extract a metadata. Expected action of type ${this.type} got ${action.type}`);
}
return action._meta;
}
destruct() {
return {
[this.type]: (_payload, _meta) => {
return {
type: this.type,
_payload,
_meta,
};
}
};
}
create(_payload, _meta) {
return {
type: this.type,
_payload,
_meta,
};
}
}
exports.ActionCreator = ActionCreator;