@grafana/data#base64StringToArrowTable TypeScript Examples

The following examples show how to use @grafana/data#base64StringToArrowTable. 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: FileBrowser.tsx    From grafana-s3-plugin with Apache License 2.0 4 votes vote down vote up
listFiles = (prefix: string, edit?: boolean) => {
    getBackendSrv()
      .datasourceRequest({
        url: '/api/ds/query',
        method: 'POST',
        data: {
          queries: [
            {
              refId: 'A',
              path: prefix,
              query: 'LIST FORMATTED',
              orgId: this.props.orgId,
              datasourceId: this.props.dsId,
            },
          ],
        },
      })
      .then(response => {
        const b64 = response.data.results.A.dataframes[0];
        const table = base64StringToArrowTable(b64);
        const frame = arrowTableToDataFrame(table);

        frame.fields[0].display = (value: string) => {
          let icon = this.icons['error'];

          const parts = /^(.*),type=(.*),key=(.*)$/.exec(value);
          if (parts !== null && parts.length === 4) {
            value = parts![1];
            icon = this.icons[parts![2]] || icon;
          }

          return {
            prefix: icon,
            numeric: Number.NaN,
            text: value,
          };
        };

        // @ts-ignore
        frame.fields[0].getLinks = (options: any) => {
          const i = options.valueRowIndex;

          let value = table.getColumnAt(0)!.get(i);
          let href = undefined;

          const parts = /^(.*),type=(.*),key=(.*)$/.exec(value);
          if (parts !== null && parts.length === 4 && parts![2] === 'folder') {
            value = parts![1];
            href = this.setsearchparams({ explore: true, prefix: parts![3] });
          }

          if (href) {
            return [{ href: href, title: value }];
          } else {
            return [undefined];
          }
        };

        frame.fields[1].display = getDisplayProcessor({ field: frame.fields[1] });
        frame.fields[2].display = getDisplayProcessor({ field: frame.fields[2] });

        frame.fields[3].display = (value: string) => {
          return {
            numeric: Number.NaN,
            text: this.icons['delete'],
          };
        };

        // @ts-ignore
        frame.fields[3].getLinks = (options: any) => {
          const i = options.valueRowIndex;
          const value = table.getColumnAt(0)!.get(i);
          let onClick = undefined;

          const parts = /^(.*),type=(.*),key=(.*)$/.exec(value);
          if (parts !== null && parts.length === 4) {
            onClick = () => {
              console.log('Delete', parts![2], parts![3]);
              return getBackendSrv()
                .datasourceRequest({
                  url: '/api/ds/query',
                  method: 'POST',
                  data: {
                    queries: [
                      {
                        refId: 'A',
                        path: parts![3],
                        query: 'DELETE ' + parts![2],
                        orgId: this.props.orgId,
                        datasourceId: this.props.dsId,
                      },
                    ],
                  },
                })
                .then(response => {
                  this.listFiles(this.state.prefix);
                });
            };
          }

          return [{ onClick: onClick, title: 'Delete' }];

          if (onClick) {
            return [{ onClick: onClick, title: 'Delete' }];
          } else {
            return [undefined];
          }
        };

        if (edit) {
          this.setState({
            hints: frame!.meta!.custom!.folders.map((folder: any) => ({ label: folder, value: folder })),
          });
        } else if (prefix === this.state.prefix) {
          this.setState({
            dirty: false,
            files: frame,
            hints: frame!.meta!.custom!.folders.map((folder: any) => ({ label: folder, value: folder })),
          });
        }
      });
  };
