メインコンテンツへスキップ

シリアライズ可能性ミドルウェア

redux-immutable-state-invariantをモデルとした、状態またはディスパッチされたアクションにシリアライズ不可能な値が含まれているかどうかを検出するカスタムミドルウェアです。検出されたシリアライズ不可能な値はコンソールにログ出力されます。

このミドルウェアは、デフォルトでconfigureStoregetDefaultMiddlewareによってストアに追加されます。

getDefaultMiddlewareserializableCheck値として、サポートされているオプションのいずれかを渡すことで、このミドルウェアの動作をカスタマイズできます。

オプション

interface SerializableStateInvariantMiddlewareOptions {
/**
* The function to check if a value is considered serializable. This
* function is applied recursively to every value contained in the
* state. Defaults to `isPlain()`.
*/
isSerializable?: (value: any) => boolean
/**
* The function that will be used to retrieve entries from each
* value. If unspecified, `Object.entries` will be used. Defaults
* to `undefined`.
*/
getEntries?: (value: any) => [string, any][]

/**
* An array of action types to ignore when checking for serializability.
* Defaults to []
*/
ignoredActions?: string[]

/**
* An array of dot-separated path strings or regular expressions to ignore
* when checking for serializability, Defaults to
* ['meta.arg', 'meta.baseQueryMeta']
*/
ignoredActionPaths?: (string | RegExp)[]

/**
* An array of dot-separated path strings or regular expressions to ignore
* when checking for serializability, Defaults to []
*/
ignoredPaths?: (string | RegExp)[]
/**
* Execution time warning threshold. If the middleware takes longer
* than `warnAfter` ms, a warning will be displayed in the console.
* Defaults to 32ms.
*/
warnAfter?: number

/**
* Opt out of checking state. When set to `true`, other state-related params will be ignored.
*/
ignoreState?: boolean

/**
* Opt out of checking actions. When set to `true`, other action-related params will be ignored.
*/
ignoreActions?: boolean
}

エクスポート

createSerializableStateInvariantMiddleware

指定されたオプションを使用して、シリアライズ可能性チェックミドルウェアのインスタンスを作成します。

getDefaultMiddlewareが既に実行しているので、自分で呼び出す必要はほとんどないでしょう。

import { Iterable } from 'immutable'
import {
configureStore,
createSerializableStateInvariantMiddleware,
isPlain,
Tuple,
} from '@reduxjs/toolkit'
import reducer from './reducer'

// Augment middleware to consider Immutable.JS iterables serializable
const isSerializable = (value: any) =>
Iterable.isIterable(value) || isPlain(value)

const getEntries = (value: any) =>
Iterable.isIterable(value) ? value.entries() : Object.entries(value)

const serializableMiddleware = createSerializableStateInvariantMiddleware({
isSerializable,
getEntries,
})

const store = configureStore({
reducer,
middleware: () => new Tuple(serializableMiddleware),
})

isPlain

指定された値が「プレーンな値」と見なされるかどうかをチェックします。

現在、次のように実装されています。

import isPlainObject from './isPlainObject'

export function isPlain(val: any) {
return (
typeof val === 'undefined' ||
val === null ||
typeof val === 'string' ||
typeof val === 'boolean' ||
typeof val === 'number' ||
Array.isArray(val) ||
isPlainObject(val)
)
}

これはすべての標準的なJSオブジェクト、配列、プリミティブを受け入れますが、DateMap、およびその他の同様のクラスインスタンスに対してはfalseを返します。