Creating a URL Type
Let’s create a simple type for encoding URLs. As an example, we’ll use URLs with the http or https protocol.
type TURL = `https://${string}` | `http://${string}`;const urlRegEx = /^https?:\/\//;
export const url = customType<TURL>({ encode(value, buffer) { // Encode protocol: http as 1, https as 2 buffer.writeUint8(value.startsWith("https") ? 2 : 1); // Encode the rest of the URL buffer.writeString(value.slice(value.indexOf("://") + 3)); }, decode(buffer) { const protocol = buffer.readUint8(); const url = buffer.readString(); return `${protocol === 2 ? "https" : "http"}://${url}`; }, guard(data): data is TURL { if (typeof data !== "string") return false; if (!urlRegEx.test(data)) return false; return true; }, name: "url",});
Now we can use this type in our data schema:
import { Serializer, t } from "encodexx";import { url } from "./url.ts";
const serializer = new Serializer([url]);