Skip to content
This repository has been archived by the owner on Nov 23, 2024. It is now read-only.

Commit

Permalink
Merge branch 'main' into enhance/fetch-base-query
Browse files Browse the repository at this point in the history
  • Loading branch information
msutkowski authored Nov 8, 2020
2 parents 8ecea84 + c65bc15 commit a2d2f7a
Show file tree
Hide file tree
Showing 6 changed files with 124 additions and 12 deletions.
10 changes: 10 additions & 0 deletions examples/svelte-counter/src/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import { QueryStatus } from '@rtk-incubator/simple-query/dist';
import { counterApi } from './services/counter';
import { store } from './store';
import Counter from './Counter.svelte'
let counters = [] as number[];
const { incrementCount, decrementCount } = counterApi.mutationActions;
Expand Down Expand Up @@ -48,4 +51,11 @@
<button on:click={() => store.dispatch(incrementCount(1, { track: false }))}>Increase</button>
<button on:click={() => store.dispatch(decrementCount(1, { track: false }))}>Decrease</button>
<button on:click={getCount} disabled={loading}>Refetch count</button>

<hr />
<h3>Custom counters!</h3><button on:click={() => { counters = [...counters, counters.length + 1] }}>Add counter</button>

{#each counters as id}
<Counter {id} />
{/each}
</main>
44 changes: 44 additions & 0 deletions examples/svelte-counter/src/Counter.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@

<script lang="ts">
export let id: number = null;
import { onMount } from 'svelte';
import { QueryStatus } from '@rtk-incubator/simple-query/dist';
import { counterApi } from './services/counter';
import { store } from './store';
const { incrementCountById, decrementCountById } = counterApi.mutationActions;
let incrementStatus, decrementStatus;
$: ({ data, status: getStatus, error } = counterApi.selectors.query.getCountById(id)($store));
$: ({ status: incrementStatus } = counterApi.selectors.query.getCountById(id)($store));
$: ({ status: decrementStatus } = counterApi.selectors.query.getCountById(id)($store));
$: loading = [incrementStatus, decrementStatus, getStatus].some(status => status === QueryStatus.pending);
onMount(() => {
store.dispatch(counterApi.queryActions.getCountById(id));
});
</script>

<style>
main {
padding: 0.5em;
}
.count {
color: #a74524;
text-transform: uppercase;
font-size: 2em;
font-weight: 100;
margin-right: 20px;
}
</style>

<main>
<span class="count">{data?.count || 0}</span>
<button on:click={() => store.dispatch(incrementCountById({ id, amount: 1 }, { track: false }))} disabled={loading}>Increase</button>
<button on:click={() => store.dispatch(decrementCountById({ id, amount: 1 }, { track: false }))} disabled={loading}>Decrease</button>
<small>(id: {id})</small>

</main>
33 changes: 33 additions & 0 deletions examples/svelte-counter/src/mocks/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { rest } from 'msw';
// high tech in-memory storage
let count = 0;

let counters = {};

export const handlers = [
rest.get('/error', (req, res, ctx) => {
return res(
Expand Down Expand Up @@ -41,4 +43,35 @@ export const handlers = [
rest.get('/count', (req, res, ctx) => {
return res(ctx.json({ count }));
}),
rest.get('/:id', (req, res, ctx) => {
const { id } = req.params;

const count = counters[id] || (counters[id] = 0);

return res(ctx.json({ count }));
}),
rest.put<{ amount: number }>('/:id/increment', (req, res, ctx) => {
const { amount } = req.body;
const { id } = req.params;

if (typeof counters[id] === 'undefined') {
return res(ctx.json({ message: 'Counter not found' }), ctx.status(402));
}

const count = (counters[id] = counters[id] + amount);

return res(ctx.json({ count }));
}),
rest.put<{ amount: number }>('/:id/decrement', (req, res, ctx) => {
const { amount } = req.body;
const { id } = req.params;

if (typeof counters[id] === 'undefined') {
return res(ctx.json({ message: 'Counter not found' }), ctx.status(402));
}

const count = (counters[id] = counters[id] - amount);

return res(ctx.json({ count }));
}),
];
34 changes: 27 additions & 7 deletions examples/svelte-counter/src/services/counter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,23 +36,43 @@ export const counterApi = createApi({
additional: 1,
},
}),
provides: [{ type: 'Counter' }],
provides: ['Counter'],
}),
incrementCount: build.mutation<CountResponse, number>({
query: (amount) => ({
url: `/increment`,
method: 'PUT',
body: { amount },
}),
invalidates: [{ type: 'Counter' }],
invalidates: ['Counter'],
}),
decrementCount: build.mutation<CountResponse, number>({
query: (amount) => ({
url: `decrement`,
method: 'PUT',
body: { amount },
query: (amount) => ({
url: `decrement`,
method: 'PUT',
body: { amount },
}),
invalidates: ['Counter'],
}),
getCountById: build.query<CountResponse, number>({
query: (id: number) => `${id}`,
provides: (_, id) => [{ type: 'Counter', id }],
}),
incrementCountById: build.mutation<CountResponse, { id: number; amount: number }>({
query: ({ id, amount }) => ({
url: `${id}/increment`,
method: 'PUT',
body: { amount },
}),
invalidates: (_, { id }) => [{ type: 'Counter', id }],
}),
decrementCountById: build.mutation<CountResponse, { id: number; amount: number }>({
query: ({ id, amount }) => ({
url: `${id}/decrement`,
method: 'PUT',
body: { amount },
}),
invalidates: [{ type: 'Counter' }],
invalidates: (_, { id }) => [{ type: 'Counter', id }],
}),
}),
});
2 changes: 1 addition & 1 deletion src/buildMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export function buildMiddleware<Definitions extends EndpointDefinitions, Reducer
const invalidateEntities = calculateProvidedBy(
endpointDefinitions[action.meta.arg.endpoint].invalidates,
action.payload,
state.mutations[action.meta.arg.endpoint]?.[action.meta.requestId]?.arg
action.meta.arg.arg
);
const toInvalidate: { [endpoint: string]: Set<string> } = {};
for (const entity of invalidateEntities) {
Expand Down
13 changes: 9 additions & 4 deletions src/endpointDefinitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ export type GetResultDescriptionFn<EntityTypes extends string, ResultType, Query
arg: QueryArg
) => ReadonlyArray<EntityDescription<EntityTypes>>;

