Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Response headers in createJson* mapData #523

Merged
merged 21 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from 14 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
5 changes: 5 additions & 0 deletions .changeset/happy-socks-know.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@farfetched/core": minor
---

Pass response original `headers` to `mapData` callback in `createJsonQuery`
11 changes: 9 additions & 2 deletions apps/website/docs/api/factories/create_json_query.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,15 @@ Config fields:
- `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.
- `validate?`: [_Validator_](/api/primitives/validator) allows you to dynamically validate received data.
- `mapData?`: optional mapper for the response data, available overloads:
- `({ result, params }) => mapped`
- `{ source: Store, fn: (data, { result, params }) => mapped }`

- `(res) => mapped`
- `{ source: Store, fn: (data, res) => mapped }`

`res` object contains:

- `result`: parsed and validated response data
- `params`: params which were passed to the [_Query_](/api/primitives/query)
- `headers`: <Badge type="tip" text="since v0.13" /> raw response headers

- `concurrency?`: concurrency settings for the [_Query_](/api/primitives/query)
::: danger Deprecation warning
Expand Down
1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
},
"scripts": {
"test:run": "vitest run --typecheck",
"test:watch": "vitest watch --typecheck",
"build": "vite build",
"size": "size-limit",
"publint": "node ../../tools/scripts/publint.mjs",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,11 @@ describe('fetch/api.response.all_in_one', () => {
});

expect(watcher.listeners.onDoneData).toHaveBeenCalledWith({
data: [1, 2],
errors: null,
result: {
data: [1, 2],
errors: null,
},
meta: expect.anything(),
});
});

Expand Down
15 changes: 12 additions & 3 deletions packages/core/src/fetch/__tests__/json.response.data.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ describe('fetch/json.response.data', () => {
params: { body: {} },
});

expect(watcher.listeners.onDoneData).toBeCalledWith({ test: 'value' });
expect(watcher.listeners.onDoneData).toBeCalledWith({
result: { test: 'value' },
meta: expect.anything(),
});
});

test('empty body as null', async () => {
Expand All @@ -74,7 +77,10 @@ describe('fetch/json.response.data', () => {
});

expect(watcher.listeners.onFailData).not.toBeCalled();
expect(watcher.listeners.onDoneData).toBeCalledWith(null);
expect(watcher.listeners.onDoneData).toBeCalledWith({
result: null,
meta: expect.anything(),
});
});

test('empty body without header as null', async () => {
Expand All @@ -92,6 +98,9 @@ describe('fetch/json.response.data', () => {
});

expect(watcher.listeners.onFailData).not.toBeCalled();
expect(watcher.listeners.onDoneData).toBeCalledWith(null);
expect(watcher.listeners.onDoneData).toBeCalledWith({
result: null,
meta: expect.anything(),
});
});
});
4 changes: 2 additions & 2 deletions packages/core/src/fetch/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export function createApiRequest<
DynamicRequestConfig<B> & {
method: HttpMethod;
},
ApiRequestResult,
{ result: ApiRequestResult; meta: { headers: Headers } },
ApiRequestError
>(
async ({
Expand Down Expand Up @@ -180,7 +180,7 @@ export function createApiRequest<
}
}

return prepared;
return { result: prepared, meta: { headers: response.headers } };
}
);

Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export {
type RemoteOperationParams,
} from './remote_operation/type';
export { onAbort } from './remote_operation/on_abort';
export { Meta, Result } from './remote_operation/store_meta';

// Validation public API
export { type ValidationResult, type Validator } from './validation/type';
Expand Down
8 changes: 6 additions & 2 deletions packages/core/src/mutation/create_json_mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
import { type Mutation } from './type';
import { concurrency } from '../concurrency/concurrency';
import { onAbort } from '../remote_operation/on_abort';
import { Meta, Result } from '../remote_operation/store_meta';

// -- Shared --

Expand Down Expand Up @@ -222,10 +223,13 @@ export function createJsonMutation(config: any): Mutation<any, any, any> {
name: config.name,
});

const executeFx = createEffect((c: any) => {
const executeFx = createEffect(async (c: any) => {
const abortController = new AbortController();
onAbort(() => abortController.abort());
return requestFx({ ...c, abortController });

const { result, meta } = await requestFx({ ...c, abortController });

return { [Result]: result, [Meta]: meta };
});

headlessMutation.__.executeFx.use(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,30 @@ describe('createJsonQuery', () => {
request: { url: 'http://api.salo.com', method: 'GET' as const },
response: {
contract: unknownContract,
mapData: ({ result, params }) => {
mapData: ({ result, params, headers }) => {
expectTypeOf(result).toEqualTypeOf<unknown>();
expectTypeOf(params).toEqualTypeOf<string>();
expectTypeOf(headers).toEqualTypeOf<Headers | undefined>();

return 12;
},
},
});
});

test('stora and callbacl', () => {
test('store and callback', () => {
createJsonQuery({
request: { url: 'http://api.salo.com', method: 'GET' as const },
response: {
contract: unknownContract,
mapData: {
source: createStore(12),
fn: ({ result, params }, source) => {
fn: ({ result, params, headers }, source) => {
expectTypeOf(result).toEqualTypeOf<unknown>();
expectTypeOf(params).toEqualTypeOf<string>();
expectTypeOf(source).toEqualTypeOf<number>();
expectTypeOf(headers).toEqualTypeOf<Headers | undefined>();

return 12;
},
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { setTimeout } from 'node:timers/promises';
import { allSettled, createStore, fork } from 'effector';
import { describe, test, expect, vi } from 'vitest';

import { unknownContract } from '../../contract/unknown_contract';
import { createJsonQuery } from '../create_json_query';
import { declareParams } from '../../remote_operation/params';
import { Contract } from '../../contract/type';
import { fetchFx } from '../../fetch/fetch';

describe('remote_data/query/json.response.map_data', () => {
// Does not matter
Expand Down Expand Up @@ -94,4 +96,117 @@ describe('remote_data/query/json.response.map_data', () => {

expect(scope.getState(query.$data)).toBe(transformed);
});

describe('metaResponse', () => {
test('simple callback', async () => {
const query = createJsonQuery({
request,
response: {
contract: unknownContract,
mapData: ({ result, headers }) => {
expect(headers?.get('X-Test')).toBe('42');

return result;
},
},
});

// We need to mock it on transport level
// because we can't pass meta to executeFx
const scope = fork({
handlers: [
[
fetchFx,
() =>
new Response(JSON.stringify({}), {
headers: { 'X-Test': '42' },
}),
],
],
});

await allSettled(query.start, { scope });

expect(scope.getState(query.$data)).toEqual({});
});

test('sourced callback', async () => {
const query = createJsonQuery({
request,
response: {
contract: unknownContract,
mapData: {
source: createStore(''),
fn: ({ result, headers }, s) => {
expect(headers?.get('X-Test')).toBe('42');

return result;
},
},
},
});

// We need to mock it on transport level
// because we can't pass meta to executeFx
const scope = fork({
handlers: [
[
fetchFx,
() =>
new Response(JSON.stringify({}), {
headers: { 'X-Test': '42' },
}),
],
],
});

await allSettled(query.start, { scope });

expect(scope.getState(query.$data)).toEqual({});
});

test('do not mix meta between calls', async () => {
const query = createJsonQuery({
params: declareParams<string>(),
request: {
url: (params) => `http://api.salo.com/${params}`,
method: 'GET' as const,
},
response: {
contract: unknownContract,
mapData: ({ result, params, headers }) => {
expect(headers?.get('X-Test')).toBe(
`http://api.salo.com/${params}`
);

return result;
},
},
});

