@equinor/fusion-framework-module-http

中文文档
8.1.5发布于 2026/11/12ISCTypeScriptES Module近 30 天下载 1.4万
原始使用文档
文档目录16 节
  1. What This Package Gives You
  2. Mental Model
  3. Start Here If You Are New
  4. When To Use Which API
  5. Install
  6. Quick Start
  7. Public Entry Points
  8. Configuring Clients
  9. Core API
  10. Promise Or Observable?
  11. Selectors And Handlers
  12. Server-Sent Events
  13. Error Types
  14. Testing
  15. Advanced Guides
  16. Things To Remember

Fusion Framework HTTP Module

@equinor/fusion-framework-module-http is the HTTP layer for Fusion Framework applications and modules. It gives you a fetch-style client factory with framework-aware configuration, MSAL-aware requests, RxJS observables, and reusable request/response pipelines.

If you only remember one thing about this package, make it this: you configure clients once, and you create fresh client instances when you use them.

If you are new to Fusion Framework or just want to call an API, start with configureHttpClient(...), createClient(...), and json().

If you are building more advanced workflows, this package also supports RxJS observable composition, request and response stream inspection, custom selectors, request and response operators, MSAL-aware requests, and server-sent events.

What This Package Gives You

  • Named HTTP client configurations for each backend you talk to.
  • Fresh client instances so headers and handlers from one usage do not leak into the next.
  • Promise and Observable APIs on top of the same request pipeline.
  • Built-in support for JSON, blobs, and server-sent events.
  • Request and response handlers for cross-cutting behavior.
  • MSAL scope support when the auth module is available.

Mental Model

Think of the HTTP module as a client factory, not a singleton HTTP client.

  1. Configure a named client during app or module setup.
  2. Call createClient(name) when you need to make requests.
  3. Use fetch, json, blob, or sse$ on that client instance.
  4. Add shared behavior in onCreate, requestHandler, and responseHandler.

Each request goes through the same high-level flow:

  1. Resolve baseUri and request path into a full URL.
  2. Run request handlers.
  3. Emit the request on request$.
  4. Execute the fetch call.
  5. Run response handlers.
  6. Emit the response on response$.
  7. Apply an optional selector.

Start Here If You Are New

The simplest useful path looks like this:

  1. Register a named client for one backend.
  2. Create a client from that name where you need it.
  3. Call json() for normal API calls.

That gives you:

  • consistent base URLs
  • shared auth scope configuration
  • shared headers or guards through onCreate
  • one fresh client instance per usage

If you are unsure whether to use promises or observables, start with json(). Move to json$() when you need RxJS operators, cancellation by unsubscribe, or stream composition.

When To Use Which API

NeedUse
Call a normal JSON APIjson() or json$()
Work with the raw Responsefetch() or fetch$()
Download a file or blob responseblob() or blob$()
Consume a streaming text/event-stream endpointsse$()
Apply standard headers, scopes, or logging per backendnamed client configuration + onCreate

Install

pnpm add @equinor/fusion-framework-module-http

Quick Start

Configure a named client during setup:

configurator.configureHttpClient('catalog', {
  baseUri: '/api/catalog',
  defaultScopes: ['api://catalog-api/.default'],
  onCreate: (client) => {
    client.requestHandler.setHeader('X-App-Name', 'portal');
  },
});

Use the configured client after the framework is initialized:

type CatalogItem = {
  id: string;
  title: string;
};

const client = framework.modules.http.createClient('catalog');
const items = await client.json<CatalogItem[]>('/items');

What is happening here:

  • catalog is a named configuration, not a long-lived shared client instance.
  • createClient('catalog') creates a fresh client with the configured base URI, handlers, and default scopes.
  • json() runs the request pipeline and returns parsed JSON.

Public Entry Points

Entry pointPurpose
@equinor/fusion-framework-module-httpModule definition, configurator/provider helpers, exported errors, and shared client types
@equinor/fusion-framework-module-http/clientHttpClient, HttpClientMsal, and client-related types
@equinor/fusion-framework-module-http/operatorsHttpRequestHandler, HttpResponseHandler, ProcessOperators, capitalizeRequestMethodOperator, requestValidationOperator, sseMap, and operator types
@equinor/fusion-framework-module-http/selectorsjsonSelector, blobSelector, createSseSelector, ResponseSelector, and SSE selector types
@equinor/fusion-framework-module-http/errorsHttpResponseError, HttpJsonResponseError, and ServerSentEventResponseError

For most teams, the top-level package plus the selectors or operators subpaths are enough.

Configuring Clients

Use named clients when you want a stable configuration for a backend: a base URL, default MSAL scopes, shared headers, and request or response policies.

The HTTP module supports three common configuration styles:

  • named clients with configureHttpClient(name, options)
  • lower-level module configuration with configureHttp(...)
  • ad-hoc clients with createClient({ baseUri }) or createClient('https://...')

MSAL scope behavior is part of client configuration:

  • defaultScopes belong to the configured client
  • per-request scopes are appended to defaultScopes
  • token acquisition only happens when the auth module is available and the final scope list is non-empty

See Client Configuration for configuration options, onCreate, direct module integration, custom client classes, ad-hoc clients, and ClientNotFoundException behavior.

Core API

Each call to createClient() returns a fresh instance with its own handler state.

MethodReturnsUse it when
fetch(path, init?)Promise<Response | T>You want the raw Response, or you want to provide a custom selector
fetch$(path, init?)Observable<Response | T>You want RxJS composition or cancellation by unsubscribing
json(path, init?)Promise<T>You are calling a JSON API
json$(path, init?)Observable<T>You want the JSON API call as an observable
blob(path, init?)Promise<BlobResult>You are downloading a file or binary payload
blob$(path, init?)Observable<BlobResult>You want blob responses in an observable pipeline
sse$(path, init?, options?)Observable<ServerSentEvent<T>>You are consuming server-sent events
execute(method, path, init?)fetch, fetch$, json, or json$ resultYou need to pick one of those methods dynamically
abort()voidYou want to cancel every in-flight request started by this client instance

