Permlink Validation | Typescript and Python | Hivemind

in Steem Dev10 months ago

Hello developers, I have been reading and comprehending the Python code of the Hivemind. I noticed that there are many reusable functions. Therefore, in this Hivemind series, I will attempt to share the useful functions provided by Hivemind in Python and convert them into Typescript. This conversion will enhance type handling and make them usable in Typescript or Javascript.

hivemind.png

Today, we will examine the valid_permlink function. This function is used to validate the permlink in various cases. For example, if an app generates a permalink that does not pass validation, it will receive an error from this validation process.

Sometimes the permlink length accidentally gets greater than 256 characters, In most cases when we generate the permlink manually for the replies or post comments the string becomes longer. For this case, it is essential to check for a valid transaction to the blockchain. It means Steem only allows a maximum of 256 characters of permlink.

GitHub

https://github.com/steemit/hivemind

Python

def valid_permlink(permlink:str, allow_empty=False):
    if not permlink:
        assert allow_empty, 'permlink cannot be blank'
        return ""
    assert isinstance(permlink, str), 'permlink must be string'
    assert len(permlink) <= 256, "invalid permlink length"
    return permlink

Example (Python)

is_valid = valid_permlink('hi-i-am-permlink')
print(is_valid)

If the permlink is validated, the function will return it; otherwise, it will return an empty string.

Typescript

function valid_permlink(permlink: string, allowEmpty: boolean = false): string {
    if (!permlink) {
        if (!allowEmpty) {
            throw new Error('Permlink cannot be blank');
        }
        return "";
    }

    if (typeof permlink !== 'string') {
        throw new Error('Permlink must be a string');
    }

    if (permlink.length > 256) {
        throw new Error('Invalid permlink length');
    }

    return permlink;
}

Example (Typescript)

const is_valid  = valid_permlink('hi-i-am-permlink')

console.log(is_valid)

If the permlink is validated, the function will return it; otherwise, it will return an empty string.



Best Regards @faisalamin

Download SteemPro Mobile

Coin Marketplace

STEEM 0.16
TRX 0.12
JST 0.026
BTC 56905.21
ETH 2508.41
USDT 1.00
SBD 2.36