rxjs#concatMap TypeScript Examples

The following examples show how to use rxjs#concatMap. 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: publish-dialog.tsx    From bext with MIT License 4 votes vote down vote up
PublishDialog: FC<{ hide?: () => void }> = ({ hide }) => {
  const { draft } = useDraft();
  const { notify, dismissNotification } = useNotifications();
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(false);

  const onPublish = () => {
    const notifyId = uniqueId('export-notify');
    const loading = (message: string) =>
      notify({
        status: 'loading',
        message,
        dismissAfter: 0,
        dismissible: false,
        id: notifyId,
      });
    const branchName = Math.random().toString(16).slice(2);
    const user = user$.getValue()!.user!;
    const octokit = octokit$.getValue()!;
    setLoading(true);

    of(draft!)
      .pipe(
        switchMap((draft) => {
          if (!(draft.id && draft.name && draft.version)) {
            return throwError(() => new Error('请填写完整 ID,名称,版本号'));
          }
          loading('编译中');
          return from(
            excuteCompile({
              meta: {
                id: draft.id,
                name: draft.name,
                version: draft.version!,
                source: draft.source!,
                defaultConfig: draft.defaultConfig,
              },
            }),
          ).pipe(
            catchError(() =>
              throwError(() => new Error('编译错误,请打开控制台查看详情')),
            ),
            switchMap(() => {
              loading('获取仓库信息');
              return from(
                octokit.repos.get({
                  owner: user.login!,
                  repo: packageJson.metaRepository.repo,
                }),
              ).pipe(
                catchError((error) => {
                  if (error.status === 404) {
                    loading('Fork 仓库');
                    return from(
                      octokit.repos.createFork({
                        owner: packageJson.metaRepository.owner,
                        repo: packageJson.metaRepository.repo,
                      }),
                    ).pipe(
                      concatMap(() => {
                        loading('查询 Fork 结果');
                        return timer(5000, 10000).pipe(
                          switchMap(() =>
                            from(
                              octokit.repos.get({
                                owner: user.login!,
                                repo: packageJson.metaRepository.repo,
                              }),
                            ).pipe(catchError(() => EMPTY)),
                          ),
                          take(1),
                        );
                      }),
                    );
                  }
                  return throwError(() => new Error('查询仓库信息失败'));
                }),
              );
            }),
            switchMap(({ data: repo }) => {
              loading('创建分支');
              return from(
                octokit.git.createRef({
                  owner: repo.owner.login,
                  repo: repo.name,
                  ref: `refs/heads/${branchName}`,
                  sha: packageJson.metaRepository.base,
                }),
              );
            }),
            switchMap(() => {
              loading('同步主分支');
              return from(
                octokit.repos.mergeUpstream({
                  owner: user.login!,
                  repo: packageJson.metaRepository.repo,
                  branch: branchName,
                }),
              );
            }),
            switchMap(() => {
              loading('获取文件信息');
              return from(
                octokit.repos.getContent({
                  owner: user.login,
                  repo: packageJson.metaRepository.repo,
                  path: `meta/${draft.id}.json`,
                  ref: branchName,
                }),
              ).pipe(
                map(({ data }) =>
                  Array.isArray(data) ? data[0].sha : data.sha,
                ),
                catchError((err) =>
                  err?.status === 404 ? of(undefined) : throwError(() => err),
                ),
              );
            }),
            switchMap((sha) => {
              const prepareDraft = omit(cloneDeep(draft), 'id');
              prepareDraft.detail = DOMPurify.sanitize(
                prepareDraft.detail || '',
              );
              return from(
                octokit.repos.createOrUpdateFileContents({
                  owner: user.login,
                  repo: packageJson.metaRepository.repo,
                  path: `meta/${draft.id}.json`,
                  message,
                  content: Base64.encode(JSON.stringify(prepareDraft)),
                  sha,
                  branch: branchName,
                }),
              );
            }),
            switchMap(() =>
              from(
                octokit.pulls.create({
                  owner: packageJson.metaRepository.owner,
                  repo: packageJson.metaRepository.repo,
                  title: `[${draft.name}] ${draft.synopsis}`,
                  head: `${user.login}:${branchName}`,
                  base: 'master',
                  maintainer_can_modify: true,
                }),
              ),
            ),
          );
        }),
        finalize(() => {
          dismissNotification(notifyId);
          setLoading(false);
          hide?.();
        }),
        catchError((err) => {
          notify({
            status: 'error',
            message: err?.message || err?.toString(),
            dismissible: true,
            dismissAfter: 3000,
          });
          return EMPTY;
        }),
      )
      .subscribe(() => {
        notify({
          status: 'success',
          message: '提交成功,请返回查看、预览',
        });
      });
  };

  return (
    <>
      <TextField
        description="将会在切换版本时展示"
        value={message}
        onChange={(_, text) => setMessage(text || '')}
        disabled={loading}
      />
      <DialogFooter>
        <PrimaryButton
          className="ml-auto"
          onClick={onPublish}
          disabled={loading || !message.length}
        >
          发布
        </PrimaryButton>
      </DialogFooter>
    </>
  );
}