Skip to content

Commit

Permalink
feat: select index work #10
Browse files Browse the repository at this point in the history
Signed-off-by: seven <[email protected]>
  • Loading branch information
Blankll committed Dec 29, 2023
1 parent 71b8d91 commit b122704
Show file tree
Hide file tree
Showing 6 changed files with 135 additions and 59 deletions.
3 changes: 2 additions & 1 deletion auto-import.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,5 +70,6 @@ declare global {
// for type re-export
declare global {
// @ts-ignore
export type { Component, ComponentPublicInstance, ComputedRef, InjectionKey, PropType, Ref, VNode } from 'vue'
export type { Component, ComponentPublicInstance, ComputedRef, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, VNode, WritableComputedRef } from 'vue'
import('vue')
}
52 changes: 52 additions & 0 deletions src/common/httpClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { CustomError } from './customError';

const catchHandler = (err: unknown) => {
if (err instanceof CustomError) {
throw new CustomError(err.status, err.details);
}
if (err instanceof Error) {
throw new CustomError(500, err.message);
}
throw new CustomError(500, `unknown error, trace: ${JSON.stringify(err)}`);
};

const buildURL = (host: string, port: number, path?: string, queryParameters?: string) => {
let url = `${host}:${port}`;
url += path ?? '';
url += queryParameters ? `?${queryParameters}` : '';

return url;
};

export const loadHttpClient = (host: string, port: number) => ({
get: async (path?: string, queryParameters?: string) => {
const url = buildURL(host, port, path, queryParameters);
try {
const result = await fetch(url, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
});
const data = await result.json();
if (!result.ok) new CustomError(result.status, data);

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);
}
},
});
102 changes: 57 additions & 45 deletions src/store/connectionStore.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { defineStore } from 'pinia';
import { CustomError, pureObject } from '../common';
import { pureObject } from '../common';
import { loadHttpClient } from '../common/httpClient';

export type Connection = {
id?: number;
Expand All @@ -10,34 +11,51 @@ export type Connection = {
password?: string;
queryParameters?: string;
};
export type ConnectionIndex = {
health: string;
status: string;
index: string;
uuid: string;
docs: {
count: number;
deleted: number;
};
store: {
size: string;
};
pri: {
store: {
size: string;
};
};
};

const { storeAPI } = window;

export const useConnectionStore = defineStore('connectionStore', {
state(): { connections: Connection[]; established: Connection | null } {
state(): {
connections: Connection[];
established:
| (Connection & { indices: Array<ConnectionIndex>; activeIndex: ConnectionIndex })
| null;
} {
return {
connections: [],
established: null,
};
},
getters: {},
getters: {
establishedIndexNames(state) {
return state.established?.indices.map(({ index }) => index) ?? [];
},
},
actions: {
async fetchConnections() {
this.connections = await storeAPI.get('connections', []);
},
async testConnection({ host, port }: Connection) {
try {
const result = await fetch(`${host}:${port}`, {
method: 'GET',
});
if (!result.ok) new CustomError(result.status, await result.json());
} catch (e) {
if (e instanceof CustomError) {
throw new CustomError(e.status, e.details);
}
if (e instanceof Error) {
throw new CustomError(500, e.message);
}
throw new CustomError(500, `unknown error, trace: ${JSON.stringify(e)}`);
}
const client = loadHttpClient(host, parseInt(`${port}`, 10));
return await client.get();
},
saveConnection(connection: Connection) {
const index = this.connections.findIndex(item => item.id === connection.id);
Expand All @@ -52,37 +70,31 @@ export const useConnectionStore = defineStore('connectionStore', {
this.connections = this.connections.filter(item => item.id !== connection.id);
storeAPI.set('connections', pureObject(this.connections));
},
establishConnection(connection: Connection) {
this.established = connection;
async establishConnection(connection: Connection) {
await this.testConnection(connection);
const client = loadHttpClient(connection?.host, parseInt(`${connection?.port}`, 10));

const data = await client.get('/_cat/indices', 'format=json');
const indices = data.map(index => ({

Check failure on line 78 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (macos-latest, 18.x)

Parameter 'index' implicitly has an 'any' type.

Check failure on line 78 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest, 18.x)

Parameter 'index' implicitly has an 'any' type.

Check failure on line 78 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (windows-latest, 18.x)

Parameter 'index' implicitly has an 'any' type.
...index,
docs: {
count: parseInt(index['docs.count'], 10),
deleted: parseInt(index['docs.deleted'], 10),
},
store: { size: index['store.size'] },
}));
this.established = { ...connection, indices };

Check failure on line 86 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (macos-latest, 18.x)

Property 'activeIndex' is missing in type '{ indices: any; id?: number | undefined; name: string; host: string; port: string | number; username?: string | undefined; password?: string | undefined; queryParameters?: string | undefined; }' but required in type '{ id?: number | undefined; name: string; host: string; port: string | number; username?: string | undefined; password?: string | undefined; queryParameters?: string | undefined; indices: { ...; }[]; activeIndex: { ...; }; }'.

Check failure on line 86 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest, 18.x)

Property 'activeIndex' is missing in type '{ indices: any; id?: number | undefined; name: string; host: string; port: string | number; username?: string | undefined; password?: string | undefined; queryParameters?: string | undefined; }' but required in type '{ id?: number | undefined; name: string; host: string; port: string | number; username?: string | undefined; password?: string | undefined; queryParameters?: string | undefined; indices: { ...; }[]; activeIndex: { ...; }; }'.

Check failure on line 86 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (windows-latest, 18.x)

Property 'activeIndex' is missing in type '{ indices: any; id?: number | undefined; name: string; host: string; port: string | number; username?: string | undefined; password?: string | undefined; queryParameters?: string | undefined; }' but required in type '{ id?: number | undefined; name: string; host: string; port: string | number; username?: string | undefined; password?: string | undefined; queryParameters?: string | undefined; indices: { ...; }[]; activeIndex: { ...; }; }'.
},
selectIndex(indexName: string) {
this.established = {
...this.established,
activeIndex: this.established.indices.find(({ index }) => index === indexName),

Check failure on line 91 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (macos-latest, 18.x)

Type '{ health: string; status: string; index: string; uuid: string; docs: { count: number; deleted: number; }; store: { size: string; }; pri: { store: { size: string; }; }; } | undefined' is not assignable to type '{ health: string; status: string; index: string; uuid: string; docs: { count: number; deleted: number; }; store: { size: string; }; pri: { store: { size: string; }; }; }'.

Check failure on line 91 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (macos-latest, 18.x)

Object is possibly 'null'.

Check failure on line 91 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest, 18.x)

Type '{ health: string; status: string; index: string; uuid: string; docs: { count: number; deleted: number; }; store: { size: string; }; pri: { store: { size: string; }; }; } | undefined' is not assignable to type '{ health: string; status: string; index: string; uuid: string; docs: { count: number; deleted: number; }; store: { size: string; }; pri: { store: { size: string; }; }; }'.

Check failure on line 91 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest, 18.x)

Object is possibly 'null'.

Check failure on line 91 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (windows-latest, 18.x)

Type '{ health: string; status: string; index: string; uuid: string; docs: { count: number; deleted: number; }; store: { size: string; }; pri: { store: { size: string; }; }; } | undefined' is not assignable to type '{ health: string; status: string; index: string; uuid: string; docs: { count: number; deleted: number; }; store: { size: string; }; pri: { store: { size: string; }; }; }'.

Check failure on line 91 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (windows-latest, 18.x)

Object is possibly 'null'.
};
},
async searchQDSL(index: string | undefined, qdsl: string) {
const url = index
? `${this.established?.host}:${this.established?.port}/${index}/_search`
: `${this.established?.host}:${this.established?.port}/_search?`;
const client = loadHttpClient(this.established?.host, this.established?.port);

Check failure on line 95 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (macos-latest, 18.x)

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.

Check failure on line 95 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest, 18.x)

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.

Check failure on line 95 in src/store/connectionStore.ts

View workflow job for this annotation

GitHub Actions / build (windows-latest, 18.x)

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.

// eslint-disable-next-line no-console
console.log(`searchQDSL_URL ${url}`);
try {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: qdsl,
});
const data = await response.json();
if (!response.ok) throw new CustomError(response.status, data);
return data;
} catch (err) {
// eslint-disable-next-line no-console
console.log(`searchQDSL error ${JSON.stringify({ err })}`);

if (err instanceof CustomError) {
throw new CustomError(err.status, err.details);
}
if (err instanceof Error) {
throw new CustomError(500, err.message);
}
throw new CustomError(500, `unknown error, trace: ${JSON.stringify(err)}`);
}
return client.post(index ? '/${index}/_search' : '/_search', undefined, JSON.parse(qdsl));
},
},
});
Original file line number Diff line number Diff line change
@@ -1,20 +1,32 @@
<template>
<div class="table-select-container">
<n-select v-model:value="value" :options="options" placeholder="no table selected" />
<div class="collection-selector-container">
<n-select
:options="options"
placeholder="No collection/index selected"
@update:value="handleUpdateValue"
/>
</div>
</template>

