Congratulations 🎉🎆!!
If you are here it means you have become a hypercore padawan. It's time to increase your P2P knowledge and follow the road to be a great Jedi.
We just saw that hypercore gives us a distributed log that we can work with. 🆒 But there are situations when that is not enough. Luckily for us, there are more libs written on top of hypercore and one of those is here to help, meet hyperdb ⭐
Hyperdb offers a key-value distributed over a set of hypercores database. 🆒
One of the most important features is that it give us the ability to have multiple-writers
. This takes Dat to the next level, where multiple users, once authorized, are able to modify a Dat resource (i.e, we have multiple owners.)
In this workshop we are learning how to use Dat to create a P2P web app. More specifically, our goal here is to build a P2P chat app together and the codename will be Olaf 😺.
So, to build our chat app we are going to use all the things that we have learned. In this module, we are about to introduce a fundamental part, the core of our chat, and it has a codename too: Saga 😻.
We are going to start using hyperdb to build saga.
Ok, so first let's define a simple API that permits multiple users to write messages over a distributed hyperdb.
Let's focus on a list of possible requirements our chat can have:
- We should be able to write messages.
- We should be able to read messages in real-time.
- We should be able to detect when an user connects and disconnects from a channel (room).
Cool, let's start writing this new API, saga. 😻
- Add a constructor to the class
Saga
that receives astorage
, akey
and ausername
. - With the
storage
and thekey
, create an instance of hyperdb using json as the valueEncoding. Saga
instance should allow us to access:
- the instance of hyperdb under the prop:
db
- the username, under the prop:
username
- a users Map, initially empty, under the prop:
users
. - a messages
Map
(initially empty):messages
. - a timestamp with the current datetime:
timestamp
hyperdb
offers an API similar to hypercore. 😉- About
Map
usage:
- a map can have objects for keys 🆒
- constructor:
new Map([iterable])
- important methods:
size()
, for getting the size.set(key, value)
, for add a new key with value.has(key)
, to know if key exists on map.keys()
, to get all the keys (array) of the map.
- Hint: it is 🆒 to use
for...of
to iterate over the map.
$ npm test ./05