export type EntityDescription<EntityType> = { type: EntityType; id?: number | string };
export type FullEntityDescription<EntityType> = { type: EntityType; id?: number | string };
export type EntityDescription<EntityType> = EntityType | FullEntityDescription<EntityType>;
export type ResultDescription<EntityTypes extends string, ResultType, QueryArg> =
| ReadonlyArray<EntityDescription<EntityTypes>>
| GetResultDescriptionFn<EntityTypes, ResultType, QueryArg>;
Expand Down Expand Up @@ -64,16 +65,20 @@ export function calculateProvidedBy<ResultType, QueryArg, D extends ResultDescri
description: D | undefined,
result: ResultType,
queryArg: QueryArg
): readonly EntityDescription<string>[] {
): readonly FullEntityDescription<string>[] {
if (isFunction(description)) {
return description(result, queryArg);
return description(result, queryArg).map(expandEntityDescription);
}
if (Array.isArray(description)) {
return description;
return description.map(expandEntityDescription);
}
return [];
}

function isFunction<T>(t: T): t is Extract<T, Function> {
return typeof t === 'function';
}

function expandEntityDescription(description: EntityDescription<string>): FullEntityDescription<string> {
return typeof description === 'string' ? { type: description } : description;
}

0 comments on commit a2d2f7a

Please sign in to comment.