lodash-es#uniqueId TypeScript Examples

The following examples show how to use lodash-es#uniqueId. 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: github-login.tsx    From bext with MIT License 4 votes vote down vote up
GithubLogin: FC = () => {
  const [{ code }] = useUrlState({ code: undefined });
  const historyReplace = useHistoryReplace();
  const { notify, dismissNotification } = useNotifications();

  useRequest(
    async () => {
      const id = uniqueId('login-loading');
      notify({
        id,
        status: 'loading',
        message: '登录中',
        dismissAfter: 0,
        dismissible: false,
      });
      const response = await fetch(`/api/gh/login?code=${code}`);
      const data = await response.json();
      if (
        response.ok &&
        data.code === 200 &&
        typeof data?.data?.access_token === 'string'
      ) {
        accessToken$.next(data.data.access_token);
        notify({
          status: 'success',
          message: '登录成功',
        });
        historyReplace(location.pathname);
        trackEvent(Events.ghLoginSuccess);
      } else {
        notify({
          status: 'error',
          message:
            data?.data?.error_description || data?.msg || response.statusText,
        });
      }
      dismissNotification(id);
    },
    {
      ready: !!code,
      refreshDeps: [code],
      onError: () => notify({ status: 'error', message: '登录失败' }),
    },
  );

  const el = useObservableState(
    useObservable(() =>
      octokit$.pipe(
        switchMap((octokit) =>
          octokit
            ? user$.pipe(
                map(({ status, user }) => {
                  switch (status) {
                    case 'complete':
                      return (
                        <div className="flex justify-between">
                          <Persona
                            imageUrl={user?.avatar_url}
                            text={user?.name || user?.login}
                            secondaryText={user?.bio || '暂无签名'}
                          />
                          <Link onClick={() => accessToken$.next(undefined)}>
                            退出
                          </Link>
                        </div>
                      );
                    case 'loading':
                      return '获取用户信息...';
                    default:
                      return (
                        <>
                          发布、更新脚本请先
                          <LoginLink />
                        </>
                      );
                  }
                }),
                startWith('获取用户信息...'),
              )
            : of(
                <>
                  发布、更新脚本请先
                  <LoginLink />
                </>,
              ),
        ),
      ),
    ),
    null,
  );

  return (
    <>
      <Title>Github</Title>
      {el}
    </>
  );
}
Example #2
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>
    </>
  );
}