Let's say you're using Indexed DB for the offline data store for a catalog. One of the object stores contains product images. Wouldn't it be great if you could just have something like this in your catalog page?
<img src="indexeddb/database/store/id">
You can do this with Service Workers without browsers having to
implement it! All you need to do is carve out the URL namespace
intercepted by the fetch
handler in your service worker and decide
how to map URLs to database queries.
This example uses the imaginary host indexeddb.test
to provide URLs
of the form:
http://indexeddb.test/$DATABASE/$STORE?key=$KEY
http://indexeddb.test/$DATABASE/$STORE?key=$KEY&path=$PATH
http://indexeddb.test/$DATABASE/$STORE/$INDEX?key=$KEY
http://indexeddb.test/$DATABASE/$STORE/$INDEX?key=$KEY&path=$PATH
The path
query parameter is optional. If used, it is evaluated as
key path against the record returned by the database, allowing only
part of the record to be served up (e.g. an image stored as a Blob as
part of a record).
The example here sets up a database named resources
which contains
an object store named records
with an index by_name
. The following
URL is used to retrieve records from that index, and respond with the
image
property of the record.
<img src="http://indexeddb.test/resources/records/by_name?key=alex&path=image">
Indexed DB keys are typed, e.g. they can be strings, numbers, etc. The
key "1" (string) and the key 1 (number) are distinct, so if you're
using numeric keys you'll need to convert URL substrings to number
e.g. k = Number(s)
before querying the database. If your use case
requires both numeric and string keys in same application, one
approach would be to use JSON.parse()
on the key values, so string
keys would look like /db/store?key="foo"
while numeric keys would
simply be /db/store?key=123
Using /
as a delimiter puts restrictions on the names for
databases/stores/indexes that aren't present in the spec. So be sure
to come up with a scheme that will support your naming conventions.
Would be nice to see a module for that.