-
Notifications
You must be signed in to change notification settings - Fork 8k
/
use_delete_slo.ts
89 lines (79 loc) · 2.79 KB
/
use_delete_slo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { i18n } from '@kbn/i18n';
import { FindSLOResponse } from '@kbn/slo-schema';
import { useKibana } from '../../utils/kibana_react';
import { sloKeys } from './query_key_factory';
export function useDeleteSlo() {
const {
http,
notifications: { toasts },
} = useKibana().services;
const queryClient = useQueryClient();
const deleteSlo = useMutation<
string,
string,
{ id: string; name: string },
{ previousSloList: FindSLOResponse | undefined }
>(
['deleteSlo'],
({ id }) => {
try {
return http.delete<string>(`/api/observability/slos/${id}`);
} catch (error) {
return Promise.reject(`Something went wrong: ${String(error)}`);
}
},
{
onMutate: async (slo) => {
// Cancel any outgoing refetches (so they don't overwrite our optimistic update)
await queryClient.cancelQueries(sloKeys.lists());
const latestQueriesData = (
queryClient.getQueriesData<FindSLOResponse>(sloKeys.lists()) || []
).at(0);
const [queryKey, data] = latestQueriesData || [];
const optimisticUpdate = {
...data,
results: data?.results?.filter((result) => result.id !== slo.id) ?? [],
total: data?.total ? data.total - 1 : 0,
};
// Optimistically update to the new value
queryClient.setQueryData(queryKey ?? sloKeys.lists(), optimisticUpdate);
toasts.addSuccess(
i18n.translate('xpack.observability.slo.slo.delete.successNotification', {
defaultMessage: 'Deleted {name}',
values: { name: slo.name },
})
);
// Return a context object with the snapshotted value
return { previousSloList: data };
},
// If the mutation fails, use the context returned from onMutate to roll back
onError: (_err, slo, context) => {
if (context?.previousSloList) {
queryClient.setQueryData(sloKeys.lists(), context.previousSloList);
}
toasts.addDanger(
i18n.translate('xpack.observability.slo.slo.delete.errorNotification', {
defaultMessage: 'Failed to delete {name}',
values: { name: slo.name },
})
);
},
onSuccess: () => {
if (
// @ts-ignore
queryClient.getQueryCache().find(sloKeys.lists())?.options.refetchInterval === undefined
) {
queryClient.invalidateQueries(sloKeys.lists());
}
},
}
);
return deleteSlo;
}