// We need to mock it on transport level
// because we can't pass meta to executeFx
const scope = fork({
handlers: [
[
fetchFx,
(req: Request) =>
setTimeout(1).then(
() =>
new Response(JSON.stringify({}), {
headers: { 'X-Test': req.url },
})
),
],
],
});

await Promise.all([
allSettled(query.start, { scope, params: '1' }),
allSettled(query.start, { scope, params: '2' }),
]);

expect(scope.getState(query.$data)).toEqual({});
});
});
});
16 changes: 10 additions & 6 deletions packages/core/src/query/create_json_query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { unknownContract } from '../contract/unknown_contract';
import { type Validator } from '../validation/type';
import { concurrency } from '../concurrency/concurrency';
import { onAbort } from '../remote_operation/on_abort';
import { Result, Meta } from '../remote_operation/store_meta';

// -- Shared

Expand Down Expand Up @@ -114,7 +115,7 @@ export function createJsonQuery<
response: {
contract: Contract<unknown, Data>;
mapData: DynamicallySourcedField<
{ result: Data; params: Params },
{ result: Data; params: Params; headers?: Headers },
TransformedData,
DataSource
>;
Expand Down Expand Up @@ -146,7 +147,7 @@ export function createJsonQuery<
response: {
contract: Contract<unknown, Data>;
mapData: DynamicallySourcedField<
{ result: Data; params: Params },
{ result: Data; params: Params; headers?: Headers },
TransformedData,
DataSource
>;
Expand Down Expand Up @@ -226,7 +227,7 @@ export function createJsonQuery<
response: {
contract: Contract<unknown, Data>;
mapData: DynamicallySourcedField<
{ result: Data; params: void },
{ result: Data; params: void; headers?: Headers },
TransformedData,
DataSource
>;
Expand Down Expand Up @@ -256,7 +257,7 @@ export function createJsonQuery<
response: {
contract: Contract<unknown, Data>;
mapData: DynamicallySourcedField<
{ result: Data; params: void },
{ result: Data; params: void; headers?: Headers },
TransformedData,
DataSource
>;
Expand Down Expand Up @@ -350,10 +351,13 @@ export function createJsonQuery(config: any) {
paramsAreMeaningless: true,
});

const executeFx = createEffect((c: any) => {
const executeFx = createEffect(async (c: any) => {
const abortController = new AbortController();
onAbort(() => abortController.abort());
return requestFx({ ...c, abortController });

const { result, meta } = await requestFx({ ...c, abortController });

return { [Result]: result, [Meta]: meta };
});

headlessQuery.__.executeFx.use(
Expand Down
Loading
Loading