Hyperlinkv0.8.0-beta.28

SchemaTransformation

SchemaTransformation.urlFromStringconsteffect/SchemaTransformation.ts:1374
Transformation<URL, string, never, never>

Decodes a string into a URL and encodes a URL back to its href string.

When to use

Use when you need a schema transformation to parse URL strings from user input or API responses.

Details

Decoding checks URL.canParse(s) and fails with InvalidValue if the string is not a valid URL. Encoding returns url.href.

Example (Converting a string to a URL)

import { Schema, SchemaTransformation } from "effect"

const schema = Schema.String.pipe(
  Schema.decodeTo(Schema.URL, SchemaTransformation.urlFromString)
)
export const urlFromString: Transformation<URL, string> = transformOrFail<URL, string>({
  decode: (s) =>
    URL.canParse(s)
      ? Effect.succeed(new URL(s))
      : Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid URL string: ${s}` })),
  encode: (url) => Effect.succeed(url.href)
})
Referenced by 2 symbols