Mikro ORM Redis Cache Adapter
This is mikro orm redis cache adapter that uses v8.serialize
and
v8.deserialize
rather than JSON.stringify
and JSON.parse
.
Quick Start
After install the package, edit your resultCache
configuration.
import { RedisCacheAdapter, type RedisCacheAdapterOptions} from '@javien/mikro-orm-redis-cache-adapter'
defineConfig({
resultCache: {
adapter: RedisCacheAdapter
options: {
client: redis
debug: true,
prefix: 'mikro',
prefixDelimiter: ':',
logger: myLogger,
gracefulShutdown: false
} as RedisCacheAdapterOptions
}
})
Behavior Explained
- Failing to store cache, it'll log the error regardless of the debug mode.
- Failing to fetch cache,
undefined
will be returned, which means your data will be loaded from the database. - Failing to delete the cache, it'll log the error regardless of the debug mode.
Debug Mode
If you use debug mode, saving data is shown with JSON.stringify
applied.
it doesn't mean JSON.stringify
is used to serialize the data. It's only for logging purposes.
Supported Data Types
v8.serialize
is compatible with The structured clone algorithm, so only Supported types are able to get serialized.
Here're suported JavaScript types.
- Array, ArrayBuffer, and TypedArray
- Number, String, and Boolean
- Primitive types, except symbol.
- DataView
- Date
- Error types (see more at MDN page).
- Map and Set
- Object objects: but only plain objects (e.g. from object literals).
- RegExp: but note that lastIndex is not preserved.
If your property is not supported type, consider using Custom Type.
Why not JSON.stringify?
JSON.stringify
is usually used to serialize objects,
but there are several kinds of data that it can't serialize and deserialize - BigInt, recursive, Buffer, Map, Set, etc.
JSON.stringify(BigInt(1))
const obj = {}
obj.obj = obj
JSON.stringify(obj)
const buf = Buffer.from([0])
const str = JSON.stringify(buf)
const parsed = JSON.parse(str)
To solve this, we can pass the replacer
parameter. However, I don't think this is the best way to serialize data, while we can choose v8 api.