Medis provides built-in encoders such as MessagePack, Gzip, PHP, etc. to convert the content stored in the database into a human-readable form. In addition, you can use or develop your own encoders.
A custom encoder is an executable shell script that communicates with Medis via standard input and output.
When Medis opens a string key or the content field of a hash/set/zset/list... key, and the user selects a custom encoder, Medis will encode the content in Base64 and send to the encoder script via the standard input and pass
decodeparameter. The process is effectively similar to:
echo -n "-17" | base64 | ./encoder_Reverse.sh decode
encoder_Reverse.shis a custom encoder.
Similarly, when the content is going to be saved to the database, Medis calls the custom encoder to encode the content with
In this section, we are going to demostrate how to implement a simple custom encoder that reverses the input.
All custom encoders need to be placed in a specific folder so Medis can find them. You can open the folder from Settings -> Encoder -> Open Encoder Folder.
Create a new file
encoder_Reverse.shinside the folder. It's worth noticing that the file name of custom encoders need to start with
encoder_, otherwise they will be ignored.
Paste the following content into the file:
# Set correct exit code when any commands fail so Medis can tell
# the user.
set -o pipefail
if [ $1 = "decode" ]; then
# Get input from stdin
# Decode Base64
decoded=$( base64 -d <<< $input )
# Reverse the input
reversed=$( echo -n $decoded | rev)
# Encode in Base64
echo -n $( echo -n $reversed | base64 )
elif [ $1 = "encode" ]; then
echo "Encode not implemented!" 1>&2
The first shebang line is required so Medis can know how to run the script. It's possible to write the encoder in different languages as long as it has the correct shebang. For example, if you want to use Node.js, name the file with
encoder_Reverse.js, and change the first line to:
Then, add the executable permission to the script with
chmod +x encoder_Reverse.sh. Then go to the encode setting panel and make sure our new encoder is enabled (you may need to click on the refresh button to see the encoder).
That's it! You can open a string key and select our new encoder. The content will get reversed. However, if we make some changes and save the content, Medis shows an error alert because we raise an error in the script when the parameter is
encode. I will let you finish the script. For this encoder, encode and decode do the same thing, but other encoders may not.