Skip to content

Commit

Permalink
fix: port type as number, add show empty value after edit connection #7
Browse files Browse the repository at this point in the history
Signed-off-by: seven <[email protected]>
  • Loading branch information
Blankll committed Jan 10, 2024
1 parent 1e639ab commit b79d5c9
Show file tree
Hide file tree
Showing 5 changed files with 96 additions and 89 deletions.
1 change: 1 addition & 0 deletions components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ declare module 'vue' {
NGridItem: typeof import('naive-ui')['NGridItem']
NIcon: typeof import('naive-ui')['NIcon']
NInput: typeof import('naive-ui')['NInput']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NLoadingBarProvider: typeof import('naive-ui')['NLoadingBarProvider']
NMessageProvider: typeof import('naive-ui')['NMessageProvider']
NModal: typeof import('naive-ui')['NModal']
Expand Down
136 changes: 70 additions & 66 deletions src/common/httpClient.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { CustomError } from './customError';
import { Buffer } from 'buffer';
import { lang } from '../lang';

const catchHandler = (err: unknown) => {
if (err instanceof CustomError) {
if (err.status === 401) {
throw new CustomError(err.status, lang.global.t('connection.unAuthorized'));
}
throw new CustomError(err.status, err.details);
}
if (err instanceof Error) {
Expand All @@ -18,81 +22,81 @@ const buildURL = (host: string, port: number, path?: string, queryParameters?: s

return url;
};

export const loadHttpClient = ({
const fetchWrapper = async ({
method,
path,
queryParameters,
payload,
host,
port,
username,
password,
}: {
method: string;
path?: string;
queryParameters?: string;
payload?: unknown;
username?: string;
password?: string;
host: string;
port: number;
}) => {
const authorization =
username && password
? `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
: undefined;

const url = buildURL(host, port, path, queryParameters);
try {
const result = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json', authorization } as unknown as Headers,
body: payload ? JSON.stringify(payload) : undefined,
});
if (result.ok) {
return await result.json();
}
throw new CustomError(result.status, await result.text());
} catch (e) {
throw catchHandler(e);
}
};
export const loadHttpClient = (con: {
host: string;
port: number;
username?: string;
password?: string;
}) => ({
get: async (path?: string, queryParameters?: string) => {
const authorization =
username && password
? `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
: undefined;
const url = buildURL(host, port, path, queryParameters);
try {
const result = await fetch(url, {
method: 'GET',
headers: { 'Content-Type': 'application/json', authorization } as unknown as Headers,
});
const data = await result.json();
if (!result.ok) new CustomError(result.status, data);
get: async (path?: string, queryParameters?: string) =>
fetchWrapper({
...con,
method: 'GET',
path,
queryParameters,
}),
post: async (path: string, queryParameters?: string, payload?: unknown) =>
fetchWrapper({
...con,
method: 'POST',
path,
queryParameters,
payload,
}),
put: async (path: string, queryParameters?: string, payload?: unknown) =>
fetchWrapper({
...con,
method: 'PUT',
path,
queryParameters,
payload,
}),

return data;
} catch (e) {
throw catchHandler(e);
}
},
post: async (path: string, queryParameters?: string, payload?: unknown) => {
const url = buildURL(host, port, path, queryParameters);
try {
const result = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: payload ? JSON.stringify(payload) : undefined,
});
const data = await result.json();
if (!result.ok) new CustomError(result.status, data);
return data;
} catch (e) {
throw catchHandler(e);
}
},
put: async (path: string, queryParameters?: string, payload?: unknown) => {
const url = buildURL(host, port, path, queryParameters);
try {
const result = await fetch(url, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: payload ? JSON.stringify(payload) : undefined,
});
const data = await result.json();
if (!result.ok) new CustomError(result.status, data);
return data;
} catch (e) {
throw catchHandler(e);
}
},

delete: async (path: string, queryParameters?: string, payload?: unknown) => {
const url = buildURL(host, port, path, queryParameters);
try {
const result = await fetch(url, {
method: 'delete',
headers: { 'Content-Type': 'application/json' },
body: payload ? JSON.stringify(payload) : undefined,
});
const data = await result.json();
if (!result.ok) new CustomError(result.status, data);
return data;
} catch (e) {
throw catchHandler(e);
}
},
delete: async (path: string, queryParameters?: string, payload?: unknown) =>
fetchWrapper({
...con,
method: 'DELETE',
path,
queryParameters,
payload,
}),
});
2 changes: 2 additions & 0 deletions src/lang/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const enUS = {
edit: 'Edit',
remove: 'Remove',
},
unAuthorized: 'Authorization failed, ensure your username and password are correct',
},
dialogOps: {
warning: 'Warning',
Expand Down Expand Up @@ -84,6 +85,7 @@ const zhCN = {
edit: '编辑',
remove: '删除',
},
unAuthorized: '认证失败,请输入正确的用户名和密码!',
},
dialogOps: {
warning: '提示',
Expand Down
21 changes: 6 additions & 15 deletions src/store/connectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export type Connection = {
id?: number;
name: string;
host: string;
port: number | string;
port: number;
username?: string;
password?: string;
queryParameters?: string;
Expand Down Expand Up @@ -60,13 +60,10 @@ export const useConnectionStore = defineStore('connectionStore', {
async fetchConnections() {
this.connections = await storeAPI.get('connections', []);
},
async testConnection({ port, ...con }: Connection) {
const client = loadHttpClient({
...con,
port: parseInt(`${port}`, 10),
});
async testConnection(con: Connection) {
const client = loadHttpClient(con);

return await client.get();
return await client.get(undefined, 'format=json');
},
saveConnection(connection: Connection) {
const index = this.connections.findIndex(item => item.id === connection.id);
Expand All @@ -83,10 +80,7 @@ export const useConnectionStore = defineStore('connectionStore', {
},
async establishConnection(connection: Connection) {
await this.testConnection(connection);
const client = loadHttpClient({
...connection,
port: parseInt(`${connection.port}`, 10),
});
const client = loadHttpClient(connection);

const data = await client.get('/_cat/indices', 'format=json');
const indices = data.map((index: { [key: string]: string }) => ({
Expand Down Expand Up @@ -117,10 +111,7 @@ export const useConnectionStore = defineStore('connectionStore', {
qdsl?: string;
}) {
if (!this.established) throw new Error('no connection established');
const client = loadHttpClient({
...this.established,
port: parseInt(`${this.established.port}`, 10),
});
const client = loadHttpClient(this.established);

const reqPath = buildPath(index, path);
const body = qdsl ? JSON.parse(qdsl) : undefined;
Expand Down
25 changes: 17 additions & 8 deletions src/views/connect/components/connect-dialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
:title="modalTitle"
:bordered="false"
class="add-connect-modal-card"
@mask-click="closeModal"
>
<template #header-extra>
<n-icon size="26" @click="closeModal">
Expand Down Expand Up @@ -42,9 +43,10 @@
</n-grid-item>
<n-grid-item span="3">
<n-form-item :label="$t('connection.port')" path="port">
<n-input
<n-input-number
v-model:value="formData.port"
clearable
:show-button="false"
:placeholder="$t('connection.port')"
/>
</n-form-item>
Expand Down Expand Up @@ -125,15 +127,15 @@ const showModal = ref(false);
const modalTitle = ref(lang.t('connection.add'));
const testLoading = ref(false);
const saveLoading = ref(false);
const formData = ref<Connection>({
const defaultFormData = {
name: '',
host: '',
port: '9200',
port: 9200,
username: '',
password: '',
queryParameters: '',
});
};
const formData = ref<Connection>(defaultFormData);
const formRules = reactive({
name: [
{
Expand All @@ -159,15 +161,22 @@ const formRules = reactive({
});
const message = useMessage();
const cleanUp = () => {
formData.value = defaultFormData;
modalTitle.value = lang.t('connection.add');
};
const showMedal = (con: Connection | null) => {
cleanUp();
showModal.value = true;
if (con) {
formData.value = con;
modalTitle.value = lang.t('connection.edit');
}
};
const closeModal = () => {
showModal.value = false;
cleanUp();
};
const validationPassed = watch(formData.value, async () => {
Expand All @@ -182,14 +191,14 @@ const testConnect = async (event: MouseEvent) => {
event.preventDefault();
testLoading.value = !testLoading.value;
try {
await testConnection({ ...formData.value, port: parseInt(formData.value.port as string) });
await testConnection({ ...formData.value });
message.success(lang.t('connection.testSuccess'));
} catch (e) {
const error = e as CustomError;
message.error(`status: ${error.status}, details: ${error.details}`, {
closable: true,
keepAliveOnHover: true,
duration: 36000000,
duration: 10000,
});
} finally {
testLoading.value = !testLoading.value;
Expand All @@ -199,7 +208,7 @@ const testConnect = async (event: MouseEvent) => {
const saveConnect = async (event: MouseEvent) => {
event.preventDefault();
saveLoading.value = !saveLoading.value;
saveConnection({ ...formData.value, port: parseInt(formData.value.port as string) });
saveConnection(formData.value);
saveLoading.value = !saveLoading.value;
showModal.value = false;
};
Expand Down

0 comments on commit b79d5c9

Please sign in to comment.