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

close #466 | create mutation shorthand #467

Closed
wants to merge 2 commits into from
Closed
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
15 changes: 15 additions & 0 deletions packages/core/src/mutation/__tests__/create_mutation.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,21 @@ import { ExecutionMeta } from '../../remote_operation/type';
import { createMutation } from '../create_mutation';

describe('createMutation', () => {
test("infer params and data from handler shorthand", () => {
const mutation = createMutation(async (params: number) => params.toString());

expectTypeOf(mutation.start).toBeCallableWith(1);
// @ts-expect-error invalid params type
expectTypeOf(mutation.start).toBeCallableWith({});

expectTypeOf(mutation.finished.success).toEqualTypeOf<
Event<{ params: number; result: string; meta: ExecutionMeta }>
>();
expectTypeOf(mutation.finished.success).not.toEqualTypeOf<
Event<{ params: string; result: string; meta: ExecutionMeta }>
>();
});

test('infer params and data from handler', () => {
const mutation = createMutation({
handler: async (params: number) => params.toString(),
Expand Down
13 changes: 9 additions & 4 deletions packages/core/src/mutation/create_mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import { Mutation } from './type';
import { resolveExecuteEffect } from '../remote_operation/resolve_execute_effect';
import { unknownContract } from '../contract/unknown_contract';

// Overload: Only handler without config
export function createMutation<Params, Data>(handler: (params: Params) => Promise<Data>): Mutation<Params, Data, unknown>;

// Overload: Only handler
export function createMutation<Params, Data>(
config: {
Expand Down Expand Up @@ -37,14 +40,16 @@ export function createMutation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: any
): Mutation<any, any, any> {
const params = typeof config === 'function' ? { handler: config } : config;

const mutation = createHeadlessMutation({
name: config.name,
enabled: config.enabled,
contract: config.contract ?? unknownContract,
name: params.name,
enabled: params.enabled,
contract: params.contract ?? unknownContract,
mapData: ({ result }) => result,
});

mutation.__.executeFx.use(resolveExecuteEffect(config));
mutation.__.executeFx.use(resolveExecuteEffect(params));

return mutation;
}
Loading