2016-10-01 60 views
2

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

我该如何做到这一点?我已经浏览了官方Docs,但没有提及如何将api响应数据传递给indexedDB。

回答

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); 
      }); 
     }); 

然后,您可以从索引资料检索它在后续请求

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); 
    }); 
    })); 
+0

我在与存储图像的特定问题,例如https://travis-ci.org/noahehall/udacity-trainschedule.svg?branch=master – neh