types#APIResponse TypeScript Examples

The following examples show how to use types#APIResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From datart with Apache License 2.0 7 votes vote down vote up
export function rejectHandle(error, rejectWithValue) {
  if (error?.response?.status === 401) {
    removeToken();
  }
  if ((error as AxiosError).response) {
    return rejectWithValue(
      ((error as AxiosError).response as AxiosResponse<APIResponse<any>>).data
        .message,
    );
  } else {
    return rejectWithValue(error.message);
  }
}
Example #2
Source File: request.ts    From datart with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated should be use @see {@link request2} in all places
 * @export
 * @template T
 * @param {(string | AxiosRequestConfig)} url
 * @param {AxiosRequestConfig} [config]
 * @return {*}  {Promise<APIResponse<T>>}
 */
export function request<T>(
  url: string | AxiosRequestConfig,
  config?: AxiosRequestConfig,
): Promise<APIResponse<T>> {
  const axiosPromise =
    typeof url === 'string' ? instance(url, config) : instance(url);
  return axiosPromise.then(response => response.data as APIResponse<T>);
}
Example #3
Source File: request.ts    From datart with Apache License 2.0 6 votes vote down vote up
/**
 * New Http Request Util
 * Feature:
 *  1. Support customize onFulfilled and onRejected handler
 *  2. Support default backend service response error handler
 *  3. Support redux rejected action handler @see rejectedActionMessageHandler
 * @template T
 * @param {(string | AxiosRequestConfig)} url
 * @param {AxiosRequestConfig} [config]
 * @param {{
 *     onFulfilled?: (value: AxiosResponse<any>) => APIResponse<T>;
 *     onRejected?: (error) => any;
 *   }} [extra]
 * @return {*}  {Promise<APIResponse<T>>}
 */
export function request2<T>(
  url: string | AxiosRequestConfig,
  config?: AxiosRequestConfig,
  extra?: {
    onFulfilled?: (value: AxiosResponse<any>) => APIResponse<T>;
    onRejected?: (error) => any;
  },
): Promise<APIResponse<T>> {
  const defaultFulfilled = response => response.data as APIResponse<T>;
  const defaultRejected = error => {
    throw standardErrorMessageTransformer(error);
  };
  const axiosPromise =
    typeof url === 'string' ? instance(url, config) : instance(url);
  return axiosPromise
    .then(extra?.onFulfilled || defaultFulfilled, error => {
      throw unAuthorizationErrorHandler(error);
    })
    .catch(extra?.onRejected || defaultRejected);
}
Example #4
Source File: FileUpload.tsx    From datart with Apache License 2.0 5 votes vote down vote up
export function FileUpload({
  form,
  sourceId,
  loading,
  onTest,
}: FileUploadProps) {
  const [uploadFileLoading, setUploadFileLoading] = useState(false);
  const t = useI18NPrefix('source');

  const normFile = useCallback(e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }, []);

  const uploadChange = useCallback(
    async ({ file }) => {
      if (file.status === 'done') {
        const format = file.name
          .substr(file.name.lastIndexOf('.') + 1)
          .toUpperCase();
        const response = file.response as APIResponse<string>;
        if (response.success) {
          form &&
            form.setFieldsValue({ config: { path: response.data, format } });
          onTest && onTest();
        }
        setUploadFileLoading(false);
      } else {
        setUploadFileLoading(true);
      }
    },
    [form, onTest],
  );

  return (
    <>
      <Form.Item
        label={t('form.file')}
        valuePropName="fileList"
        getValueFromEvent={normFile}
      >
        <Upload
          accept=".xlsx,.xls,.csv"
          method="post"
          action={`${BASE_API_URL}/files/datasource/?sourceId=${sourceId}`}
          headers={{ authorization: getToken()! }}
          showUploadList={false}
          onChange={uploadChange}
        >
          <Button
            icon={<UploadOutlined />}
            loading={uploadFileLoading || loading}
          >
            {t('form.selectFile')}
          </Button>
        </Upload>
      </Form.Item>
      <Form.Item
        name={['config', 'path']}
        css={`
          display: none;
        `}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name={['config', 'format']}
        css={`
          display: none;
        `}
      >
        <Input />
      </Form.Item>
    </>
  );
}
Example #5
Source File: Profile.tsx    From datart with Apache License 2.0 4 votes vote down vote up
export function Profile({ visible, onCancel }: ModalProps) {
  const [avatarLoading, setAvatarLoading] = useState(false);
  const dispatch = useDispatch();
  const loggedInUser = useSelector(selectLoggedInUser);
  const loading = useSelector(selectSaveProfileLoading);
  const [saveDisabled, setSaveDisabled] = useState(true);
  const [form] = Form.useForm();
  const t = useI18NPrefix('main.nav.account.profile');
  const tg = useI18NPrefix('global');

  const reset = useCallback(() => {
    form.resetFields();
    setSaveDisabled(true);
  }, [form]);

  useEffect(() => {
    if (visible) {
      reset();
    }
  }, [visible, reset, loggedInUser]);

  const avatarChange = useCallback(
    ({ file }) => {
      if (file.status === 'done') {
        const response = file.response as APIResponse<string>;
        if (response.success) {
          dispatch(updateUser({ ...loggedInUser!, avatar: response.data }));
        }
        setAvatarLoading(false);
      } else {
        setAvatarLoading(true);
      }
    },
    [dispatch, loggedInUser],
  );

  const formChange = useCallback(
    (_, values) => {
      setSaveDisabled(
        Object.entries(values).every(
          ([key, value]) => loggedInUser![key] === value,
        ),
      );
    },
    [loggedInUser],
  );

  const formSubmit = useCallback(
    values => {
      dispatch(
        saveProfile({
          user: {
            ...values,
            id: loggedInUser!.id,
            email: loggedInUser!.email,
          },
          resolve: () => {
            message.success(tg('operation.updateSuccess'));
            onCancel && onCancel(null as any);
          },
        }),
      );
    },
    [dispatch, loggedInUser, onCancel, tg],
  );

  return (
    <Modal
      title={t('title')}
      footer={false}
      visible={visible}
      onCancel={onCancel}
      afterClose={reset}
    >
      <AvatarUpload>
        <Avatar
          size={SPACE_UNIT * 24}
          src={`${BASE_RESOURCE_URL}${loggedInUser?.avatar}`}
        >
          {loggedInUser?.username.substr(0, 1).toUpperCase()}
        </Avatar>
        <Upload
          accept=".jpg,.jpeg,.png,.gif"
          method="post"
          action={`${BASE_API_URL}/files/user/avatar?userId=${loggedInUser?.id}`}
          headers={{ authorization: getToken()! }}
          className="uploader"
          showUploadList={false}
          onChange={avatarChange}
        >
          <Button type="link" loading={avatarLoading}>
            {t('clickUpload')}
          </Button>
        </Upload>
      </AvatarUpload>
      <Form
        form={form}
        initialValues={loggedInUser || void 0}
        labelCol={{ span: 7 }}
        wrapperCol={{ span: 12 }}
        onValuesChange={formChange}
        onFinish={formSubmit}
      >
        <FormItem label={t('username')}>{loggedInUser?.username}</FormItem>
        <FormItem label={t('email')}>{loggedInUser?.email}</FormItem>
        <FormItem label={t('name')} name="name">
          <Input />
        </FormItem>
        <FormItem label={t('department')} name="department">
          <Input />
        </FormItem>
        <Form.Item wrapperCol={{ offset: 7, span: 12 }}>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            disabled={saveDisabled}
            block
          >
            {tg('button.save')}
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
}
Example #6
Source File: index.tsx    From datart with Apache License 2.0 4 votes vote down vote up
export function OrgSettingPage() {
  const [deleteConfirmVisible, setDeleteConfirmVisible] = useState(false);
  const { actions } = useMainSlice();
  const [avatarLoading, setAvatarLoading] = useState(false);
  const dispatch = useDispatch();
  const currentOrganization = useSelector(selectCurrentOrganization);
  const saveOrganizationLoading = useSelector(selectSaveOrganizationLoading);
  const [form] = Form.useForm();
  const t = useI18NPrefix('orgSetting');
  const tg = useI18NPrefix('global');

  useEffect(() => {
    if (currentOrganization) {
      form.setFieldsValue(currentOrganization);
    }
  }, [form, currentOrganization]);

  const avatarChange = useCallback(
    ({ file }) => {
      if (file.status === 'done') {
        const response = file.response as APIResponse<string>;
        if (response.success) {
          dispatch(actions.setCurrentOrganizationAvatar(response.data));
        }
        setAvatarLoading(false);
      } else {
        setAvatarLoading(true);
      }
    },
    [dispatch, actions],
  );

  const save = useCallback(
    values => {
      dispatch(
        editOrganization({
          organization: { id: currentOrganization?.id, ...values },
          resolve: () => {
            message.success(tg('operation.updateSuccess'));
          },
        }),
      );
    },
    [dispatch, currentOrganization, tg],
  );

  const showDeleteConfirm = useCallback(() => {
    setDeleteConfirmVisible(true);
  }, []);

  const hideDeleteConfirm = useCallback(() => {
    setDeleteConfirmVisible(false);
  }, []);

  return (
    <Wrapper>
      <Card title={t('info')}>
        <Form
          name="org_form_"
          form={form}
          labelAlign="left"
          labelCol={{ offset: 1, span: 7 }}
          wrapperCol={{ span: 16 }}
          onFinish={save}
        >
          <Form.Item label={t('avatar')} className="avatar">
            <Avatar
              size={SPACE_UNIT * 20}
              src={`${BASE_RESOURCE_URL}${currentOrganization?.avatar}`}
            >
              {currentOrganization?.name.substr(0, 1).toUpperCase()}
            </Avatar>
          </Form.Item>
          <Form.Item label=" " colon={false}>
            <Upload
              accept=".jpg,.jpeg,.png,.gif"
              method="post"
              action={`${BASE_API_URL}/files/org/avatar?orgId=${currentOrganization?.id}`}
              headers={{ authorization: getToken()! }}
              className="uploader"
              showUploadList={false}
              onChange={avatarChange}
            >
              <Button type="link" loading={avatarLoading}>
                {t('clickToUpload')}
              </Button>
            </Upload>
          </Form.Item>
          <Form.Item
            name="name"
            label={t('name')}
            rules={[
              {
                required: true,
                message: `${t('name')}${tg('validation.required')}`,
              },
              {
                validator: debounce((_, value) => {
                  if (value === currentOrganization?.name) {
                    return Promise.resolve();
                  }
                  const data = { name: value };
                  return fetchCheckName('orgs', data);
                }, DEFAULT_DEBOUNCE_WAIT),
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item name="description" label={t('description')}>
            <Input.TextArea autoSize={{ minRows: 4, maxRows: 8 }} />
          </Form.Item>
          <Form.Item label=" " colon={false}>
            <Button
              type="primary"
              htmlType="submit"
              loading={saveOrganizationLoading}
            >
              {tg('button.save')}
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title={t('deleteOrg')}>
        <h4 className="notice">{t('deleteOrgDesc')}</h4>
        <Button danger onClick={showDeleteConfirm}>
          {t('deleteOrg')}
        </Button>
        <DeleteConfirm
          width={480}
          title={t('deleteOrg')}
          visible={deleteConfirmVisible}
          onCancel={hideDeleteConfirm}
        />
      </Card>
    </Wrapper>
  );
}