You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@apisix.apache.org by GitBox <gi...@apache.org> on 2020/12/11 06:58:13 UTC

[GitHub] [apisix-dashboard] juzhiyuan commented on a change in pull request #978: Refactor online debug fe

juzhiyuan commented on a change in pull request #978:
URL: https://github.com/apache/apisix-dashboard/pull/978#discussion_r540729520



##########
File path: web/src/pages/Route/components/DebugViews/AuthenticationView.tsx
##########
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import React, { useState } from 'react';
+import { Form, Input, Radio, Card } from 'antd';
+import { useIntl } from 'umi';
+import { AUTH_LIST } from '../../constants';
+import styles from './index.less';
+
+const AuthenticationView: React.FC<RouteModule.DebugViewProps> = (props) => {
+  const { formatMessage } = useIntl();
+  const [authType, setAuthType] = useState('none');
+
+  const getAuthFormItems = () => {
+    switch (props.form.getFieldValue('authType')) {
+      case 'basic-auth':
+        return (
+          <>
+            <Form.Item
+              label={formatMessage({ id: 'page.route.form.itemLabel.username' })}
+              name="username"
+              rules={[
+                {
+                  required: true,
+                  message: `${formatMessage({
+                    id: 'component.global.pleaseEnter',
+                  })}${formatMessage({ id: 'page.route.form.itemLabel.username' })}`,
+                },
+              ]}
+            >
+              <Input />
+            </Form.Item>
+            <Form.Item
+              label={formatMessage({ id: 'page.route.form.itemLabel.password' })}
+              name="password"
+              rules={[
+                {
+                  required: true,
+                  message: `${formatMessage({
+                    id: 'component.global.pleaseEnter',
+                  })}${formatMessage({ id: 'page.route.form.itemLabel.password' })}`,
+                },
+              ]}
+            >
+              <Input.Password />
+            </Form.Item>
+          </>
+        );
+      case 'jwt-auth':
+        return (
+          <Form.Item
+            label={formatMessage({ id: 'page.route.form.itemLabel.token' })}
+            name="Authorization"
+            rules={[
+              {
+                required: true,
+                message: `${formatMessage({ id: 'component.global.pleaseEnter' })}${formatMessage({
+                  id: 'page.route.form.itemLabel.token',
+                })}`,
+              },
+            ]}
+          >
+            <Input />
+          </Form.Item>
+        );
+      case 'key-auth':
+        return (
+          <Form.Item
+            label={formatMessage({ id: 'page.route.form.itemLabel.apikey' })}
+            name="apikey"
+            rules={[
+              {
+                required: true,
+                message: `${formatMessage({ id: 'component.global.pleaseEnter' })}${formatMessage({
+                  id: 'page.route.form.itemLabel.apikey',
+                })}`,
+              },
+            ]}
+          >
+            <Input />
+          </Form.Item>
+        );
+      default:
+        return <div>{formatMessage({ id: 'page.route.debugWithoutAuth' })}</div>;
+    }
+  };
+
+  return (
+    <Card>
+      <Form name="authForm" form={props.form}>
+        <div className={styles.authForm}>
+          <Form.Item name="authType">
+            <Radio.Group
+              defaultValue={authType}
+              onChange={(event) => {
+                const currentValue = event.target.value;
+                setAuthType(currentValue);
+                props.form.setFieldsValue({ autyType: currentValue });
+              }}
+            >
+              <Radio value="none">none</Radio>
+              {AUTH_LIST.map((type) => (
+                <Radio value={type}>{type}</Radio>

Review comment:
       key is needed

##########
File path: web/src/pages/Route/components/DebugViews/AuthenticationView.tsx
##########
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import React, { useState } from 'react';
+import { Form, Input, Radio, Card } from 'antd';
+import { useIntl } from 'umi';
+import { AUTH_LIST } from '../../constants';
+import styles from './index.less';
+
+const AuthenticationView: React.FC<RouteModule.DebugViewProps> = (props) => {
+  const { formatMessage } = useIntl();
+  const [authType, setAuthType] = useState('none');
+
+  const getAuthFormItems = () => {
+    switch (props.form.getFieldValue('authType')) {
+      case 'basic-auth':
+        return (
+          <>
+            <Form.Item
+              label={formatMessage({ id: 'page.route.form.itemLabel.username' })}
+              name="username"
+              rules={[
+                {
+                  required: true,
+                  message: `${formatMessage({
+                    id: 'component.global.pleaseEnter',
+                  })}${formatMessage({ id: 'page.route.form.itemLabel.username' })}`,
+                },
+              ]}
+            >
+              <Input />
+            </Form.Item>
+            <Form.Item
+              label={formatMessage({ id: 'page.route.form.itemLabel.password' })}
+              name="password"
+              rules={[
+                {
+                  required: true,
+                  message: `${formatMessage({
+                    id: 'component.global.pleaseEnter',
+                  })}${formatMessage({ id: 'page.route.form.itemLabel.password' })}`,
+                },
+              ]}
+            >
+              <Input.Password />
+            </Form.Item>
+          </>
+        );
+      case 'jwt-auth':
+        return (
+          <Form.Item
+            label={formatMessage({ id: 'page.route.form.itemLabel.token' })}
+            name="Authorization"
+            rules={[
+              {
+                required: true,
+                message: `${formatMessage({ id: 'component.global.pleaseEnter' })}${formatMessage({
+                  id: 'page.route.form.itemLabel.token',
+                })}`,
+              },
+            ]}
+          >
+            <Input />
+          </Form.Item>
+        );
+      case 'key-auth':
+        return (
+          <Form.Item
+            label={formatMessage({ id: 'page.route.form.itemLabel.apikey' })}
+            name="apikey"
+            rules={[
+              {
+                required: true,
+                message: `${formatMessage({ id: 'component.global.pleaseEnter' })}${formatMessage({
+                  id: 'page.route.form.itemLabel.apikey',
+                })}`,
+              },
+            ]}
+          >
+            <Input />
+          </Form.Item>
+        );
+      default:
+        return <div>{formatMessage({ id: 'page.route.debugWithoutAuth' })}</div>;
+    }
+  };
+
+  return (
+    <Card>
+      <Form name="authForm" form={props.form}>
+        <div className={styles.authForm}>
+          <Form.Item name="authType">
+            <Radio.Group
+              defaultValue={authType}
+              onChange={(event) => {
+                const currentValue = event.target.value;
+                setAuthType(currentValue);
+                props.form.setFieldsValue({ autyType: currentValue });
+              }}
+            >
+              <Radio value="none">none</Radio>

Review comment:
       use `None` as label would be better
   
   ```suggestion
                 <Radio value="none">None</Radio>
   ```

##########
File path: web/src/pages/Route/components/DebugViews/DebugDrawView.tsx
##########
@@ -0,0 +1,238 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import React, { useEffect, useState } from 'react';
+import { Input, Select, Card, Tabs, Form, Drawer, Spin, notification } from 'antd';
+import { useIntl } from 'umi';
+import CodeMirror from '@uiw/react-codemirror';
+import { PanelSection } from '@api7-dashboard/ui';
+import queryString from 'query-string';
+import Base64 from 'base-64';
+
+import {
+  HTTP_METHOD_OPTION_LIST,
+  DEFAULT_DEBUG_PARAM_FORM_DATA,
+  DEFAULT_DEBUG_AUTH_FORM_DATA,
+} from '../../constants';
+import { DebugParamsView, AuthenticationView } from '.';
+import { debugRoute } from '../../service';
+import styles from './index.less';
+
+const { Option } = Select;
+const { Search } = Input;
+const { TabPane } = Tabs;
+
+const DebugDrawView: React.FC<RouteModule.DebugDrawProps> = (props) => {
+  const { formatMessage } = useIntl();
+  const [httpMethod, setHttpMethod] = useState('GET');
+  const [showBodyTab, setShowBodyTab] = useState(false);
+  const [queryForm] = Form.useForm();
+  const [bodyForm] = Form.useForm();
+  const [authForm] = Form.useForm();
+  const [headerForm] = Form.useForm();
+  const [responseCode, setResponseCode] = useState(
+    `${formatMessage({ id: 'page.route.debug.showResultAfterSendRequest' })}`,
+  );
+  const [loading, setLoading] = useState(false);
+  const methodWithoutBody = ['GET', 'HEAD'];
+
+  const resetForms = () => {
+    queryForm.setFieldsValue(DEFAULT_DEBUG_PARAM_FORM_DATA);
+    bodyForm.setFieldsValue(DEFAULT_DEBUG_PARAM_FORM_DATA);
+    headerForm.setFieldsValue(DEFAULT_DEBUG_PARAM_FORM_DATA);
+    authForm.setFieldsValue(DEFAULT_DEBUG_AUTH_FORM_DATA);
+  };
+
+  useEffect(() => {
+    resetForms();
+  }, []);
+
+  const transformBodyParamsFormData = (formData: RouteModule.debugRequestParamsFormData[]) => {
+    let transformData = {};
+    (formData || [])
+      .filter((data) => data.check)
+      .forEach((data) => {
+        transformData = {
+          ...transformData,
+          [data.key]: data.value,
+        };
+      });
+
+    return transformData;
+  };
+
+  const transformHeaderAndQueryParamsFormData = (
+    formData: RouteModule.debugRequestParamsFormData[],
+  ) => {
+    let transformData = {};
+    (formData || [])
+      .filter((data) => data.check)
+      .forEach((data) => {
+        transformData = {
+          ...transformData,
+          [data.key]: [...(transformData[data.key] || []), data.value],
+        };
+      });
+
+    return transformData;
+  };
+
+  const transformAuthFormData = (formData: RouteModule.authData, headerData: any) => {
+    const { authType } = formData;
+
+    switch (authType) {
+      case 'basic-auth':
+        return {
+          ...headerData,
+          Authorization: [`Basic ${Base64.encode(`${formData.username}:${formData.password}`)}`],
+        };
+      case 'jwt-auth':
+        return {
+          ...headerData,
+          Authorization: [formData.Authorization],
+        };
+      case 'key-auth':
+        return {
+          ...headerData,
+          apikey: [formData.apikey],
+        };
+      default:
+        break;
+    }
+
+    return headerData;
+  };
+
+  const handleDebug = (url: string) => {
+    if (url === '') {
+      notification.warning({
+        message: formatMessage({ id: 'page.route.input.placeholder.requestUrl' }),
+      });
+      return;
+    }
+    const queryFormData = transformHeaderAndQueryParamsFormData(queryForm.getFieldsValue().params);
+    const bodyFormData = transformBodyParamsFormData(bodyForm.getFieldsValue().params);
+    const pureHeaderFormData = transformHeaderAndQueryParamsFormData(
+      headerForm.getFieldsValue().params,
+    );
+    const headerFormData = transformAuthFormData(authForm.getFieldsValue(), pureHeaderFormData);
+    const urlQueryString = queryString.stringify(queryFormData);
+
+    setLoading(true);
+    debugRoute({
+      url: `${url}${urlQueryString && `?${urlQueryString}`}`,
+      method: httpMethod,
+      bodyParams: bodyFormData,
+      headerParams: headerFormData,
+    })
+      .then((req) => {
+        setLoading(false);
+        setResponseCode(JSON.stringify(req.data.data, null, 2));
+      })
+      .catch(() => {
+        setLoading(false);
+      });
+  };
+  return (
+    <Drawer
+      title={formatMessage({ id: 'page.route.onlineDebug' })}
+      mask={false}
+      maskClosable={false}
+      visible={props.visible}
+      width={600}
+      onClose={() => {
+        props.onClose();
+      }}
+      className={styles.routeDebugDraw}
+    >
+      <Card bordered={false}>
+        <Input.Group compact>
+          <Select
+            defaultValue={httpMethod}
+            style={{ width: '20%' }}
+            onChange={(value) => {
+              setHttpMethod(value);
+              setShowBodyTab(!(methodWithoutBody.indexOf(value) > -1));
+            }}
+            size="large"
+          >
+            {HTTP_METHOD_OPTION_LIST.map((method) => {
+              return <Option value={method}>{method}</Option>;

Review comment:
       key is also needed

##########
File path: web/src/pages/Route/service.ts
##########
@@ -85,3 +85,10 @@ export const checkHostWithSSL = (hosts: string[]) =>
     method: 'POST',
     data: hosts,
   });
+
+export const debugRoute = (params: RouteModule.debugRequest) => {
+  return request('/debug-request-forwarding', {
+    method: 'post',
+    data: { ...params },

Review comment:
       may don't need to destruct here?

##########
File path: web/src/pages/Route/components/DebugViews/DebugParamsView.tsx
##########
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import React from 'react';
+import { Form, Input, Row, Col, Checkbox } from 'antd';
+import { useIntl } from 'umi';
+import { MinusCircleOutlined } from '@ant-design/icons';
+
+import styles from './index.less';
+
+const DebugParamsView: React.FC<RouteModule.DebugViewProps> = (props) => {
+  const { formatMessage } = useIntl();
+
+  return (
+    <Form name="dynamic_form_nest_item" className={styles.routeDebugDraw} form={props.form}>
+      <Form.List name="params">
+        {(fields, { add, remove }) => {
+          return (
+            <>
+              {fields.map((field, index) => (
+                <Row gutter={16}>

Review comment:
       key




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org