How to keep a temporary filesystem

There’s no option yet in webnative to keep a temporary filesystem around for “a soon to be” user. So in the meantime app developers can manage that on their own in the following way.

Written for webnative version 0.24.x

Create the filesystem

const permissions = { fs: { private: [ webnative.path.root() ], public: [ webnative.path.root() ] }}
const fs = await webnative.fs.empty({ localOnly: true, permissions })

// Add some content
const ingredientsPath = webnative.path.file("private", "Databank", "Food", "Ingredients.json")
await fs.write(ingredientsPath, "[]")

// Get the content identifier
const cid = await fs.root.put()

The only thing to do now is to keep that CID around somewhere locally, so next time you can …

Load the filesystem

const fs = await webnative.fs.fromCID(cid, { localOnly: true, permissions })

await fs.read(ingredientsPath)
// []

Save the filesystem

Originally the publish method sends your data root (ie. the root CID) to the fission servers. We’ll need to override the publish method to do what we want. Here we take that root CID and store in localStorage instead.

fs.publish = async function() {
  localStorage.setItem(TMP_KEY, await this.root.put())
}

Copy from temporary to other filesystem

If at some point the user wants to login with their account, we’ll need to copy over the temporary data. We’ll do this on a successful authentication (the AuthSucceeded scenario). At that point we’ll detect if the involved files already exist on the user’s filesystem or not. If not, then we copy over the files.

await usersFs.write(
  ingredientsPath,
  await temporaryFs.cat(ingredientsPath)
)

(I haven’t actually tested this code yet, but that’s idea)

Notes

You will not be able to load this filesystem on another browser or device. The webnative.fs.empty function generates an AES key for you and stores this locally. It needs this AES key to be able to read the files of the /private filesystem.

3 Likes

Added how to save the filesystem and how to copy over files. Slowly figuring this out here nourish/index.js at b7636d2011d51f0476ffbf379ddee22bce32c321 · icidasset/nourish · GitHub

1 Like

Awesome, may be trying this out soon on a project!

One question. The temporary filesystem is stored in localStorage in this implementation. Are there restrictions about the types of content you could store temporarily? Because it’s localStorage, only strings or some raw representations?

1 Like

We’re only storing the CID in localStorage, content storage works as normal (js-ipfs via iframe + indexedDB).

Ah, I see, that makes sense. Thanks. :pray: