當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript Cache.get方法代碼示例

本文整理匯總了TypeScript中spica/cache.Cache.get方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Cache.get方法的具體用法?TypeScript Cache.get怎麽用?TypeScript Cache.get使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在spica/cache.Cache的用法示例。


在下文中一共展示了Cache.get方法的3個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: match

function match(pattern: string, segment: string): boolean {
  assert(segment === '/' || !segment.startsWith('/'));
  if (segment[0] === '.' && [...'?*'].includes(pattern[0])) return false;
  const id = `${pattern}:${segment}`;
  return cache.has(id)
    ? cache.get(id)!
    : cache.set(id, match(optimize(pattern), segment));

  function match(pattern: string, segment: string): boolean {
    const [p = '', ...ps] = [...pattern];
    const [s = '', ...ss] = [...segment];
    assert(typeof p === 'string');
    assert(typeof s === 'string');
    switch (p) {
      case '':
        return s === '';
      case '?':
        return s !== ''
            && s !== '/'
            && match(ps.join(''), ss.join(''));
      case '*':
        return s === '/'
          ? match(ps.join(''), segment)
          : Sequence
              .zip(
                Sequence.cycle([ps.join('')]),
                Sequence.from(segment)
                  .tails()
                  .map(ss => ss.join('')))
              .filter(uncurry(match))
              .take(1)
              .extract()
              .length > 0;
      default:
        return s === p
            && match(ps.join(''), ss.join(''));
    }
  }
  
  function optimize(pattern: string): string {
    const pat = pattern.replace(/\*(\?+)\*?/g, '$1*');
    return pat === pattern
      ? pat
      : optimize(pat);
  }
}
開發者ID:falsandtru,項目名稱:pjax-api,代碼行數:46,代碼來源:router.ts

示例2: URL

 .bind(xhr => {
   const url = new URL(standardize(xhr.responseURL));
   switch (true) {
     case !xhr.responseURL:
       return Left(new Error(`Failed to get the response URL.`));
     case url.origin !== new URL(window.location.origin).origin:
       return Left(new Error(`Redirected to another origin.`));
     case !/2..|304/.test(`${xhr.status}`):
       return Left(new Error(`Failed to validate the status of response.`));
     case !xhr.responseXML:
       return method === 'GET' && xhr.status === 304 && caches.has(url.path)
         ? Right(caches.get(url.path)!.xhr)
         : Left(new Error(`Failed to get the response body.`));
     case !match(xhr.getResponseHeader('Content-Type'), 'text/html'):
       return Left(new Error(`Failed to validate the content type of response.`));
     default:
       return Right(xhr);
   }
 });
開發者ID:falsandtru,項目名稱:pjax-api,代碼行數:19,代碼來源:xhr.ts

示例3: xhr

export function xhr(
  method: RouterEventMethod,
  displayURL: URL<StandardURL>,
  headers: Headers,
  body: FormData | null,
  timeout: number,
  rewrite: (path: URL.Path<StandardURL>) => string,
  cache: (path: string, headers: Headers) => string,
  cancellation: Cancellee<Error>
): AtomicPromise<Either<Error, FetchResponse>> {
  headers = new Headers(headers);
  void headers.set('Accept', headers.get('Accept') || 'text/html');
  const requestURL = new URL(standardize(rewrite(displayURL.path)));
  if (method === 'GET' && caches.has(requestURL.path) && Date.now() > caches.get(requestURL.path)!.expiry) {
    void headers.set('If-None-Match', headers.get('If-None-Match') || caches.get(requestURL.path)!.etag);
  }
  const key = method === 'GET'
    ? cache(requestURL.path, headers) || undefined
    : undefined;
  return new AtomicPromise<Either<Error, FetchResponse>>(resolve => {
    if (key && memory.has(key)) return resolve(Right(memory.get(key)!(displayURL, requestURL)));
    const xhr = new XMLHttpRequest();
    void xhr.open(method, requestURL.path, true);
    for (const [name, value] of headers) {
      void xhr.setRequestHeader(name, value);
    }

    xhr.responseType = 'document';
    xhr.timeout = timeout;
    void xhr.send(body);

    void xhr.addEventListener("abort", () =>
      void resolve(Left(new Error(`Failed to request a page by abort.`))));

    void xhr.addEventListener("error", () =>
      void resolve(Left(new Error(`Failed to request a page by error.`))));

    void xhr.addEventListener("timeout", () =>
      void resolve(Left(new Error(`Failed to request a page by timeout.`))));

    void xhr.addEventListener("load", () =>
      void verify(xhr, method)
        .fmap(xhr => {
          const responseURL: URL<StandardURL> = new URL(standardize(xhr.responseURL));
          assert(responseURL.origin === new URL(window.location.origin).origin);
          if (method === 'GET') {
            const cc = new Map<string, string>(
              xhr.getResponseHeader('Cache-Control')
                ? xhr.getResponseHeader('Cache-Control')!.trim().split(/\s*,\s*/)
                    .filter(v => v.length > 0)
                    .map(v => v.split('=').concat('') as [string, string])
                : []);
            for (const path of new Set([requestURL.path, responseURL.path])) {
              if (xhr.getResponseHeader('ETag') && !cc.has('no-store')) {
                void caches.set(path, {
                  etag: xhr.getResponseHeader('ETag')!,
                  expiry: cc.has('max-age') && !cc.has('no-cache')
                    ? Date.now() + +cc.get('max-age')! * 1000 || 0
                    : 0,
                  xhr,
                });
              }
              else {
                void caches.delete(path);
              }
            }
          }
          return (overriddenDisplayURL: URL<StandardURL>, overriddenRequestURL: URL<StandardURL>) =>
            new FetchResponse(
              responseURL.path === overriddenRequestURL.path
                ? overriddenDisplayURL
                : overriddenRequestURL.path === requestURL.path || !key
                    ? responseURL
                    : overriddenDisplayURL,
              xhr);
        })
        .fmap(f => {
          if (key) {
            void memory.set(key, f);
          }
          return f(displayURL, requestURL);
        })
        .extract(
          err => void resolve(Left(err)),
          res => void resolve(Right(res))));

    void cancellation.register(() => void xhr.abort());
  });
}
開發者ID:falsandtru,項目名稱:pjax-api,代碼行數:89,代碼來源:xhr.ts


注:本文中的spica/cache.Cache.get方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。