Effect CommunityEC
Effect Community3y ago
20 replies
Rory

Existing Wrapper for Fetch with Effect in fp-ts

I may have not been able to find this in the docs. Is there something already existing that wraps fetch with Effect? I have some helpers scattered about I use with fp-ts that safely wrap fetch and it's irritating promise based data accessors. I can easily port things like this, don't want to reinvent the wheel. ex

export interface UnparsedJsonData {
  data: unknown
  _tag: "UnparsedJsonData"
}
export class JsonParseError extends Error {
  _tag = "JsonParseError";
  constructor(m?: string) {
    super(m);
  }
}
export const safeJson = (resp: Response) => TE.tryCatch<JsonParseError, UnparsedJsonData>(
  () => resp.json().then(d => { return { data: d, _tag: "UnparsedJsonData" }}),
  (e) => e instanceof Error ? new JsonParseError(e.message) : new JsonParseError(String(e))
);

export const
safeFetchJsonAlways =
(info: RequestInfo | URL, init?: RequestInit | undefined ) => pipe(
  TE.tryCatch(
    () => fetch(info, init),
    e => e instanceof Error ? new FetchNetworkError(e.message) : new FetchNetworkError(String(e))
  ),
  TE.bindTo('resp'),
  TE.bindW('j', ({resp}) => safeJson(resp)),
  TE.chainW(({resp, j}) => resp.ok ? TE.right(j) : TE.left(j)),
);
Was this page helpful?