Middleware to add time to all actions

Viewed 92

Using Redux Toolkit, I have many action creators that have prepare callbacks adding a unixtime property to the payload. This property gets the Date.now() value. Since I'm continually adding more actions requiring a time, I'm thinking I'll instead add middleware like the following:

import { Middleware } from 'redux';
import { RootState } from '../sliceReducer'; // type of my app's Redux state

const unixtimeMiddleware: Middleware<{}, RootState> = () => (next) => (action) => {
    if (action && !action.meta) {
        action.meta = {};
    }
    action.meta.unixtime = Date.now();
    return next(action);
};

export default unixtimeMiddleware;

My question is:

  1. Is this the right type for the middleware?
  2. Possibly related to (1), is there a way to automatically have meta: { unixtime: number } added to all RTK action types, or do I need to create types that extend the built-in action types like:
import { PayloadAction } from '@reduxjs/toolkit';

/**
 * An extension of Redux Toolkit's PayloadAction which includes a .meta.unixtime property.
 *
 * @template P The type of the action's payload.
 * @template M Union to the action's base meta type { unixtime: number } (optional)
 * @template E The type of the action's error (optional)
 *
 * @public
 */
export type PayloadActionUnixtime<P, M = never, E = never> = PayloadAction<
    P,
    string,
    { unixtime: number } & ([M] extends [never] ? {} : M),
    E
>;

(Side note: I chose the name unixtime over something like timestamp to reduce the likelihood someone would think it is a string like YYYY-MM-DD HH-MM-SS)

0 Answers
Related