<script setup lang="ts">
const value = ref(null);
import { storeToRefs } from 'pinia';
import { useConnectionStore } from '../../../store';
const options = ref([
{ label: '1', value: 2 },
{ label: '2', value: 1 },
]);
const connectionStore = useConnectionStore();
const { establishedIndexNames } = storeToRefs(connectionStore);
// build options list
const options = computed(() =>
establishedIndexNames.value.map(name => ({ label: name, value: name })),
);
const handleUpdateValue = (value: string) => {
connectionStore.selectIndex(value);
};
</script>

<style lang="scss" scoped>
.table-select-container {
.collection-selector-container {
height: 100%;
width: 260px;
display: flex;
Expand Down
5 changes: 2 additions & 3 deletions src/views/connect/components/connect-list.vue
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const options = reactive([
{ key: 3, label: lang.t('connection.operations.remove') },
]);
const connectionStore = useConnectionStore();
const { fetchConnections, removeConnection, establishConnection, testConnection } = connectionStore;
const { fetchConnections, removeConnection, establishConnection } = connectionStore;
const { connections, established } = storeToRefs(connectionStore);
fetchConnections();
Expand All @@ -70,8 +70,7 @@ const handleSelect = (key: number, connection: Connection) => {
const establishConnect = async (connection: Connection) => {
try {
await testConnection(connection);
establishConnection(connection);
await establishConnection(connection);
} catch (err) {
const error = err as CustomError;
message.error(`status: ${error.status}, details: ${error.details}`, {
Expand Down
4 changes: 2 additions & 2 deletions src/views/connect/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
</div>
<div class="connect-body">
<div class="table-select">
<table-select />
<collection-selector />
</div>
<div class="editor-container">
<Editor />
Expand All @@ -25,7 +25,7 @@
import { Add } from '@vicons/carbon';
import ConnectModal from './components/connect-dialog.vue';
import connectList from './components/connect-list.vue';
import tableSelect from './components/table-select.vue';
import collectionSelector from './components/collection-selector.vue';
import Editor from '../editor/index.vue';
import { useAppStore } from './../../store';
Expand Down

0 comments on commit b122704

Please sign in to comment.