Environment deletion and better actions menu

This commit is contained in:
Gregory Schier
2023-10-26 16:18:47 -07:00
parent f8584f1537
commit 356eaf1713
7 changed files with 138 additions and 60 deletions

View File

@@ -472,6 +472,16 @@
}, },
"query": "\n INSERT INTO environments (\n id,\n workspace_id,\n name,\n data\n )\n VALUES (?, ?, ?, ?)\n " "query": "\n INSERT INTO environments (\n id,\n workspace_id,\n name,\n data\n )\n VALUES (?, ?, ?, ?)\n "
}, },
"aeb0712785a9964d516dc8939bc54aa8206ad852e608b362d014b67a0f21b0ed": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Right": 1
}
},
"query": "\n DELETE FROM environments\n WHERE id = ?\n "
},
"b19c275180909a39342b13c3cdcf993781636913ae590967f5508c46a56dc961": { "b19c275180909a39342b13c3cdcf993781636913ae590967f5508c46a56dc961": {
"describe": { "describe": {
"columns": [], "columns": [],

View File

@@ -479,6 +479,19 @@ async fn delete_request(
emit_and_return(&window, "deleted_model", req) emit_and_return(&window, "deleted_model", req)
} }
#[tauri::command]
async fn delete_environment(
window: Window<Wry>,
db_instance: State<'_, Mutex<Pool<Sqlite>>>,
environment_id: &str,
) -> Result<models::Environment, String> {
let pool = &*db_instance.lock().await;
let req = models::delete_environment(environment_id, pool)
.await
.expect("Failed to delete environment");
emit_and_return(&window, "deleted_model", req)
}
#[tauri::command] #[tauri::command]
async fn list_requests( async fn list_requests(
workspace_id: &str, workspace_id: &str,
@@ -600,10 +613,10 @@ async fn new_window(window: Window<Wry>, url: &str) -> Result<(), String> {
async fn delete_workspace( async fn delete_workspace(
window: Window<Wry>, window: Window<Wry>,
db_instance: State<'_, Mutex<Pool<Sqlite>>>, db_instance: State<'_, Mutex<Pool<Sqlite>>>,
id: &str, workspace_id: &str,
) -> Result<models::Workspace, String> { ) -> Result<models::Workspace, String> {
let pool = &*db_instance.lock().await; let pool = &*db_instance.lock().await;
let workspace = models::delete_workspace(id, pool) let workspace = models::delete_workspace(workspace_id, pool)
.await .await
.expect("Failed to delete workspace"); .expect("Failed to delete workspace");
emit_and_return(&window, "deleted_model", workspace) emit_and_return(&window, "deleted_model", workspace)
@@ -643,6 +656,7 @@ fn main() {
create_request, create_request,
create_workspace, create_workspace,
delete_all_responses, delete_all_responses,
delete_environment,
delete_request, delete_request,
delete_response, delete_response,
delete_workspace, delete_workspace,

View File

@@ -252,13 +252,27 @@ pub async fn create_environment(
get_environment(&id, pool).await get_environment(&id, pool).await
} }
pub async fn delete_environment(id: &str, pool: &Pool<Sqlite>) -> Result<Environment, sqlx::Error> {
let env = get_environment(id, pool).await?;
let _ = sqlx::query!(
r#"
DELETE FROM environments
WHERE id = ?
"#,
id,
)
.execute(pool)
.await;
Ok(env)
}
pub async fn update_environment( pub async fn update_environment(
id: &str, id: &str,
name: &str, name: &str,
data: HashMap<String, JsonValue>, data: HashMap<String, JsonValue>,
pool: &Pool<Sqlite>, pool: &Pool<Sqlite>,
) -> Result<Environment, sqlx::Error> { ) -> Result<Environment, sqlx::Error> {
println!("DATA: {}", data.clone().len());
let json_data = Json(data); let json_data = Json(data);
sqlx::query!( sqlx::query!(
r#" r#"
@@ -457,6 +471,10 @@ pub async fn get_request(id: &str, pool: &Pool<Sqlite>) -> Result<HttpRequest, s
pub async fn delete_request(id: &str, pool: &Pool<Sqlite>) -> Result<HttpRequest, sqlx::Error> { pub async fn delete_request(id: &str, pool: &Pool<Sqlite>) -> Result<HttpRequest, sqlx::Error> {
let req = get_request(id, pool).await?; let req = get_request(id, pool).await?;
// DB deletes will cascade but this will delete the files
delete_all_responses(id, pool).await?;
let _ = sqlx::query!( let _ = sqlx::query!(
r#" r#"
DELETE FROM http_requests DELETE FROM http_requests
@@ -467,8 +485,6 @@ pub async fn delete_request(id: &str, pool: &Pool<Sqlite>) -> Result<HttpRequest
.execute(pool) .execute(pool)
.await; .await;
delete_all_responses(id, pool).await?;
Ok(req) Ok(req)
} }

View File

@@ -13,6 +13,7 @@ import { usePrompt } from '../hooks/usePrompt';
import { useDialog } from './DialogContext'; import { useDialog } from './DialogContext';
import { EnvironmentEditDialog } from './EnvironmentEditDialog'; import { EnvironmentEditDialog } from './EnvironmentEditDialog';
import { useAppRoutes } from '../hooks/useAppRoutes'; import { useAppRoutes } from '../hooks/useAppRoutes';
import { useDeleteEnvironment } from '../hooks/useDeleteEnvironment';
type Props = { type Props = {
className?: string; className?: string;
@@ -24,13 +25,14 @@ export const EnvironmentActionsDropdown = memo(function EnvironmentActionsDropdo
const environments = useEnvironments(); const environments = useEnvironments();
const activeEnvironment = useActiveEnvironment(); const activeEnvironment = useActiveEnvironment();
const updateEnvironment = useUpdateEnvironment(activeEnvironment?.id ?? null); const updateEnvironment = useUpdateEnvironment(activeEnvironment?.id ?? null);
const deleteEnvironment = useDeleteEnvironment(activeEnvironment);
const createEnvironment = useCreateEnvironment(); const createEnvironment = useCreateEnvironment();
const prompt = usePrompt(); const prompt = usePrompt();
const dialog = useDialog(); const dialog = useDialog();
const routes = useAppRoutes(); const routes = useAppRoutes();
const items: DropdownItem[] = useMemo(() => { const items: DropdownItem[] = useMemo(() => {
const environmentItems = environments.map( const environmentItems: DropdownItem[] = environments.map(
(e) => ({ (e) => ({
key: e.id, key: e.id,
label: e.name, label: e.name,
@@ -41,57 +43,58 @@ export const EnvironmentActionsDropdown = memo(function EnvironmentActionsDropdo
}), }),
[activeEnvironment?.id], [activeEnvironment?.id],
); );
const activeEnvironmentItems: DropdownItem[] =
environments.length <= 1
? []
: [
...environmentItems,
{
type: 'separator',
label: activeEnvironment?.name,
},
];
return [ return [
...activeEnvironmentItems, ...environmentItems,
{ ...((environmentItems.length > 0
key: 'edit', ? [{ type: 'separator', label: activeEnvironment?.name }]
label: 'Edit', : []) as DropdownItem[]),
leftSlot: <Icon icon="sun" />, ...((activeEnvironment != null
onSelect: async () => { ? [
dialog.show({ {
title: 'Environments', key: 'rename',
render: () => <EnvironmentEditDialog />, label: 'Rename',
}); leftSlot: <Icon icon="pencil" />,
}, onSelect: async () => {
}, const name = await prompt({
{ title: 'Rename Environment',
key: 'rename', description: (
label: 'Rename', <>
leftSlot: <Icon icon="pencil" />, Enter a new name for <InlineCode>{activeEnvironment?.name}</InlineCode>
onSelect: async () => { </>
const name = await prompt({ ),
title: 'Rename Environment', name: 'name',
description: ( label: 'Name',
<> defaultValue: activeEnvironment?.name,
Enter a new name for <InlineCode>{activeEnvironment?.name}</InlineCode> });
</> updateEnvironment.mutate({ name });
), },
name: 'name', },
label: 'Name', {
defaultValue: activeEnvironment?.name, key: 'delete',
}); label: 'Delete',
updateEnvironment.mutate({ name }); leftSlot: <Icon icon="trash" />,
}, onSelect: deleteEnvironment.mutate,
}, variant: 'danger',
// { },
// key: 'delete', { type: 'separator' },
// label: 'Delete', ]
// leftSlot: <Icon icon="trash" />, : []) as DropdownItem[]),
// onSelect: deleteEnv.mutate, ...((environments.length > 0
// variant: 'danger', ? [
// }, {
{ type: 'separator' }, key: 'edit',
label: 'Manage Environments',
leftSlot: <Icon icon="gear" />,
onSelect: async () => {
dialog.show({
title: 'Environments',
render: () => <EnvironmentEditDialog />,
});
},
},
]
: []) as DropdownItem[]),
{ {
key: 'create-environment', key: 'create-environment',
label: 'Create Environment', label: 'Create Environment',
@@ -110,12 +113,13 @@ export const EnvironmentActionsDropdown = memo(function EnvironmentActionsDropdo
]; ];
}, [ }, [
// deleteEnvironment.mutate, // deleteEnvironment.mutate,
activeEnvironment?.name, activeEnvironment,
createEnvironment, createEnvironment,
dialog, dialog,
environments, environments,
prompt, prompt,
updateEnvironment, updateEnvironment,
deleteEnvironment,
routes, routes,
]); ]);

View File

@@ -3,11 +3,9 @@ import { invoke } from '@tauri-apps/api';
import type { Environment } from '../lib/models'; import type { Environment } from '../lib/models';
import { environmentsQueryKey } from './useEnvironments'; import { environmentsQueryKey } from './useEnvironments';
import { useActiveWorkspaceId } from './useActiveWorkspaceId'; import { useActiveWorkspaceId } from './useActiveWorkspaceId';
import { useActiveEnvironmentId } from './useActiveEnvironmentId';
import { useAppRoutes } from './useAppRoutes'; import { useAppRoutes } from './useAppRoutes';
export function useCreateEnvironment() { export function useCreateEnvironment() {
const environmentId = useActiveEnvironmentId();
const workspaceId = useActiveWorkspaceId(); const workspaceId = useActiveWorkspaceId();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const routes = useAppRoutes(); const routes = useAppRoutes();
@@ -18,7 +16,7 @@ export function useCreateEnvironment() {
}, },
onSuccess: async (environment) => { onSuccess: async (environment) => {
if (workspaceId == null) return; if (workspaceId == null) return;
routes.navigate('workspace', { workspaceId, environmentId }); routes.setEnvironment(environment);
queryClient.setQueryData<Environment[]>( queryClient.setQueryData<Environment[]>(
environmentsQueryKey({ workspaceId }), environmentsQueryKey({ workspaceId }),
(environments) => [...(environments ?? []), environment], (environments) => [...(environments ?? []), environment],

View File

@@ -0,0 +1,36 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { invoke } from '@tauri-apps/api';
import { InlineCode } from '../components/core/InlineCode';
import type { Environment, Workspace } from '../lib/models';
import { useConfirm } from './useConfirm';
import { environmentsQueryKey } from './useEnvironments';
export function useDeleteEnvironment(environment: Environment | null) {
const queryClient = useQueryClient();
const confirm = useConfirm();
return useMutation<Environment | null, string>({
mutationFn: async () => {
const confirmed = await confirm({
title: 'Delete Environment',
variant: 'delete',
description: (
<>
Permanently delete <InlineCode>{environment?.name}</InlineCode>?
</>
),
});
if (!confirmed) return null;
return invoke('delete_environment', { environmentId: environment?.id });
},
onSuccess: async (environment) => {
if (environment === null) return;
const { id: environmentId, workspaceId } = environment;
queryClient.setQueryData<Workspace[]>(
environmentsQueryKey({ workspaceId }),
(environments) => environments?.filter((e) => e.id !== environmentId),
);
},
});
}

View File

@@ -26,7 +26,7 @@ export function useDeleteWorkspace(workspace: Workspace | null) {
), ),
}); });
if (!confirmed) return null; if (!confirmed) return null;
return invoke('delete_workspace', { id: workspace?.id }); return invoke('delete_workspace', { workspaceId: workspace?.id });
}, },
onSuccess: async (workspace) => { onSuccess: async (workspace) => {
if (workspace === null) return; if (workspace === null) return;