Skip to content

feat: Endpoint.update programmable sideeffects #843

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

Merged
merged 3 commits into from
May 24, 2021
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
6 changes: 6 additions & 0 deletions __tests__/new.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,12 @@ export class FutureArticleResource extends CoolerArticleResource {
return instanceFetch(this.url(), this.getFetchInit(body));
},
url: this.listUrl.bind(this),
update: (newid: string) => ({
[this.list().key({})]: (existing: string[] = []) => [
newid,
...existing,
],
}),
});
}

Expand Down
78 changes: 75 additions & 3 deletions packages/core/src/state/__tests__/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ArticleResourceWithOtherListUrl,
PaginatedArticleResource,
} from '__tests__/common';
import { PaginatedArticleResource as PaginatedArticle } from '__tests__/new';
import { DELETED, schema } from '@rest-hooks/normalizr';

import reducer, { initialState } from '../reducer';
Expand All @@ -19,7 +20,7 @@ import {
FETCH_TYPE,
RESET_TYPE,
} from '../../actionTypes';
import createFetch from '../actions/createFetch';
import { createReceive } from '../actions';

describe('reducer', () => {
describe('singles', () => {
Expand All @@ -40,8 +41,9 @@ describe('reducer', () => {
payload: { id, title: 'hello' },
};
const iniState = initialState;
const newState = reducer(iniState, action);
let newState = initialState;
it('should update state correctly', () => {
newState = reducer(iniState, action);
expect(newState).toMatchSnapshot();
});
it('should overwrite existing entity', () => {
Expand Down Expand Up @@ -193,7 +195,7 @@ describe('reducer', () => {
expect(newState.entities[ArticleResource.key]).toEqual(expectedEntities);
});

describe('optimistic update', () => {
describe('updaters', () => {
describe('Update on get (pagination use case)', () => {
const shape = PaginatedArticleResource.listShape();
function makeOptimisticAction(
Expand Down Expand Up @@ -385,6 +387,76 @@ describe('reducer', () => {
});
});

describe('endpoint.update', () => {
describe('Update on get (pagination use case)', () => {
const endpoint = PaginatedArticle.list();

const iniState: any = {
...initialState,
entities: {
[PaginatedArticle.key]: {
'10': PaginatedArticle.fromJS({ id: 10 }),
},
},
results: {
[PaginatedArticle.list().key({})]: { results: ['10'] },
},
};

it('should insert a new page of resources into a list request', () => {
const action = createReceive(
{ results: [{ id: 11 }, { id: 12 }] },
{
...endpoint,
key: endpoint.key({ cursor: 2 }),
update: (nextpage: { results: string[] }) => ({
[PaginatedArticle.list().key({})]: (
existing: { results: string[] } = { results: [] },
) => ({
...existing,
results: [...existing.results, ...nextpage.results],
}),
}),
dataExpiryLength: 600000,
},
);
const newState = reducer(iniState, action);
expect(newState.results[PaginatedArticle.list().key({})]).toStrictEqual(
{
results: ['10', '11', '12'],
},
);
});

it('should insert correctly into the beginning of the list request', () => {
const newState = reducer(
iniState,
createReceive(
{ results: [{ id: 11 }, { id: 12 }] },
{
...endpoint,
key: endpoint.key({ cursor: 2 }),
update: (nextpage: { results: string[] }) => ({
[PaginatedArticle.list().key({})]: (
existing: { results: string[] } = { results: [] },
) => ({
...existing,
results: [...nextpage.results, ...existing.results],
}),
}),
dataExpiryLength: 600000,
},
),
);
expect(newState.results[PaginatedArticle.list().key({})]).toStrictEqual(
{
results: ['11', '12', '10'],
},
);
});
});
});

it('invalidates resources correctly', () => {
const id = 20;
const action: InvalidateAction = {
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/state/actions/createReceive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ interface Options<
S extends Schema | undefined = any,
> extends Pick<
FetchAction<Payload, S>['meta'],
'schema' | 'key' | 'type' | 'updaters'
'schema' | 'key' | 'type' | 'updaters' | 'update'
> {
dataExpiryLength: NonNullable<FetchOptions['dataExpiryLength']>;
}
Expand All @@ -34,7 +34,7 @@ export default function createReceive<
S extends Schema | undefined = any,
>(
data: Payload,
{ schema, key, updaters, dataExpiryLength }: Options<Payload, S>,
{ schema, key, updaters, update, dataExpiryLength }: Options<Payload, S>,
): ReceiveAction<Payload, S> {
/* istanbul ignore next */
if (process.env.NODE_ENV === 'development' && dataExpiryLength < 0) {
Expand All @@ -48,6 +48,7 @@ export default function createReceive<
expiresAt: now + dataExpiryLength,
};
meta.updaters = updaters;
meta.update = update;
return {
type: RECEIVE_TYPE,
payload: data,
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/state/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ export default function reducer(
[action.meta.key]: result,
};
results = applyUpdatersToResults(results, result, action.meta.updaters);
if (action.meta.update) {
const updaters = action.meta.update(result);
Object.keys(updaters).forEach(key => {
results[key] = updaters[key](results[key]);
});
}
return {
entities: mergeDeepCopy(
state.entities,
Expand Down
17 changes: 10 additions & 7 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
import { NormalizedIndex } from '@rest-hooks/normalizr';
import type {
UpdateFunction,
AbstractInstanceType,
Schema,
FetchFunction,
EndpointExtraOptions,
} from '@rest-hooks/endpoint';
import { Middleware } from '@rest-hooks/use-enhanced-reducer';
import { FSAWithPayloadAndMeta, FSAWithMeta, FSA } from 'flux-standard-action';

Expand All @@ -20,6 +13,14 @@ import {
INVALIDATE_TYPE,
} from './actionTypes';

import type {
UpdateFunction,
AbstractInstanceType,
Schema,
FetchFunction,
EndpointExtraOptions,
} from '@rest-hooks/endpoint';

export type { AbstractInstanceType, UpdateFunction };

export type ReceiveTypes = typeof RECEIVE_TYPE;
Expand Down Expand Up @@ -66,6 +67,7 @@ export interface ReceiveMeta<S extends Schema | undefined> {
schema: S;
key: string;
updaters?: Record<string, UpdateFunction<S, any>>;
update?: (result: any) => Record<string, (...args: any) => any>;
date: number;
expiresAt: number;
}
Expand Down Expand Up @@ -97,6 +99,7 @@ interface FetchMeta<
schema: S;
key: string;
updaters?: Record<string, UpdateFunction<S, any>>;
update?: (result: any) => Record<string, (...args: any) => any>;
options?: FetchOptions;
throttle: boolean;
resolve: (value?: any | PromiseLike<any>) => void;
Expand Down
34 changes: 30 additions & 4 deletions packages/experimental/src/__tests__/useFetcher.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { FutureArticleResource } from '__tests__/new';
import nock from 'nock';
import { useCache } from '@rest-hooks/core';
import { useCache, useResource } from '@rest-hooks/core';

// relative imports to avoid circular dependency in tsconfig references
import {
Expand All @@ -24,6 +24,29 @@ export const createPayload = {
tags: ['a', 'best', 'react'],
};

export const nested = [
{
id: 5,
title: 'hi ho',
content: 'whatever',
tags: ['a', 'best', 'react'],
author: {
id: 23,
username: 'bob',
},
},
{
id: 3,
title: 'the next time',
content: 'whatever',
author: {
id: 23,
username: 'charles',
email: '[email protected]',
},
},
];

for (const makeProvider of [makeCacheProvider, makeExternalCacheProvider]) {
describe(`${makeProvider.name} => <Provider />`, () => {
// TODO: add nested resource test case that has multiple partials to test merge functionality
Expand All @@ -50,6 +73,9 @@ for (const makeProvider of [makeCacheProvider, makeExternalCacheProvider]) {
.reply(403, {})
.get(`/article-cooler/666`)
.reply(200, '')
.get(`/article-cooler/`)
.reply(200, nested)

.post(`/article-cooler/`)
.reply(200, createPayload);

Expand Down Expand Up @@ -105,7 +131,7 @@ for (const makeProvider of [makeCacheProvider, makeExternalCacheProvider]) {
};
});

/*it('should update on create', async () => {
it('should update on create', async () => {
const { result, waitForNextUpdate } = renderRestHook(() => {
const articles = useResource(FutureArticleResource.list(), {});
const fetch = useFetcher();
Expand All @@ -115,7 +141,7 @@ for (const makeProvider of [makeCacheProvider, makeExternalCacheProvider]) {
await result.current.fetch(FutureArticleResource.create(), {
id: 1,
});
expect(result.current.articles.map(({ id }) => id)).toEqual([5, 3, 1]);
});*/
expect(result.current.articles.map(({ id }) => id)).toEqual([1, 5, 3]);
});
});
}
21 changes: 10 additions & 11 deletions packages/experimental/src/createFetch.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import type { FetchAction } from '@rest-hooks/core';
import { actionTypes } from '@rest-hooks/core';

import { UpdateFunction } from './types';

import type { FetchAction } from '@rest-hooks/core';
import type { EndpointInterface } from '@rest-hooks/endpoint';

/** Requesting a fetch to begin
*
* @param endpoint
* @param options { args, throttle }
*/
export default function createFetch<E extends EndpointInterface>(
export default function createFetch<
E extends EndpointInterface & { update?: UpdateFunction<E> },
>(
endpoint: E,
{ args, throttle }: { args: readonly [...Parameters<E>]; throttle: boolean },
): FetchAction {
Expand All @@ -32,15 +37,9 @@ export default function createFetch<E extends EndpointInterface>(
: /* istanbul ignore next */ new Date(),
};

/*if (endpoint.update) {
meta.updaters = updateParams.reduce(
(accumulator: object, [toShape, toParams, updateFn]) => ({
[toShape.getFetchKey(toParams)]: updateFn,
...accumulator,
}),
{},
);
}*/
if (endpoint.update) {
meta.update = endpoint.update;
}

if (endpoint.optimisticUpdate) {
meta.optimisticResponse = endpoint.optimisticUpdate(...args);
Expand Down
14 changes: 14 additions & 0 deletions packages/experimental/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Normalize } from '@rest-hooks/endpoint';

import type { EndpointInterface, ResolveType } from '@rest-hooks/endpoint';

type ResultEntry<E extends EndpointInterface> = E['schema'] extends undefined
? ResolveType<E>
: Normalize<E>;

export type UpdateFunction<
Source extends EndpointInterface,
Updaters extends Record<string, any> = Record<string, any>,
> = (
source: ResultEntry<Source>,
) => { [K in keyof Updaters]: (result: Updaters[K]) => Updaters[K] };
3 changes: 2 additions & 1 deletion packages/experimental/src/useFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import { DispatchContext } from '@rest-hooks/core';
import { useContext, useCallback } from 'react';

import createFetch from './createFetch';
import { UpdateFunction } from './types';

/** Build an imperative dispatcher to issue network requests. */
export default function useFetcher(
throttle = false,
): <E extends EndpointInterface>(
): <E extends EndpointInterface & { update?: UpdateFunction<E> }>(
endpoint: E,
...args: readonly [...Parameters<E>]
) => ReturnType<E> {
Expand Down