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

Cleanup connections #29

Merged
merged 2 commits into from
Mar 5, 2024
Merged
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: 0 additions & 1 deletion locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ export default {
'connection.form.port.label': 'Port',
'connection.form.user.label': 'User',
'connection.form.password.label': 'Password',
'connection.form.saveConnection': 'Save connection',
'connection.form.action.connect': 'Connect',
'connection.form.action.saveAndConnect': 'Save and connect',
'table.rows.loadMore': 'Load more…',
Expand Down
1 change: 0 additions & 1 deletion locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ const fr: Translation = {
'connection.form.port.label': 'Port',
'connection.form.user.label': 'Utilisateur',
'connection.form.password.label': 'Mot de passe',
'connection.form.saveConnection': 'Enregistrer la connexion',
'connection.form.action.connect': 'Connecter',
'connection.form.action.saveAndConnect': 'Enregistrer et connecter',
'table.rows.loadMore': 'Charger plus…',
Expand Down
25 changes: 24 additions & 1 deletion src/configuration/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
updateConnectionState,
} from '.';

const { getBaseConfig } = testables;
const { getBaseConfig, resetConfiguration } = testables;

vi.mock('env-paths', () => ({
default: () => ({ config: 'config' }),
Expand All @@ -37,6 +37,8 @@ function resetAllMocks(): void {
mockExistsSync.mockReset();
mockReadFileSync.mockReset();
mockWriteFile.mockReset();

resetConfiguration();
}

vi.mock('electron', () => ({
Expand Down Expand Up @@ -81,13 +83,16 @@ describe('read configuration from file', () => {
mockExistsSync.mockReturnValue(false);

expect(getConfiguration()).toStrictEqual(getBaseConfig());
expect(mockReadFileSync).not.toHaveBeenCalled();
});

test('existing file but empty', () => {
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue('');

expect(getConfiguration()).toStrictEqual(getBaseConfig());

expect(mockReadFileSync).toHaveBeenCalledOnce();
});

test('existing file without connexion key', () => {
Expand All @@ -97,6 +102,8 @@ describe('read configuration from file', () => {
expect(getConfiguration()).toStrictEqual({
connections: {},
});

expect(mockReadFileSync).toHaveBeenCalledOnce();
});

test('existing file without connexion', () => {
Expand All @@ -107,6 +114,8 @@ describe('read configuration from file', () => {
version: 1,
connections: {},
});

expect(mockReadFileSync).toHaveBeenCalledOnce();
});

test('existing file with connexions', () => {
Expand Down Expand Up @@ -237,6 +246,8 @@ describe('add connection to config', () => {
'utf-8',
expect.any(Function)
);

expect(mockReadFileSync).toHaveBeenCalledOnce();
});
});

Expand Down Expand Up @@ -313,6 +324,8 @@ describe('set theme', () => {
'utf-8',
expect.any(Function)
);

expect(mockReadFileSync).toHaveBeenCalledOnce();
});
});

Expand All @@ -331,6 +344,8 @@ describe('set connection appState', async () => {
await updateConnectionState('inexistant', 'isActive', true);

expect(mockWriteFile).not.toHaveBeenCalled();

expect(mockReadFileSync).toHaveBeenCalledOnce();
});

test('existing file, set active', async () => {
Expand Down Expand Up @@ -372,6 +387,8 @@ describe('set connection appState', async () => {
'utf-8',
expect.any(Function)
);

expect(mockReadFileSync).toHaveBeenCalledOnce();
});

test('existing file, set activeDatabase', async () => {
Expand Down Expand Up @@ -437,6 +454,8 @@ describe('set connection appState', async () => {
'utf-8',
expect.any(Function)
);

expect(mockReadFileSync).toHaveBeenCalledOnce();
});
});

Expand Down Expand Up @@ -483,6 +502,8 @@ describe('edit', () => {
'utf-8',
expect.any(Function)
);

expect(mockReadFileSync).toHaveBeenCalledOnce();
});

test('rename connexion', () => {
Expand Down Expand Up @@ -528,5 +549,7 @@ describe('edit', () => {
'utf-8',
expect.any(Function)
);

expect(mockReadFileSync).toHaveBeenCalledOnce();
});
});
17 changes: 16 additions & 1 deletion src/configuration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,17 @@ function decryptConnection(
};
}

let configuration: Configuration | null = null;

export function getConfiguration(): Configuration {
if (!configuration) {
configuration = loadConfiguration();
}

return configuration;
}

function loadConfiguration(): Configuration {
if (!existsSync(dataFilePath)) {
return getBaseConfig();
}
Expand Down Expand Up @@ -183,4 +193,9 @@ export function bindIpcMain(ipcMain: Electron.IpcMain): void {
}
}

export const testables = { getBaseConfig };
export const testables = {
getBaseConfig,
resetConfiguration: () => {
configuration = null;
},
};
3 changes: 0 additions & 3 deletions src/contexts/ConnectionContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,13 @@ interface ConnexionContextProps {
currentConnectionName: string | null;
connectionNameList: string[];
connectTo: ConnectToFunc;
setCurrentConnectionName: (connectionName: string) => void;
}

export const ConnectionContext = createContext<ConnexionContextProps>({
currentConnectionName: null,
connectionNameList: [],
// eslint-disable-next-line @typescript-eslint/no-empty-function
connectTo: () => Promise.resolve(),
// eslint-disable-next-line @typescript-eslint/no-empty-function
setCurrentConnectionName: () => {},
});
ConnectionContext.displayName = 'ConnectionContext';

Expand Down
2 changes: 0 additions & 2 deletions src/renderer/component/Cell.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ const meta: Meta<typeof Cell> = {
value={{
currentConnectionName: 'test',
connectionNameList: ['test'],
// eslint-disable-next-line @typescript-eslint/no-empty-function
setCurrentConnectionName: () => {},
connectTo: async (connection) => {
action('connectTo')(connection);
},
Expand Down
2 changes: 0 additions & 2 deletions src/renderer/component/Connection/ConnectionForm.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ const meta: Meta<typeof ConnectionForm> = {
value={{
currentConnectionName: 'test',
connectionNameList: ['test'],
// eslint-disable-next-line @typescript-eslint/no-empty-function
setCurrentConnectionName: () => {},
connectTo: async (connection) => {
action('connectTo')(connection);
},
Expand Down
61 changes: 15 additions & 46 deletions src/renderer/component/Connection/ConnectionForm.tsx
Original file line number Diff line number Diff line change
@@ -1,125 +1,94 @@
import { useState } from 'react';
import { Button, Checkbox, Form, Input } from 'antd';
import { Button, Form, Input } from 'antd';
import type { TFunction } from 'i18next';
import { useNavigate } from 'react-router';
import { useConfiguration } from '../../../contexts/ConfigurationContext';
import { useConnectionContext } from '../../../contexts/ConnectionContext';
import { useTranslation } from '../../../i18n';
import type { ConnectionObject } from '../../../sql/types';

type ConnectionFormType = ConnectionObject & {
save?: boolean;
};

type Props = { connection?: ConnectionObject };

function getSubmitButtonLabel(
t: TFunction,
connection: ConnectionObject | undefined,
isSaveChecked: boolean | undefined
connection: ConnectionObject | undefined
): string {
if (connection) {
return t('save');
}

return isSaveChecked
? t('connection.form.action.saveAndConnect')
: t('connection.form.action.connect');
return t('connection.form.action.saveAndConnect');
}

function ConnectionForm({ connection }: Props) {
const initialValues: ConnectionFormType = connection ?? {
const initialValues: ConnectionObject = connection ?? {
name: '',
host: 'localhost',
port: 3306,
user: 'root',
password: '',
save: true,
};

const { t } = useTranslation();
const { connectTo } = useConnectionContext();
const { addConnectionToConfig, editConnection } = useConfiguration();
const navigate = useNavigate();
const [form] = Form.useForm();
const [submitButtonLabel, setSubmitButtonLabel] = useState<string>(
getSubmitButtonLabel(t, connection, initialValues.save)
);

const handleSubmit = (formData: ConnectionFormType): void => {
const { save, ...connectionFormData } = formData;

const handleSubmit = (formData: ConnectionObject): void => {
if (connection) {
// edit connection
editConnection(connection.name, connectionFormData);
editConnection(connection.name, formData);

navigate('/connect');
return;
}

if (save) {
addConnectionToConfig(connectionFormData);
}

connectTo(connectionFormData);
addConnectionToConfig(formData);
connectTo(formData);
};

return (
<Form initialValues={initialValues} onFinish={handleSubmit} form={form}>
<Form.Item<ConnectionFormType>
<Form.Item<ConnectionObject>
name="name"
label={t('connection.form.name.label')}
rules={[{ required: true }]}
>
<Input />
</Form.Item>

<Form.Item<ConnectionFormType>
<Form.Item<ConnectionObject>
name="host"
label={t('connection.form.host.label')}
rules={[{ required: true }]}
>
<Input />
</Form.Item>

<Form.Item<ConnectionFormType>
<Form.Item<ConnectionObject>
name="port"
label={t('connection.form.port.label')}
rules={[{ required: true }]}
>
<Input />
</Form.Item>

<Form.Item<ConnectionFormType>
<Form.Item<ConnectionObject>
name="user"
label={t('connection.form.user.label')}
rules={[{ required: true }]}
>
<Input />
</Form.Item>

<Form.Item<ConnectionFormType>
<Form.Item<ConnectionObject>
name="password"
label={t('connection.form.password.label')}
>
<Input type="password" />
</Form.Item>

{!connection && (
<Form.Item<ConnectionFormType> name="save" valuePropName="checked">
<Checkbox
onChange={() => {
setSubmitButtonLabel(
getSubmitButtonLabel(t, connection, form.getFieldValue('save'))
);
}}
>
{t('connection.form.saveConnection')}
</Checkbox>
</Form.Item>
)}

<Form.Item<ConnectionFormType> shouldUpdate>
<Form.Item<ConnectionObject> shouldUpdate>
<Button
onClick={() => {
navigate(-1);
Expand All @@ -128,7 +97,7 @@ function ConnectionForm({ connection }: Props) {
{t('cancel')}
</Button>
<Button type="primary" htmlType="submit">
{submitButtonLabel}
{getSubmitButtonLabel(t, connection)}
</Button>
</Form.Item>
</Form>
Expand Down
8 changes: 0 additions & 8 deletions src/renderer/component/Connection/ConnectionStack.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,6 @@ function ConnectionStack({ children }: Props) {
[navigate, setConnectionNameList]
);

const handleSetConnection = useCallback(
(connectionName: string) => {
navigate(`/connections/${connectionName}`);
},
[navigate]
);

const handleSetDatabase = useCallback(
(database: string) => {
invariant(currentConnectionName, 'Connection name is required');
Expand All @@ -59,7 +52,6 @@ function ConnectionStack({ children }: Props) {
connectionNameList,
currentConnectionName: currentConnectionName ?? null,
connectTo: handleConnectTo,
setCurrentConnectionName: handleSetConnection,
}}
>
<DatabaseContext.Provider
Expand Down
5 changes: 0 additions & 5 deletions src/renderer/component/Connection/Nav.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { action } from '@storybook/addon-actions';
import type { Meta, StoryObj } from '@storybook/react';
import { Layout } from 'antd';
import { styled } from 'styled-components';
Expand All @@ -21,10 +20,6 @@ const meta: Meta<typeof Nav> = {
value={{
currentConnectionName: 'production',
connectionNameList: ['test', 'production', 'staging', 'development'],
// eslint-disable-next-line @typescript-eslint/no-empty-function
setCurrentConnectionName: (connection) => {
action('setCurrentConnectionName')(connection);
},
connectTo: async () => {},
}}
>
Expand Down
2 changes: 0 additions & 2 deletions src/renderer/component/TableList.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ const meta: Meta<typeof TableList> = {
value={{
currentConnectionName: 'test',
connectionNameList: ['test'],
// eslint-disable-next-line @typescript-eslint/no-empty-function
setCurrentConnectionName: () => {},
connectTo: async (connection) => {
action('connectTo')(connection);
},
Expand Down
Loading