Extractors
Reading optional values from a source, with inspectable metadata.
package @smitejs/fp
An extractor is (source) => Option<Value> — a function that reads an optional value from a source and reports absence explicitly instead of with undefined. Transport builders (cookies, headers, params, query) produce them, and chain composes them.
Reading a value
The canonical example is a request-like source: read a cookie, a header, a query param — each returns an Option, so a missing value is an explicit none, never a crash.
const extract = (source: HttpLike) =>
Option.fromNullable(source.cookies.session_id);
const value = extract({ cookies: { session_id: "abc123" }, headers: {} });"abc123"
"missing",chain — try in order
chain(...extractors) tries each extractor in order and returns the first value found, or none if all miss. Order matters: prefer more specific or more secure sources first (an authenticated header before a session cookie).
const sessionId = chain(cookie("session_id"), header("x-session-id"));
const fromCookie = sessionId({
cookies: { session_id: "abc123" },
headers: {},
});
const fromHeader = sessionId({
cookies: {},
headers: { "x-session-id": "header-id" },
});
const missing = sessionId({ cookies: {}, headers: {} });"abc123"
"header-id"
trueMetadata
Extractors produced by chain (and transport factories) carry a non-enumerable extractorMetadata symbol describing their source and key. Tooling reads it with getExtractorMetadata without executing the extractor — and normal iteration and serialization never see it.
const read = (source: HttpLike) =>
Option.fromNullable(source.headers["x-id"]);
const extractor = chain(read);
const metadata = getExtractorMetadata(extractor);{
kind: "fp.extractor",
source: "chain",
key: "read",
chain: [
{
kind: "fp.extractor",
source: "custom",
key: "read",
},
],
}
[]
metadata