Skip to content

Commit

Permalink
feat: impl post, put, delete #10
Browse files Browse the repository at this point in the history
Signed-off-by: seven <[email protected]>
  • Loading branch information
Blankll committed Jan 7, 2024
1 parent 6572afc commit e8cd72e
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 25 deletions.
31 changes: 31 additions & 0 deletions src/common/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,35 @@ export const loadHttpClient = (host: string, port: number) => ({
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);
}
},
});
50 changes: 41 additions & 9 deletions src/store/connectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,20 @@ export type ConnectionIndex = {
};

const { storeAPI } = window;
type Established =
| (Connection & { indices: Array<ConnectionIndex>; activeIndex?: ConnectionIndex })
| null;

const buildPath = (index: string | undefined, path: string | undefined) => {
return index && !['_nodes', '_cluster'].includes(path?.split('/')[0] ?? '')
? `/${index}/${path}`
: `/${path}`;
};

export const useConnectionStore = defineStore('connectionStore', {
state(): {
connections: Connection[];
established:
| (Connection & { indices: Array<ConnectionIndex>; activeIndex: ConnectionIndex })
| null;
established: Established;
} {
return {
connections: [],
Expand Down Expand Up @@ -75,7 +82,7 @@ export const useConnectionStore = defineStore('connectionStore', {
const client = loadHttpClient(connection?.host, parseInt(`${connection?.port}`, 10));

const data = await client.get('/_cat/indices', 'format=json');
const indices = data.map(index => ({
const indices = data.map((index: { [key: string]: string }) => ({
...index,
docs: {
count: parseInt(index['docs.count'], 10),
Expand All @@ -88,13 +95,38 @@ export const useConnectionStore = defineStore('connectionStore', {
selectIndex(indexName: string) {
this.established = {
...this.established,
activeIndex: this.established.indices.find(({ index }) => index === indexName),
};
activeIndex: this.established?.indices.find(({ index }) => index === indexName),
} as Established;
},
async searchQDSL(index: string | undefined, qdsl: string) {
const client = loadHttpClient(this.established?.host, this.established?.port);
async searchQDSL({
method,
path,
index,
qdsl,
}: {
method: string;
path: string;
index?: string;
qdsl?: string;
}) {
const client = loadHttpClient(
this.established?.host || '',
parseInt(`${this.established?.port || 9200}`, 10),
);

return client.post(index ? `/${index}/_search` : '/_search', undefined, JSON.parse(qdsl));
const reqPath = buildPath(index, path);
const body = qdsl ? JSON.parse(qdsl) : undefined;

// eslint-disable-next-line no-console
console.log('before req', { index, qdsl, method, path });
const dispatch: { [method: string]: () => Promise<unknown> } = {
POST: async () => client.post(reqPath, undefined, body),
PUT: async () => client.put(reqPath, undefined, body),
DELETE: async () => client.delete(reqPath, undefined, body),
GET: async () =>
body ? client.post(reqPath, undefined, body) : client.get(reqPath, 'format=json'),
};
return dispatch[method]();
},
},
});
47 changes: 31 additions & 16 deletions src/views/editor/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ let queryEditor: Editor | null = null;
const queryEditorRef = ref();
const displayEditorRef = ref();
const executionGutterClass = 'execute-button-decoration';
const executeDecorationType = 'action-execute-decoration.search';
let executeDecorations: Array<Decoration> = [];
const themeMedia = window.matchMedia('(prefers-color-scheme: light)');
const systemTheme = ref(themeMedia.matches);
themeMedia.addListener(e => {
Expand All @@ -89,11 +94,6 @@ watch(
},
);
const executionGutterClass = 'execute-button-decoration';
const executeDecorationType = 'action-execute-decoration.search';
let executeDecorations: Array<Decoration> = [];
const getActionMarksDecorations = (editor: Editor): Array<Decoration> => {
// Get the model of the editor
const model = editor.getModel();
Expand All @@ -115,13 +115,23 @@ const getActionMarksDecorations = (editor: Editor): Array<Decoration> => {
const refreshActionMarks = (editor: Editor) => {
const freshedDecorations = getActionMarksDecorations(editor);
// @See https://github.com/Microsoft/monaco-editor/issues/913#issuecomment-396537569
executeDecorations = editor.deltaDecorations(executeDecorations, freshedDecorations);
executeDecorations = editor.deltaDecorations(
executeDecorations,

Check failure on line 119 in src/views/editor/index.vue

View workflow job for this annotation

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

Argument of type 'Decoration[]' is not assignable to parameter of type 'string[]'.

Check failure on line 119 in src/views/editor/index.vue

View workflow job for this annotation

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

Argument of type 'Decoration[]' is not assignable to parameter of type 'string[]'.

Check failure on line 119 in src/views/editor/index.vue

View workflow job for this annotation

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

Argument of type 'Decoration[]' is not assignable to parameter of type 'string[]'.
freshedDecorations,
) as unknown as Decoration[];
};
const getAction = (editor: Editor, startLine: number) => {
const model = editor.getModel();
const action = model.getLineContent(startLine);
if (!model) {
return;
}
const commands = model.getLineContent(startLine).split(/[\/\s]+/);
const method = commands[0]?.toUpperCase();
const index = commands[1]?.startsWith('_') ? undefined : commands[1];
const path = commands.slice(index ? 2 : 1, commands.length).join('/');
let payload = '';
let qdsl = '';
// Get non-comment payload
for (let lineNumber = startLine + 1; lineNumber <= model.getLineCount(); lineNumber++) {
const lineContent = model.getLineContent(lineNumber);
Expand All @@ -131,21 +141,24 @@ const getAction = (editor: Editor, startLine: number) => {
if (lineContent.trim().startsWith('//')) {
continue;
}
payload += lineContent;
qdsl += lineContent;
}
return { payload, action };
return { qdsl, method, index, path };
};
const executeQueryAction = async (
queryEditor: Editor,
displayEditor: Editor,
position: { column: number; lineNumber: number },
) => {
const { action, payload } = getAction(queryEditor, position.lineNumber);
const action = getAction(queryEditor, position.lineNumber);
if (!action) {
return;
}
try {
// eslint-disable-next-line no-console
console.log(`execute ${JSON.stringify({ payload, action })}`);
console.log(`execute ${JSON.stringify({ action })}`);
if (!established.value) {
message.error(lang.t('editor.establishedRequired'), {
closable: true,
Expand All @@ -154,7 +167,10 @@ const executeQueryAction = async (
});
return;
}
const data = await searchQDSL(established.value?.activeIndex?.index, payload);
const data = await searchQDSL({
...action,
index: action.index || established.value?.activeIndex?.index,
});
displayEditor.getModel().setValue(JSON.stringify(data, null, ' '));

Check failure on line 174 in src/views/editor/index.vue

View workflow job for this annotation

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

Object is possibly 'null'.

Check failure on line 174 in src/views/editor/index.vue

View workflow job for this annotation

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

Object is possibly 'null'.

Check failure on line 174 in src/views/editor/index.vue

View workflow job for this annotation

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

Object is possibly 'null'.
} catch (err) {
const { status, details } = err as CustomError;
Expand Down Expand Up @@ -204,9 +220,8 @@ onMounted(async () => {
});
const { sourceFileAPI } = window;
sourceFileAPI.onSaveChortcut(async (_: unknown) => {
const content = queryEditor.getModel()!.getValue() || '';
await saveSourceToFile(content);
sourceFileAPI.onSaveChortcut(async () => {

Check failure on line 223 in src/views/editor/index.vue

View workflow job for this annotation

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

Expected 0 arguments, but got 1.

Check failure on line 223 in src/views/editor/index.vue

View workflow job for this annotation

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

Expected 0 arguments, but got 1.

Check failure on line 223 in src/views/editor/index.vue

View workflow job for this annotation

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

Expected 0 arguments, but got 1.
await saveSourceToFile(queryEditor.getModel()!.getValue() || '');

Check failure on line 224 in src/views/editor/index.vue

View workflow job for this annotation

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

'queryEditor' is possibly 'null'.

Check failure on line 224 in src/views/editor/index.vue

View workflow job for this annotation

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

'queryEditor' is possibly 'null'.

Check failure on line 224 in src/views/editor/index.vue

View workflow job for this annotation

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

'queryEditor' is possibly 'null'.
});
</script>

Expand Down

0 comments on commit e8cd72e

Please sign in to comment.