在IndexedDB中存储api响应

时间:2016-10-01 20:06:55

标签: indexeddb

我正在建立一个我需要离线存储数据的网络应用。为此,我使用了indexedDb。我想将从API接收的响应存储到indexedDB中,然后将该数据传递到Web应用程序中。

我如何实现同样的目标?我已经阅读了官方文档,但没有提到如何将api响应数据传递给indexedDB。

1 个答案:

答案 0 :(得分:0)

我正在将响应转换为blob,然后将blob存储在indexeddb中。查看整页here

return fetch(new Request(prefetchThisUrl, { mode: 'no-cors' }))
      .then((resp) => {
        resp.blob()
          .then((blob) => {
            console.log(`blob is: ${blob.size}, ${blob.type}`);

            return db.set(prefetchThisUrl, blob);
          });
      });

然后,您可以在后续请求中从indexeddb检索它

    db.get(event.request.url).then((blobFound) => {
        if (!blobFound) {
          console.error(`error in retrieving from db: ${blobFound}`);

          return fetch(event.request.clone())
            .then((response) => {
              // only cache valid responses
              if (!response) {
                console.error(`received invalid response from fetch: ${responseTwo}`);

                return resolve(response);
              }

              // insert response body in db
              response.clone().blob().then(
                (blob) => {
                  console.info(`updating cache with: ${JSON.stringify(event.request.clone().url)}, then returning`);
                  db.set(
                    event.request.url,
                    blob
                  ).then(
                    (suc2) => console.log(`success in setting: ${suc2}`),
                    (err2) => console.error(`error in setting: ${err2}`)
                  );
                }
              );

              return resolve(response);
            });
        }

        const contentType = consts.getBlobType(blobFound, event.request.url);
        console.log('responding from cache', event.request.url, contentType);
        // on this page https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
        const myHeaders = new Headers({
          "Content-Length": String(blobFound.size),
          "Content-Type": contentType,
          "X-Custom-Header": "ProcessThisImmediately",
        });

        const init = {
          'content-type': 'text/html; charset=utf-8',
          'headers': myHeaders,
          'status' : 200,
          'statusText' : 'OKS',
        };
        const response = new Response(blobFound, init);

        return resolve(response);
    });
  }));