Example #2
Source File: FileUploader.tsx    From grafana-s3-plugin with Apache License 2.0 4 votes vote down vote up
FileUploader: FC<Props> = props => {
  const [errors, _setErrors] = useState<string[]>([]);

  const setError = (error: string) => {
    errors.push(error);
    _setErrors(errors);
  };

  const [progress, _setProgress] = useState<Progress>({
    busy: false,
    message: 'Done',
    progress: 100,
  });

  const setProgress = (progress: Progress) => {
    console.log(progress.message, progress.progress, '%');
    _setProgress(progress);
  };

  let credentials: any = undefined;
  const authenticate = () => {
    if (credentials && !credentials.expired) {
      return Promise.resolve();
    }

    setProgress({
      busy: true,
      message: 'Authenticating',
      progress: 0,
    });

    return getBackendSrv()
      .datasourceRequest({
        url: '/api/ds/query',
        method: 'POST',
        data: {
          queries: [
            {
              refId: 'A',
              query: 'UPLOAD',
              orgId: props.orgId,
              datasourceId: props.dsId,
            },
          ],
        },
      })
      .then(response => {
        setProgress({
          busy: true,
          message: 'Authenticating',
          progress: 80,
        });
        const b64 = response.data.results.A.dataframes[0];
        const table = base64StringToArrowTable(b64);
        credentials = new AWS.Credentials({
          accessKeyId: table.getColumn('AccessKeyId').get(0),
          secretAccessKey: table.getColumn('SecretAccessKey').get(0),
          sessionToken: table.getColumn('SessionToken').get(0),
        });
        AWS.config.update({
          region: props.region,
          credentials: credentials,
        });
        setProgress({
          busy: true,
          message: 'Authenticating',
          progress: 100,
        });
      });
  };

  const uploadFile = (file: any, i: number, n: number) => {
    return authenticate().then(() => {
      setProgress({
        busy: true,
        message: 'Uploading (' + i + ' of ' + n + '): "' + file.name + '"',
        progress: 0,
      });
      return new AWS.S3.ManagedUpload({
        params: {
          Bucket: props.bucket,
          Key: props.prefix + file.name,
          Body: file,
          ACL: 'private',
        },
      })
        .on('httpUploadProgress', function(evt) {
          setProgress({
            busy: true,
            message: 'Uploading (' + i + ' of ' + n + '): "' + file.name + '"',
            progress: (100 * evt.loaded) / evt.total,
          });
        })
        .promise()
        .catch((err: any) => {
          setProgress({
            busy: true,
            message: file.name + ': ' + err.message,
            progress: 100,
          });
          setError(file.name + ': ' + err.message);
        });
    });
  };

  const onFileUpload = async (event: any) => {
    const files = event.target.files;

    if (!files.length) {
      return;
    }

    _setErrors([]);
    for (let i = 0; i < files.length; i++) {
      await uploadFile(files[i], i + 1, files.length);
      props.refresh();
    }

    setProgress({
      busy: false,
      message: 'Done',
      progress: 100,
    });
    // @ts-ignore
    $('#uploadInput').val('');
  };

  const theme = useTheme();
  const style = getStyles(theme, 'md');

  return (
    <div style={{ width: '100%' }}>
      <Box display="flex" alignItems="center" mb="12px">
        <Box minWidth={35} key="button">
          {/*
          // @ts-ignore*/}
          <label className={style.button} disabled={progress.busy}>
            <Icon name="upload" className={style.icon} />
            Upload files
            <input
              type="file"
              id="uploadInput"
              className={style.fileUpload}
              onChange={onFileUpload}
              multiple={true}
              disabled={progress.busy}
            />
          </label>
        </Box>
        {progress.busy && [
          <Box width="calc(100% - 200px)" mx="12px" key="progress">
            <Typography variant="body2" noWrap={true} color="textSecondary">
              {progress.message}
            </Typography>
            <LinearProgress variant="determinate" color="secondary" value={progress.progress} />
          </Box>,
          <Box width="35px" key="label">
            <Typography variant="body2" color="textSecondary">
              &nbsp;
            </Typography>
            <Typography variant="body2" color="textSecondary">{`${Math.round(progress.progress)}%`}</Typography>
          </Box>,
        ]}
      </Box>
      {errors.map(err => (
        <Typography variant="body2" noWrap={true} color="error">
          {err}
        </Typography>
      ))}
    </div>
  );
}