aboutsummaryrefslogtreecommitdiffstats
path: root/client/js/app/src/app/pages/querybuilder/query-endpoint/query-endpoint.jsx
blob: 23f171fb3ee56f041cf0bb057485cb1c2253c3fd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import React from 'react';
import { Select, TextInput, Button } from '@mantine/core';
import { errorMessage } from 'app/libs/notification';
import {
  ACTION,
  dispatch,
  useQueryBuilderContext,
} from 'app/pages/querybuilder/context/query-builder-provider';
import { Container, Content } from 'app/components';

function send(event, method, url, body) {
  event.preventDefault();
  dispatch(ACTION.SET_HTTP, { loading: true });
  fetch(url, {
    method,
    headers: { 'Content-Type': 'application/json;charset=utf-8' },
    body,
  })
    .then((response) => response.json())
    .then((result) =>
      dispatch(ACTION.SET_HTTP, {
        response: JSON.stringify(result, null, 4),
      })
    )
    .catch((error) => {
      errorMessage(error.message);
      dispatch(ACTION.SET_HTTP, {});
    });
}

export default function QueryEndpoint() {
  const { method, url, fullUrl, body } = useQueryBuilderContext('request');
  const hasError = useQueryBuilderContext((ctx) => ctx.query.error != null);
  const loading = useQueryBuilderContext((ctx) => ctx.http.loading);

  return (
    <Content>
      <form onSubmit={(event) => send(event, method, fullUrl, body)}>
        <Container sx={{ gridTemplateColumns: 'max-content auto max-content' }}>
          <Select
            data={['POST', 'GET']}
            onChange={(value) => dispatch(ACTION.SET_METHOD, value)}
            value={method}
            radius={0}
          />
          <TextInput
            onChange={(e) => dispatch(ACTION.SET_URL, e.currentTarget.value)}
            value={url}
            radius={0}
          />
          <Button
            radius={0}
            type="submit"
            loading={loading}
            disabled={hasError}
          >
            Send
          </Button>
        </Container>
      </form>
    </Content>
  );
}