Deprecated aliases still exist, but new code should prefer fetch() and json() over fetchAsync() and jsonAsync().

Promise Or Observable?

  • Use promise methods when you just want the result of a single request.
  • Use observable methods when you want RxJS composition, cancellation by unsubscribe, or stream-based integration.
  • Observable methods are cold. Nothing is sent until you subscribe.
  • Promise methods are implemented with firstValueFrom(...) on the corresponding observable method.
  • request$ and response$ let you observe outgoing requests and incoming responses for that client instance.

In practical terms:

  • json('/items') is the simplest choice for page load or command-style calls.
  • json$('/items') is the better choice when the request depends on another stream such as route params, user selections, debounced search terms, refresh triggers, or SSE event handling.

See Observable Patterns for RxJS composition, cancellation, request and response inspection, and selector reuse.

Selectors And Handlers

Selectors and handlers solve different problems:

  • selectors shape the response value your application consumes
  • request handlers shape outgoing transport behavior
  • response handlers enforce response policies before selector parsing runs

Built-in selectors include jsonSelector, blobSelector, and createSseSelector. The default request pipeline includes capitalizeRequestMethodOperator() and requestValidationOperator().

See Selectors and Handlers for guidance on when to use each API, how to add reusable operators, and how to keep transport concerns separate from response parsing.

Server-Sent Events

Use client.sse$() when the endpoint returns text/event-stream and you want parsed event objects instead of manually reading the stream. For lower-level composition, use createSseSelector or sseMap.

See Server-Sent Events for sse$() usage, event filtering, heartbeat handling, abort behavior, lower-level SSE helpers, and ServerSentEventResponseError handling.

Error Types

ErrorWhen it is used
ClientNotFoundExceptioncreateClient(name) is called with a key that is neither configured nor an absolute http: or https: URL
HttpResponseErrorGeneric response or selector failure, including synchronous selector execution failures
HttpJsonResponseErrorJSON parsing failures or non-OK JSON responses
ServerSentEventResponseErrorInvalid SSE responses such as non-OK status, unreadable body, or wrong content type

Native fetch errors can still surface as well, including abort and network failures.

Testing

Register a short-circuiting middleware through configurator.http.addMiddleware(...) to answer requests without touching the network — no separate mock client or configurator is needed. createOpenApiMockMiddleware (@equinor/fusion-framework-module-http/mock) adapts an @equinor/fusion-openapi-mock instance into one for faking an entire OpenAPI document.

See Testing for the middleware contract and createOpenApiMockMiddleware.

Advanced Guides

  • Client Configuration: named clients, configureHttpClient, configureHttp, onCreate, custom client classes, and ad-hoc clients
  • Observable Patterns: fetch$, json$, request$, response$, cancellation, and RxJS composition
  • Selectors and Handlers: jsonSelector, blobSelector, request handlers, response handlers, and built-in operators
  • Server-Sent Events: sse$, createSseSelector, sseMap, event filtering, heartbeats, and abort behavior
  • Testing: the middleware contract, addMiddleware, and createOpenApiMockMiddleware

Things To Remember

  • createClient(name) throws ClientNotFoundException for unknown client keys.
  • hasClient(name) is useful when a client configuration may be optional.
  • json() and json$() stringify object bodies with JSON.stringify(...) and append JSON request headers.
  • fetch() and fetch$() leave the response untouched unless you provide a selector.
  • execute() currently supports fetch, fetch$, json, and json$ only.
  • If you configure a client through config.http.configureClient(name, callback), that callback is stored as onCreate and runs every time a new client instance is created.

版本与发布记录

@equinor/fusion-framework-module-http 共发布 183 个版本,首次发布于 2022/01/14;过去 12 个月发布了 24 个版本。

版本发布日期距今
8.1.5latest2026/11/121 天前
8.1.5-next.1next2026/11/112 天前
8.1.5-next.02026/10/2816 天前
8.1.42026/10/1727 天前
8.1.4-trusted-publishing-20261015-9dfe7602cd2a49a8a9df00d62c26e7304a82a85atrusted-publishing-202610152026/10/1629 天前
8.1.32026/10/121 个月前

其他发布通道:apploader → 6.3.3-apploader-be21a6b60eb13eee8bf869e75002d8634e9c50a9,cli-search-index → 7.0.6-cli-search-index.0,msal-v5 → 7.0.7-msal-v5.1,trusted-publishing-20261015 → 8.1.4-trusted-publishing-20261015-9dfe7602cd2a49a8a9df00d62c26e7304a82a85a,next → 8.1.5-next.1。

关于 @equinor/fusion-framework-module-http 的常见问题

如何安装 @equinor/fusion-framework-module-http?

在项目目录运行 npm install @equinor/fusion-framework-module-http,或使用 pnpm add / yarn add / bun add。

@equinor/fusion-framework-module-http 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@equinor/fusion-framework-module-http 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@equinor/fusion-framework-module-http 可以商用吗?

@equinor/fusion-framework-module-http 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@equinor/fusion-framework-module-http 的下载量有多少?

根据 npm 官方下载统计,@equinor/fusion-framework-module-http 在 2026/10/14 – 2026/11/12 这 30 天内被下载 14,405 次,日均约 480 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@equinor/fusion-framework-module-http 还在维护吗?

最新版本 8.1.5 发布于 2026/11/12(1 天前);至今共发布 183 个版本,其中过去 12 个月发布了 24 个;首次发布于 2022/01/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。