Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/wise-adults-doubt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@farfetched/core': minor
---

Added `request.fetch` feature to createJson\* methods, which allows to apply any valid `RequestInit` setting to underlying `fetch` call

The top-level `request.credentials` is deprecated in favor of `request.fetch.credentials`
3 changes: 2 additions & 1 deletion apps/website/docs/api/factories/create_json_mutation.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ Config fields:
- `body`: _[Sourced](/api/primitives/sourced) Json_, any value which can be serialized to JSON and parsed back without loses by JavaScript native module JSON. For example, `{ a: 1, b: 2 }`. Note that body cannot be used in `GET` and `HEAD` requests.
- `query?`: _[Sourced](/api/primitives/sourced) object_, keys of the object must be `String` and values must be `String` or `Array<String>` or (since v0.8) _[Sourced](/api/primitives/sourced) String_ containing ready-to-use query string
- `headers?`: _[Sourced](/api/primitives/sourced) object_, keys of the object must be `String` and values must be `String` or `Array<String>`
- `credentials?`: <Badge type="tip" text="since v0.7" /> _String_, [available values](https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials):
- `credentials?`: <Badge type="warning" text="deprecated" /> _String_, [available values](https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials). **Deprecated**: use `fetch.credentials` instead.
- `omit` — do not include credentials
- `same-origin` — include credentials only if the request URL is the same origin
- `include` — include credentials on all requests
- `fetch?`: <Badge type="tip" text="since v0.14.3" /> _Object or [Store](https://effector.dev/docs/api/effector/Store) with Object_, additional [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) options to pass to the underlying fetch request. This allows configuring options like `mode`, `cache`, `redirect`, `referrerPolicy`, `integrity`, `keepalive`, etc. If `credentials` is specified both at the top level and in `fetch`, the top-level value takes precedence.

- `response`: declarative rules to handle response from the API.
- `contract`: [_Contract_](/api/primitives/contract) allows you to validate the response and decide how your application should treat it — as a success response or as a failed one.
Expand Down
3 changes: 2 additions & 1 deletion apps/website/docs/api/factories/create_json_query.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ Config fields:
- `body`: _[Sourced](/api/primitives/sourced) Json_, any value which can be serialized to JSON and parsed back without loses by JavaScript native module JSON. For example, `{ a: 1, b: 2 }`. Note that body cannot be used in `GET` and `HEAD` requests.
- `query?`: _[Sourced](/api/primitives/sourced) object_, keys of the object must be `String` and values must be `String` or `Array<String>` or (since v0.8) _[Sourced](/api/primitives/sourced) String_ containing ready-to-use query string
- `headers?`: _[Sourced](/api/primitives/sourced) object_, keys of the object must be `String` and values must be `String` or `Array<String>`
- `credentials?`: <Badge type="tip" text="since v0.7" /> _String_, [available values](https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials):
- `credentials?`: <Badge type="warning" text="deprecated" /> _String_, [available values](https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials). **Deprecated**: use `fetch.credentials` instead.
- `omit` — do not include credentials
- `same-origin` — include credentials only if the request URL is the same origin
- `include` — include credentials on all requests
- `fetch?`: <Badge type="tip" text="since v0.14.3" /> _Object or [Store](https://effector.dev/docs/api/effector/Store) with Object_, additional [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) options to pass to the underlying fetch request. This allows configuring options like `mode`, `cache`, `redirect`, `referrerPolicy`, `integrity`, `keepalive`, etc. If `credentials` is specified both at the top level and in `fetch`, the top-level value takes precedence.

- `response`: declarative rules to handle response from the API.
- `contract`: [_Contract_](/api/primitives/contract) allows you to validate the response and decide how your application should treat it — as a success response or as a failed one.
Expand Down
199 changes: 199 additions & 0 deletions packages/core/src/fetch/__tests__/api.request.fetchOptions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import { allSettled, createStore, fork } from 'effector';
import { describe, test, expect, vi } from 'vitest';

import { createApiRequest, type FetchOptions } from '../api';
import { fetchFx } from '../fetch';

describe('fetch/api.request.fetch', () => {
// Does not matter
const mapBody = () => 'any body';
const url = 'https://api.salo.com';
const method = 'GET';

// Does not matter
const response = {
extract: async <T>(v: T) => v,
};

test('pass static fetch on creation to request', async () => {
const callApiFx = createApiRequest({
request: {
mapBody,
method,
url,
fetch: {
mode: 'cors',
cache: 'no-cache',
referrerPolicy: 'no-referrer',
},
},
response,
});

const fetchMock = vi.fn().mockResolvedValue(new Response('test'));

const scope = fork({ handlers: [[fetchFx, fetchMock]] });

await allSettled(callApiFx, { scope, params: {} });

const request = fetchMock.mock.calls[0][0] as Request;
expect(request.mode).toEqual('cors');
expect(request.cache).toEqual('no-cache');
expect(request.referrerPolicy).toEqual('no-referrer');
});

test('pass reactive fetch on creation to request', async () => {
const $fetch = createStore<FetchOptions>({
mode: 'cors',
cache: 'no-cache',
});

const callApiFx = createApiRequest({
request: { mapBody, method, url, fetch: $fetch },
response,
});

const fetchMock = vi.fn().mockResolvedValue(new Response('test'));

const scope = fork({ handlers: [[fetchFx, fetchMock]] });

// with original value
await allSettled(callApiFx, { scope, params: {} });
let request = fetchMock.mock.calls[0][0] as Request;
expect(request.mode).toEqual('cors');
expect(request.cache).toEqual('no-cache');

// with new value
await allSettled($fetch, {
scope,
params: { mode: 'no-cors', cache: 'force-cache' },
});
await allSettled(callApiFx, { scope, params: {} });
request = fetchMock.mock.calls[1][0] as Request;
expect(request.mode).toEqual('no-cors');
expect(request.cache).toEqual('force-cache');
});

test('top-level credentials takes precedence over fetch.credentials', async () => {
const callApiFx = createApiRequest({
request: {
mapBody,
method,
url,
credentials: 'include',
fetch: {
credentials: 'omit',
cache: 'no-cache',
},
},
response,
});

const fetchMock = vi.fn().mockResolvedValue(new Response('test'));

const scope = fork({ handlers: [[fetchFx, fetchMock]] });

await allSettled(callApiFx, { scope, params: {} });

const request = fetchMock.mock.calls[0][0] as Request;
// top-level credentials should win
expect(request.credentials).toEqual('include');
// other fetch should still apply
expect(request.cache).toEqual('no-cache');
});

test('fetch.credentials is used when top-level credentials is not set', async () => {
const callApiFx = createApiRequest({
request: {
mapBody,
method,
url,
fetch: {
credentials: 'include',
},
},
response,
});

const fetchMock = vi.fn().mockResolvedValue(new Response('test'));

const scope = fork({ handlers: [[fetchFx, fetchMock]] });

await allSettled(callApiFx, { scope, params: {} });

const request = fetchMock.mock.calls[0][0] as Request;
expect(request.credentials).toEqual('include');
});

test('pass fetch with keepalive option', async () => {
const callApiFx = createApiRequest({
request: {
mapBody,
method,
url,
fetch: {
keepalive: true,
},
},
response,
});

const fetchMock = vi.fn().mockResolvedValue(new Response('test'));

const scope = fork({ handlers: [[fetchFx, fetchMock]] });

await allSettled(callApiFx, { scope, params: {} });

const request = fetchMock.mock.calls[0][0] as Request;
expect(request.keepalive).toEqual(true);
});

test('pass fetch with redirect option', async () => {
const callApiFx = createApiRequest({
request: {
mapBody,
method,
url,
fetch: {
redirect: 'manual',
},
},
response,
});

const fetchMock = vi.fn().mockResolvedValue(new Response('test'));

const scope = fork({ handlers: [[fetchFx, fetchMock]] });

await allSettled(callApiFx, { scope, params: {} });

const request = fetchMock.mock.calls[0][0] as Request;
expect(request.redirect).toEqual('manual');
});

test('pass fetch with integrity option', async () => {
const integrityValue =
'sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC';

const callApiFx = createApiRequest({
request: {
mapBody,
method,
url,
fetch: {
integrity: integrityValue,
},
},
response,
});

const fetchMock = vi.fn().mockResolvedValue(new Response('test'));

const scope = fork({ handlers: [[fetchFx, fetchMock]] });

await allSettled(callApiFx, { scope, params: {} });

const request = fetchMock.mock.calls[0][0] as Request;
expect(request.integrity).toEqual(integrityValue);
});
});
24 changes: 22 additions & 2 deletions packages/core/src/fetch/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ export type HttpMethod =

export type RequestBody = Blob | BufferSource | FormData | string;

// Future-proof: automatically includes any new RequestInit fields from the browser
export type FetchOptions = Omit<
RequestInit,
'method' | 'headers' | 'body' | 'signal'
>;

// These settings can be defined only statically
export interface StaticOnlyRequestConfig<B> {
method: StaticOrReactive<HttpMethod>;
Expand All @@ -43,6 +49,7 @@ export interface StaticOnlyRequestConfig<B> {
export interface ExclusiveRequestConfigShared {
url: string;
credentials?: RequestCredentials;
fetch?: FetchOptions;
abortController?: AbortController;
}

Expand Down Expand Up @@ -139,17 +146,23 @@ export function createApiRequest<
query,
headers,
credentials,
fetch,
body,
abortController,
}) => {
const mappedBody = body ? config.request.mapBody(body) : null;

const request = new Request(formatUrl(url, query), {
...fetch,
method,
headers: formatHeaders(headers),
credentials,
body: mappedBody,
signal: abortController?.signal,
/**
* `credentials` is available both in `fetch` and in the top-level config.
* The top-level config was introduced much earlier, so it takes precedence.
*/
...(credentials !== undefined ? { credentials } : {}),
});

const response = await requestFx(request).catch((cause: RequestError) => {
Expand Down Expand Up @@ -240,6 +253,7 @@ export function createApiRequest<
query: normalizeStaticOrReactive(config.request.query),
headers: normalizeStaticOrReactive(config.request.headers),
credentials: normalizeStaticOrReactive(config.request.credentials),
fetch: normalizeStaticOrReactive(config.request.fetch),
body: normalizeStaticOrReactive(config.request.body),
},
mapParams(dynamicConfig: ApiRequestParams, staticConfig) {
Expand All @@ -250,11 +264,16 @@ export function createApiRequest<
// @ts-expect-error TS cannot infer type correctly, but there is always field in staticConfig or dynamicConfig
dynamicConfig.url;

const credentials: RequestCredentials =
const credentials: RequestCredentials | undefined =
staticConfig.credentials ??
// @ts-expect-error TS cannot infer type correctly, but there is always field in staticConfig or dynamicConfig
dynamicConfig.credentials;

const fetch: FetchOptions | undefined =
staticConfig.fetch ??
// @ts-expect-error TS cannot infer type correctly, but there is always field in staticConfig or dynamicConfig
dynamicConfig.fetch;

const body: B =
staticConfig.body ??
// @ts-expect-error TS cannot infer type correctly, but there is always field in staticConfig or dynamicConfig
Expand All @@ -276,6 +295,7 @@ export function createApiRequest<
query,
headers,
credentials,
fetch,
body,
abortController,
};
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export { type ValidationResult, type Validator } from './validation/type';
export { type Json } from 'effector';
export { type JsonObject } from './fetch/json';
export { type FetchApiRecord } from './fetch/lib';
export { type JsonApiRequestError } from './fetch/api';
export { type JsonApiRequestError, type FetchOptions } from './fetch/api';
export { fetchFx } from './fetch/fetch';

// Exposed errors
Expand Down
Loading