gcanti / io-ts-types

A collection of codecs and combinators for use with io-ts
https://gcanti.github.io/io-ts-types/
MIT License
311 stars 40 forks source link

Base64 decode/encode #155

Closed piu130 closed 3 years ago

piu130 commented 3 years ago

🚀 Feature request

Desired Behavior

Would be cool, if this library supports base64 decode and encode natively. My scenario: I fetch some base64 encoded Json StringFromBase64.pipe(JsonFromString).

Suggested Solution

I'm new to io-ts, so this might not be the correct way to implement it:

export const StringFromBase64 = new t.Type<string, string, string>(
    'StringFromBase64',
    (u): u is string => typeof u === 'string',
    (s, c) => {
        try {
            return t.success(atob(s));
        } catch (e) {
            return t.failure(s, c);
        }
    },
    s => btoa(s)
);
piu130 commented 3 years ago

There is no atob and btoa in NodeJS.

DenisFrezzato commented 3 years ago

@piu130 there isn't, but the same can be achieved using Buffer and character encoding, see this.