Skip to content
Draft
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
1 change: 1 addition & 0 deletions packages/base-data-service/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `ExponentialBackoff`
- `handleAll`
- `handleWhen`
- Add `executeMutation` to `BaseDataService` to allow for making state-mutating requests ([#9324](https://github.com/MetaMask/core/pull/9324))

### Changed

Expand Down
51 changes: 51 additions & 0 deletions packages/base-data-service/src/BaseDataService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { cleanAll } from 'nock';

import { ExampleDataService, serviceName } from '../tests/ExampleDataService';
import {
mockAddFollowerRequest,
mockAssets,
mockTransactionsPage1,
mockTransactionsPage2,
Expand Down Expand Up @@ -161,6 +162,44 @@ describe('BaseDataService', () => {
);
});

it('handles mutations', async () => {
mockAddFollowerRequest();

const messenger = new Messenger({ namespace: serviceName });
const service = new ExampleDataService(messenger);

expect(await service.addFollower('1')).toStrictEqual({
followed: [
{
profileId: '550e8400-e29b-41d4-a716-446655440000',
address: '0x1234567890abcdef1234567890abcdef12345678',
name: 'TraderAlice',
imageUrl: 'https://example.com/avatar.png',
},
],
});
});

it('never retries mutations even if they fail', async () => {
mockAddFollowerRequest({ status: 504 });
mockAddFollowerRequest();

const messenger = new Messenger({ namespace: serviceName });
const service = new ExampleDataService(messenger);

await expect(service.addFollower('1')).rejects.toThrow('Mutation failed');
expect(await service.addFollower('1')).toStrictEqual({
followed: [
{
profileId: '550e8400-e29b-41d4-a716-446655440000',
address: '0x1234567890abcdef1234567890abcdef12345678',
name: 'TraderAlice',
imageUrl: 'https://example.com/avatar.png',
},
],
});
});

it('emits `:cacheUpdated` events when cache entry is removed', async () => {
const messenger = new Messenger({ namespace: serviceName });
const service = new ExampleDataService(messenger);
Expand All @@ -186,6 +225,18 @@ describe('BaseDataService', () => {
);
});

it('does not emit `:cacheUpdated` when a mutation is executed', async () => {
mockAddFollowerRequest();

const messenger = new Messenger({ namespace: serviceName });
const service = new ExampleDataService(messenger);
const publishSpy = jest.spyOn(messenger, 'publish');

await service.addFollower('1');

expect(publishSpy).not.toHaveBeenCalled();
});

it('does not emit events after being destroyed', async () => {
const messenger = new Messenger({ namespace: serviceName });
const service = new ExampleDataService(messenger);
Expand Down
34 changes: 34 additions & 0 deletions packages/base-data-service/src/BaseDataService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
InfiniteData,
InvalidateOptions,
InvalidateQueryFilters,
MutationOptions,
OmitKeyof,
QueryClient,
QueryClientConfig,
Expand Down Expand Up @@ -251,6 +252,39 @@ export class BaseDataService<
return result.pages[pageIndex];
}

/**
* Execute a mutation (a request that is expected to change the state of a server).
* Unlike `fetchQuery`, the request will not be cached.
*
* @param options - The options defining the mutation. Keep in mind that `mutationKey` and `mutationFn` are required when using data services.
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
* @returns The mutation results.
*/
protected async executeMutation<

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mutation cache is separate from the query cache, should we sync it with the UI as well?

E.g. https://github.com/MetaMask/core/blob/main/packages/base-data-service/src/BaseDataService.ts#L145-L152

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ooh good point. Okay I'll make this change.

TData extends Json,
TError = unknown,
TVariables = void,
TContext = unknown,
>(
options: WithRequired<
OmitKeyof<
MutationOptions<TData, TError, TVariables, TContext>,
'retry' | 'retryDelay'
>,
'mutationKey' | 'mutationFn'
>,
): Promise<TData> {
const mutationCache = this.#queryClient.getMutationCache();

@mcmire mcmire Jun 30, 2026

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QueryClient doesn't have a executeMutation method itself. I looked inside of the class, however, and saw that there was a getMutationCache method and followed where that led. This is not how useMutation works, which uses MutationObserver, but I don't know if that really matters. I figured it made more sense to mimic how fetchQuery works. But I'm not very familiar with TanStack Query, so if this is not the way we should be doing things, I'm happy to change this.

const mutation = mutationCache.build(this.#queryClient, {
...options,
mutationFn: (context) =>
this.#policy.circuitBreakerPolicy.execute(() =>
options.mutationFn(context),
),
});
return await mutation.execute();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mutation variables never forwarded

Medium Severity

executeMutation always calls mutation.execute() with no arguments, so TanStack mutationFn never receives TVariables. Callers that pass inputs via variables (the usual mutation pattern) instead of closing over them will run with missing or undefined data.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 603d673. Configure here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are using an older version of TanStack Query where Mutation.execute doesn't take any arguments. Variables are passed to the Mutation constructor.

}

/**
* Invalidate queries serviced by this data service.
*
Expand Down
34 changes: 34 additions & 0 deletions packages/base-data-service/tests/ExampleDataService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ export type GetActivityResponse = {
};
};

export type AddFollowerResponse = {
followed: {
profileId: string;
address: string;
name: string;
imageUrl?: string | null;
}[];
};

export type PageParam =
| {
before: string;
Expand All @@ -60,6 +69,8 @@ export class ExampleDataService extends BaseDataService<

readonly #tokensBaseUrl = 'https://tokens.api.cx.metamask.io';

readonly #socialBaseUrl = 'https://social.api.cx.metamask.io';

constructor(messenger: ExampleMessenger) {
super({
name: serviceName,
Expand Down Expand Up @@ -139,6 +150,29 @@ export class ExampleDataService extends BaseDataService<
);
}

async addFollower(followerId: string): Promise<AddFollowerResponse> {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adapted from SocialService:

async follow(options: FollowOptions): Promise<FollowResponse> {

return this.executeMutation<AddFollowerResponse>({
mutationKey: [`${this.name}:addFollower`, followerId],
mutationFn: async () => {
const url = new URL(`${this.#socialBaseUrl}/api/v1/users/me/follows`);

const response = await fetch(url, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ followerId }),
});

if (!response.ok) {
throw new Error(
`Mutation failed with status code: ${response.status}.`,
);
}

return response.json();
},
});
}

destroy(): void {
super.destroy();
}
Expand Down
20 changes: 20 additions & 0 deletions packages/base-data-service/tests/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,26 @@ type MockReply = {
body?: nock.Body;
};

export function mockAddFollowerRequest(mockReply?: MockReply): nock.Scope {
const reply = mockReply ?? {
status: 200,
body: {
followed: [
{
profileId: '550e8400-e29b-41d4-a716-446655440000',
address: '0x1234567890abcdef1234567890abcdef12345678',
name: 'TraderAlice',
imageUrl: 'https://example.com/avatar.png',
},
],
Comment thread
cursor[bot] marked this conversation as resolved.
},
};

return nock('https://social.api.cx.metamask.io:443')
.put('/api/v1/users/me/follows', { followerId: '1' })
.reply(reply.status, reply.body);
}

export function mockAssets(mockReply?: MockReply): nock.Scope {
const reply = mockReply ?? {
status: 200,
Expand Down