Skip to content

Instantly share code, notes, and snippets.

@nvie

nvie/example.md Secret

Last active February 1, 2022 20:55
Show Gist options
  • Save nvie/9e912992102b44b5c843c26ee3b19450 to your computer and use it in GitHub Desktop.
Save nvie/9e912992102b44b5c843c26ee3b19450 to your computer and use it in GitHub Desktop.

Here's an example that illustrates how you can manually define a decoder for specific URL schemas.

import { url } from 'decoders';

// ❌ In decoders v1.x 
const gitUrl: Decoder<string> = url(['git']);

// ✅ In decoders v2.x
const gitUrl: Decoder<string> =
  url
    .refine((value) => value.protocol === 'git:', 'Must be a git:// URL')
    .transform((value) => value.toString());  // Only if you need this to be a Decoder<string>

The benefit of writing these manually is that you can also easily define custom checks, like accepted domain names, paths, etc. For example, here's one that only accepts github.com URLs:

import { url } from 'decoders';

const githubUrl: Decoder<URL> =
  url
    .refine((value) => value.hostname === 'github.com', 'Must be a GitHub URL')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment