Tuesday, November 27, 2012

PetStore web App using Knockout and IndexedDB

         PetStore is a web application (SPA? you decide), which shows how we can store large amounts of data at clientside (browser) and also works in offline. Presently it doesn't relies on web server to process any logic or storage. It is self-sufficient and works pure clientside (except for first time serve, and when offline & web data are deleted).

Why IndexedDB?
         The older "Web Database api" (aka WebSQL) became obsolete and replaced by indexedDB.  IndexedDB stores large amounts of data in JSON format at clientside. For data storage limits check the site references below (it could be unlimited). You can also find my old post on - Web Database api.
         Browsers supporting IndexedDB provided Async api to communicate with it. Because of lack of support, Sync communication approach may be omitted in future from W3C specification.

       Knockoutjs is a javascript MV* framework, provides two-way data bindig using MVVM pattern. In this application, the temporary data and state is maintained by knockout until data gets flushed into DB, during that time you can do all CRUD operations.

Features of PetStore:

  • CRUD operations using knockout.
  • uses browser built-in validations.
  • stores data in IndexedDB.
  • works in offline.
      The PetStore contains only 3 screens: Add/Edit, Unsaved, Saved Records. Check the screenshots below for each screen. With this application we can do: 
  • Add or Edit Pet details.
  • Check the unsaved records to decide for edit or delete and 
  • Finally save all records into IndexedDB and show them (even after revisit and offline).

Initial screen - Add a Pet
Unsaved Records

Edit and update Pet details

Saved records from IndexedDB

         Download the Zip file (check link below) and try running the application for yourself. For web server i have used NodeJS (httpster), but you can use any of your preferred web server. This Zip file contains the code files, wherein the functionality specific code is segregated into different files (like IndexedDB.js, ko_VM.js), which makes easy to understand and debug code. Out of them, its worth mentioning IndexedDB.js file, it provides the api to communicate with browser's storage - IndexedDB. (following standards: it works with latest version of browsers. Check the supported versions below). To better make use of this js file, i also provided another html "IndexedDB_Test.html", so that you can understand its working. The limitations of this api is: Delete and Update operations are not implemented, but you can: OpenDB, Read and Write.

Supported browsers: 
Tested on Chrome 23 and Firefox 16.02. IE10 may also support.


Download Link:

IndexedDB.js file has been updated, check the new post.