Fetch
Every member of the Fetch namespace: clients, calls, errors, plugins, endpoints, streams and pages.
@monarcode/effetch exports one name, the Fetch namespace. Its members, grouped by the guide that covers them:
import { } from "@monarcode/effetch";Clients
Guide: Declare a client.
Fetch.isService
Returns true if u is a class made by Service, or a class that extends one. false for anything else, including a key made with Context.Service and a Client.
Fetch.make
Makes a Client.
Fetch.Service
Declares a client as a service class: one class that is the client's service key, its layer and its config.
Fetch.Client
A client made by make. Every call returns an Effect that needs no services, apart from those its schemas require (the call's or endpoint's own, and the client's defaultError and statusErrors), and that can fail with the plugins' errors and the statusErrors that apply, on top of Effetch's own.
Prop
Type
Fetch.ClientConfig
Configuration for make.
Prop
Type
Fetch.ServiceClass
A client as a service class: what Service returns, to extend.
Fetch.ServiceClass.Any
Any class made by Service, whatever its config. What isService narrows to.
Calls
Guide: Methods.
Fetch.AnySchema
Any Effect schema accepted by the output, error and input options.
Fetch.Args
The rest arguments after the path: the options object T is required when path P has parameters, optional otherwise.
Fetch.BaseOptions
Options shared by every method.
Prop
Type
Fetch.BodyMethod
The signature of post, put, patch and del: body allowed, typed by input when given.
Ps: the client's plugins.DefaultEB: the client'sdefaultErrorschema, used when a call has noerror.ClientSE: the client'sstatusErrorsmap, orundefinedwithout one.
Fetch.BodyOptions
The body and input options of methods that send a body.
Prop
Type
Fetch.CallEffect
The Effect a call returns: it succeeds with Success, fails with CallError and requires CallServices.
O: theoutputschema, orundefinedfor the raw response.EB: theerrorschema for non-2xx bodies.I: theinputschema (Schema.Unknownorundefinedwhen the call has none).Ps: the client's plugins.SE: thestatusErrorsmaps of the call, the endpoint and the client, as a union.undefined(the default) when there are none.M: theResponseMode, orundefined(the default) for the decoded body alone.QS: an endpoint'squeryschema (seeQuerySchema), orundefined(the default) without one.
Fetch.CallServices
The services a call requires: those needed to decode output, error and the statusErrors maps' errors, and to encode input and an endpoint's query.
SE: thestatusErrorsmaps of the call, the endpoint and the client, as a union.undefined(the default) when there are none.QS: the endpoint'squeryschema (seeQuerySchema), orundefined(the default) without one.
Fetch.NoBodyMethod
The signature of get, head and options: no body or input.
Ps: the client's plugins.DefaultEB: the client'sdefaultErrorschema, used when a call has noerror.ClientSE: the client'sstatusErrorsmap, orundefinedwithout one.
Fetch.NoBodyRequestOptions
Options of methods that don't send a body: get, head, options. The type parameters are those of BaseOptions.
Fetch.ParamsOption
The params option for path P: required (with exactly the path's parameter names) when the path has :params, forbidden otherwise.
Fetch.PathParamNames
The names of the path parameters in P, as a union of string literals.
Fetch.PathParams
The params object for path P: one required key per parameter name.
Fetch.PathParamValue
A value accepted for a path parameter. It's converted with String() and then encodeURIComponent.
Fetch.QueryInput
The query option: an object whose entries become URL query parameters. Arrays repeat the key (tags=a&tags=b); null and undefined entries and array items are dropped.
Fetch.QueryOf
The constraint on a query of type Q: each of Q's own properties must be a QueryValue or an array of them.
Fetch.QueryValue
A single query value. Effetch drops null and undefined (Effect's own UrlParams would send null as the string "null"); other values are converted with String(). With Effect 4.1 or later, a value can also be Redacted: it's sent as its value, and stays redacted in Effect's own logs and traces.
Fetch.RequestMethod
The signature of request: any HTTP method, body allowed, typed by input when given.
Ps: the client's plugins.DefaultEB: the client'sdefaultErrorschema, used when a call has noerror.ClientSE: the client'sstatusErrorsmap, orundefinedwithout one.
Fetch.RequestOptions
Options of methods that send a body: post, put, patch, del and request. The type parameters are those of BaseOptions, and I is the input schema.
Responses
Guide: Read the response.
Fetch.bytes
Reads a 2xx body as bytes, a Uint8Array, for output. Use it for images, PDFs and other binary bodies. The array is typed Uint8Array<ArrayBuffer>, so in browsers, Node, Bun and Deno it can go straight into a Blob. React Native's Blob doesn't take arrays.
Fetch.text
Reads a 2xx body as text, for output. Use it for plain-text tokens, CSV and other bodies that aren't JSON.
Fetch.text()gives the text as it was sent, as astring. An empty body is"".Fetch.text(schema)reads a single value, such as a count or a status: it trims the text, then decodes it withschema, whose encoded side is a string, such asSchema.NumberFromString. An empty body fails, as for JSON.
Fetch.BytesSchema
The schema bytes returns: a Uint8Array over an ArrayBuffer, read from the body's bytes.
Fetch.ResponseMode
What a call succeeds with, besides the decoded body:
"decoded"(the default): the decoded body, or the raw response without anoutputschema."decoded-and-response": a pair of the decoded body and the response, to read its status and headers too. Without anoutputschema, the first item is the response as well.
Fetch.Success
What a call succeeds with: the output schema's type, or the raw HttpClientResponse without one. A conditional output gives the union.
Fetch.TextSchema
A schema whose encoded side is a string, as text takes: such as Schema.String, Schema.NumberFromString or a Schema.Literals of strings.
Uploads
Guide: Upload files.
Fetch.multipart
Sends a body as multipart/form-data, for input: the body is typed and checked by schema, as for JSON, then sent as FormData. Use it for file uploads.
Fetch.UploadFile
A file to upload, for a field of a multipart input schema. It takes the files each platform can send:
- in browsers, Node, Bun and Deno, a
BloborFile; - in React Native, a
NativeFile,{ uri, name, type }, as its pickers give it. React Native'sFormDatareads the file from disk byuri, and can't send aBlob.
Fetch.MultipartFields
What a multipart input schema encodes a body to: an object of fields, each a MultipartValue or a list of them.
Fetch.MultipartSchema
A schema multipart takes: one whose encoded side is MultipartFields, such as a Schema.Struct of strings, numbers, booleans, dates, lists of them and UploadFiles.
Fetch.MultipartValue
One value of a multipart field, as an input schema encodes it: a string, a number, a boolean, a bigint or a Date (sent as text), a file (Blob, File or NativeFile), or null or undefined (left out).
Fetch.NativeFile
A file picked in React Native: the object React Native's pickers give, and its FormData reads from disk by uri.
uri: where the file is, such asfile:///…orcontent://….name: the file name sent with it. A server only treats a part as a file when it has one, so it's required.type: its media type, such as"image/jpeg". Without it, the part is sent asapplication/octet-stream, since Android rejects a file part without a type.
Fetch.UploadFileSchema
The schema UploadFile is: a Blob (a File is one) or a NativeFile, encoded as it is.
Errors
Guide: Call errors.
Fetch.catchStatus
Handles an HttpError with one of the given statuses, for one call: f gets the error, and the call continues with what f returns. Errors with other statuses, and every other error, pass through.
statusis one status, such as404, or a list, such as[401, 403]. The handler's error has itsstatusnarrowed to them (seeCaughtStatus).HttpErrorstays in the error type, since other statuses can still fail.f's own errors are added.- It works on any Effect whose errors include
HttpError: calls, endpoints, and Effects built on them.
Fetch.DecodeError
A 2xx response body didn't match the call's output schema, wasn't valid JSON, or couldn't be read.
Fetch.HttpError
The server answered with a non-2xx status.
Fetch.HttpError.With
An HttpError whose body was decoded as B. body is undefined when the response didn't match the error schema.
Fetch.isFetchError
Returns true if u is a NetworkError, HttpError or DecodeError.
Fetch.NetworkError
The request never produced a response: DNS failure, connection refused, CORS rejection, the device is offline, and so on.
Fetch.optional
Turns a 404 into Option.none(), and a success into Option.some, for one call: the call succeeds with an Option of its value. Other errors, HttpErrors with other statuses included, pass through.
Fetch.CallError
What a call can fail with: NetworkError, HttpError (with body typed by the error schema), DecodeError when there's an output schema, the plugins' errors, and the errors of the statusErrors maps that apply (see StatusError).
SE: thestatusErrorsmaps of the call, the endpoint and the client, as a union.undefined(the default) when there are none.
Fetch.CaughtStatus
The error catchStatus's handler gets: an HttpError whose status is narrowed to the statuses S it was given. Its body is unknown: to read it typed by the error schema, use Effect.catchTag("HttpError", …).
Fetch.FetchError
Every error the library itself can fail a call with. Plugins may add their own errors on top of these.
Fetch.StatusError
The errors a StatusErrorMap can fail a call with: the union of its schemas' types. M can be a union of maps (the call's, the endpoint's and the client's), and is undefined when there are none, which gives never.
Fetch.StatusErrorMap
The statusErrors option: turns error responses into your own errors. Each key is an HTTP status, and its value is the schema of the error that status means, or a list of schemas tried in order. The first schema that decodes the response's JSON body is what the call fails with, in place of an HttpError.
Fetch.StatusErrorSchema
The schemas a StatusErrorMap lists, as a union, under its numeric keys only. M can be a union of maps, and undefined gives never.
Fetch.StatusErrorServices
The services decoding a StatusErrorMap's errors requires: the union of its schemas' DecodingServices. Like StatusError, M can be a union of maps, and undefined gives never.
Plugins
Guide: Write a plugin.
Fetch.plugin
Defines a plugin. Returns its argument unchanged; it exists to infer Name, the errors, the services and the options type from the hooks.
Fetch.Plugin
A plugin hooks into every call a client makes.
Prop
Type
Fetch.Plugin.Any
Any plugin. Use it to constrain a generic plugin-list parameter (Ps extends ReadonlyArray<Plugin.Any>).
Fetch.Plugin.Definition
What plugin accepts. Like Plugin, but each hook has its own error and service type parameters, so hooks that fail with different errors infer their union instead of conflicting.
Fetch.Plugin.Errors
The union of errors the plugins in Ps can add to a call. unknown if a plugin's types were erased (for example by Any).
Fetch.Plugin.OnError
The onError hook. error is a FetchError, another plugin's error, one of the call's statusErrors, or a defect's cause. It can't fail or change the call's outcome: if it dies, the defect is logged at Debug level and ignored.
Fetch.Plugin.OnExit
The onExit hook: runs once per call, when it's over, with the call's Exit. On success that holds the call's result: the decoded output, or the response for a call without one, or, with responseMode: "decoded-and-response", a pair of that and the response. Otherwise it holds the cause of its failure, defect or interruption. To tell whether the body was read, compare the result, or its first item, with ctx.response: a call returns the response itself only when it didn't decode it. It sees the final outcome, statusErrors and decoding included, which suits logging and metrics.
Fetch.Plugin.OnRequest
The onRequest hook: returns the request to send, possibly changed.
Fetch.Plugin.OnResponse
The onResponse hook: returns the response, possibly changed, or fails. Sees non-2xx responses too.
Fetch.Plugin.Options
The options type of plugin P.
Fetch.Plugin.Override
What one plugin accepts as a per-request override: false to skip it, or a partial of its options. Plugins without options accept only false. Keys set to undefined keep their default.
Fetch.Plugin.Overrides
The plugins option of a call: an override per plugin name in Ps. Unknown names are compile errors, including when the client has no plugins. Plugins whose name isn't a string literal can't be overridden (they'd make every name valid).
Fetch.Plugin.Services
The union of services the plugins in Ps require. make requires them once; calls on the client don't. unknown if a plugin's types were erased.
Fetch.Plugin.Upstream
The client a plugin's wrap receives: the rest of the chain.
Fetch.Plugin.UpstreamError
Stands for the errors of everything inside a plugin's wrap: the network, the library's other errors and inner plugins' errors. It's opaque on purpose; a wrap can only pass it through.
Fetch.Plugin.UpstreamServices
Stands for the services required by everything inside a plugin's wrap. Opaque, like UpstreamError.
Fetch.Plugin.Wrap
The wrap hook: wraps the rest of the chain (client). Its error and service types are opaque placeholders, so a wrap can add errors and services but can't drop the ones from further in. options reads this call's merged options, and route this call's route (see PluginContext).
Fetch.PluginContext
What a plugin hook receives besides the request or response.
Prop
Type
Fetch.PluginExitContext
What a plugin's onExit hook receives besides the call's Exit: the fields of PluginContext, and
response: the response the plugin chain returned, whose status was checked and whose body was decoded. When a plugin failed after a response arrived, the last response the network sent (its body may not have been read).undefinedwhen no response arrived: a network failure, a timeout, or a plugin that failed first. Itsrequestis the one that was sent, after every plugin'sonRequest.durationMs: how long the call took, in whole milliseconds measured with Effect'sClock, from when its request entered the plugin chain until the status was checked and the body decoded. Retries made by a plugin'swrapare included.
Prop
Type
Endpoints and services
Guide: Endpoints or methods.
Fetch.endpoint
Defines an endpoint without a client: a route like "GET /users/:id" and the schemas and headers to call it with. You get back plain data, an UnboundEndpoint, that you can export from module level next to its schemas. client.bind(definition) turns it into an Endpoint of that client: the same one client.endpoint(route, definition) makes.
- The route is checked as you type, as with
client.endpoint. A route that isn't valid (which the types prevent) throws here, when the module loads. - With an
inputschema,bodyis required on every call and typed by it.GET,HEAD,OPTIONSandTRACEendpoints take noinput. - Without
error, the endpoint uses thedefaultErrorof the client it's bound to. statusErrors(seeStatusErrorMap) are tried before those of the client it's bound to.- With a
queryschema (seeQuerySchema), each call'squeryis typed and encoded by it, and required when the schema has required fields. - With
stream: "sse"orstream: "ndjson", each call of the bound endpoint returns aStreamof the body's values. Astreamthat isn't one of those, or that comes withresponseModeor aFetch.bytes()output, throws here. - Plugin overrides are given when binding: a definition doesn't know which plugins a client has.
definition.url(options)builds the URL a call would go to, without the client'sbaseUrl.
Fetch.Endpoints
Declares a module's endpoints as a service class: one class that is the service key, its layer and its definitions.
Fetch.AnyUnboundEndpoint
Any UnboundEndpoint, whatever its route and schemas. Use it to constrain a parameter that takes definitions.
Fetch.BindAllMethod
The signature of client.bindAll: binds a record of definitions at once, as client.bind binds each one. Ps, DefaultEB and ClientSE are the client's, as in BindMethod.
Fetch.BindMethod
The signature of client.bind: turns an UnboundEndpoint into an Endpoint of the client, the same one client.endpoint makes from the same route and definition.
Ps: the client's plugins.DefaultEB: the client'sdefaultErrorschema, used when the definition has noerror.ClientSE: the client'sstatusErrorsmap, orundefinedwithout one.
Fetch.BindOptions
What client.bind takes besides the definition: headers and plugin overrides for every call of the bound endpoint.
Prop
Type
Fetch.BoundEndpoint
The endpoint a client makes from one entry of EndpointDefinitions: what client.bind returns for that definition. Ps, DefaultEB and ClientSE are the client's, as in BindMethod.
Fetch.BoundEndpoints
The endpoints client.bindAll makes from a record of EndpointDefinitions: one Endpoint for each entry, under the same name.
Fetch.Endpoint
An endpoint made by client.endpoint or client.bind: a function that sends its request with the options of one call, and returns the same Effect as the equivalent client method. With stream, it returns a Stream of the body's values instead, as api.sse and api.ndjson do. To page through a list endpoint, pass it to Fetch.paginate.
Fetch.EndpointArgs
The arguments of an endpoint call: the options object T is required when route R has path params, the endpoint has an input schema, or its query schema QS has required fields, and optional otherwise.
Fetch.EndpointBody
The body option of an endpoint call: not allowed on GET, HEAD, OPTIONS and TRACE endpoints, required and typed by the schema when the endpoint has an input, and optional otherwise (sent according to its runtime type, like a call's body).
Fetch.EndpointDefinition
What an endpoint is defined with, besides its route. Everything is optional.
Prop
Type
Fetch.EndpointDefinitions
What client.bindAll and Fetch.Endpoints take: a record of definitions made with endpoint, by the name each endpoint gets, each entry checked by EndpointEntry. D is the record's own type, and Ps the client's plugins. Names are strings: symbol keys are left out.
Fetch.EndpointEntry
How client.bindAll and Fetch.Endpoints check one entry of a record of definitions, given the entry's own type E and the client's plugins Ps. An entry is a definition made with endpoint, or a pair of a definition and the BindOptions to bind it with. A pair's options are checked as client.bind checks them, so a misspelt option or plugin name is an error.
Fetch.EndpointMethod
The signature of client.endpoint: defines an Endpoint from a route and an EndpointDefinition.
Ps: the client's plugins.DefaultEB: the client'sdefaultErrorschema, used when the endpoint has noerror.ClientSE: the client'sstatusErrorsmap, orundefinedwithout one.
Fetch.EndpointOptions
The options of one endpoint call: params for the route's path (see ParamsOption), body (see EndpointBody), query, headers, plugins and responseMode. The schemas are fixed by the endpoint.
Q: the type ofquerywithout a query schema, checked withQueryOf. Defaults toQueryInput.M: the call'sResponseMode, which wins over the endpoint's, orundefinedwithout one.QS: the endpoint'squeryschema, which typesquery(seeEndpointQuery), orundefinedwithout one.
Fetch.EndpointQuery
The query option of an endpoint call. With a query schema (see QuerySchema), it's typed by the schema's Type, and required when that has required fields. Without one, it's any QueryInput, typed as Q.
Fetch.EndpointRoute
The routes endpoint accepts: an uppercase HTTP method, one space, then a path that starts with / or an absolute http:// or https:// URL.
Fetch.EndpointsClass
A service class whose service is a record of endpoints: what Endpoints returns, to extend.
Fetch.EndpointUrlArgs
The arguments of endpoint.url: its EndpointUrlOptions, which can be left out when nothing in them is required.
Fetch.EndpointUrlOptions
What endpoint.url takes: params for the route's path (see ParamsOption) and query (see EndpointQuery), as a call takes them.
Fetch.QuerySchema
A schema for an endpoint's query: an object schema, usually a Schema.Struct, whose fields are the query parameters. A call's query is then typed by the schema's Type, and encoded with it before it's sent. A Schema.Class works too, and its calls take an instance.
Fetch.RouteMethod
The HTTP method of route R ("GET /users/:id" gives "GET").
Fetch.RoutePath
The path of route R, everything after the method and the space ("GET /users/:id" gives "/users/:id").
Fetch.UnboundDefinition
What endpoint defines an endpoint with, besides its route: an EndpointDefinition without plugins. Everything is optional.
output: decodes the 2xx body, read as JSON, or as text or bytes withFetch.text()andFetch.bytes(). Without it, the endpoint succeeds with the rawHttpClientResponse.error: decodes non-2xx bodies intoHttpError.body. Without it, the endpoint uses thedefaultErrorof the client it's bound to.statusErrors: turns error responses into your own errors, by status (seeStatusErrorMap). Tried before those of the client it's bound to.input: encodesbodybefore it's sent as JSON, and makesbodyrequired on every call. Not allowed onGET,HEAD,OPTIONSandTRACEendpoints, which take no body.headers: sent with every call, over the client's headers. Headers given when binding, then a call's own, win over them. Unlike the client's headers, these can setcontent-type.responseMode: what every call succeeds with (seeResponseMode). A call's ownresponseModewins.query: a schema for the query parameters (seeQuerySchema). Each call'squeryis then typed by it, and encoded with it.stream:"sse"or"ndjson"makes every call return aStreamof the body's values (seeStreamFormat).
Fetch.UnboundEndpoint
An endpoint defined without a client, by endpoint: its route, schemas and headers, as plain data. client.bind turns it into an Endpoint of that client, the same one client.endpoint makes from the same route and definition.
Fetch.ValidRoute
The type of endpoint's route argument: R itself when it's an EndpointRoute, otherwise the list of "<METHOD> /" starts.
Streaming
Guide: Streaming responses.
Fetch.SseEvent
One Server-Sent Event, as api.sse and SSE endpoints give it (see StreamElement).
Prop
Type
Fetch.StreamElement
What a stream in format St gives for each value, with the output schema O:
"sse": anSseEventwhosedatahasO's type, or is astringwithoutoutput;"ndjson":O's type, orunknown(the parsed JSON) withoutoutput.
Fetch.StreamFormat
How a streamed response body is split into values:
"sse": Server-Sent Events (text/event-stream), one value per event (seeSseEvent)."ndjson": newline-delimited JSON (application/x-ndjson), one value per line.
Fetch.StreamMethod
The signature of api.sse and api.ndjson: sends a request, and gives its response body as a Stream of values in format St, each a StreamElement. It takes StreamOptions.
St: theStreamFormat.Ps: the client's plugins.DefaultEB: the client'sdefaultErrorschema.ClientSE: the client'sstatusErrorsmap, orundefined.
Fetch.StreamOptions
The options of api.sse and api.ndjson: those of a call, without responseMode, and with method.
method: the request's method. Defaults to"GET". Streaming APIs that take a request body, such as those of language models, use"POST".GET,HEAD,OPTIONSandTRACEtake nobodyorinput.output: decodes each value (seeStreamElement).Fetch.text()gives each value's text;Fetch.bytes()can't be used.params,query,headers,body,input,error,statusErrorsandplugins: as for any call.
Pagination
Guide: Pagination.
Fetch.paginate
Pages through a list, as a Stream of pages: it calls endpoint (a PageEndpoint) for the first page, then for the next one while next gives a state, and stops after the page for which it gives Option.none(). See PaginateOptions for start, request and next. Each page is one value of the stream, so a page that is a list stays a list: Stream.flattenIterable gives its items instead.
Fetch.PageEndpoint
An endpoint paginate can page through: one made by client.endpoint or client.bind, whose calls return an Effect. A definition made by Fetch.endpoint needs binding first, and a stream endpoint can't be paged.
Fetch.PageOf
One page of endpoint EP: its output's type, or the raw response without output. It's what paginate's stream gives, and what PaginateOptions' next gets.
Fetch.PageRequest
The options of one page's call, as PaginateOptions' request returns them for endpoint EP: params, body, query and headers, typed as for any call of the endpoint.
Fetch.PageResponse
What next gets as the response of a page of endpoint EP: the response when the endpoint's responseMode is "decoded-and-response", for cursors in headers, and undefined otherwise.
Fetch.PaginateOptions
How paginate goes from page to page, with a state S, such as a page number or a cursor.
Prop
Type