Step 3: Reading data
We've got the user's WebID and we know that it points to a Document; it's time we actually read some data from that Document!
We'll be using Tripledoc, which was designed specifically for this purpose. Other libraries exist, such as ldflex, rdf-ext and rdflib; Tripledoc intentionally has a more limited scope, aimed to aid "thinking in Solid". If at some point in the future you want to start combining many different data sources, you might want to consider investigating these alternative libraries.
We'll try to get the user's name as follows:
- Fetch the Document living at their WebID.
- From that Document, read the Subject representing the current user's profile.
- Get the
foaf:name
of that Subject, if set.
In code, that looks like this:
import { fetchDocument } from 'tripledoc';
async function getName(webId) {
/* 1. Fetch the Document at `webId`: */
const webIdDoc = await fetchDocument(webId);
/* 2. Read the Subject representing the current user's profile: */
const profile = webIdDoc.getSubject(webId);
/* 3. Get their foaf:name: */
return profile.getString('http://xmlns.com/foaf/0.1/name')
}
Tip: you can avoid typing the full 'http://xmlns.com/foaf/0.1/name' every time using the library rdf-namespaces. It exports strings for the URLs of the terms in common Vocabularies, turning the above into:
import { fetchDocument } from 'tripledoc';
import { foaf } from 'rdf-namespaces';
async function getName(webId) {
/* 1. Fetch the Document at `webId`: */
const webIdDoc = await fetchDocument(webId);
/* 2. Read the Subject representing the current user's profile: */
const profile = webIdDoc.getSubject(webId);
/* 3. Get their foaf:name: */
return profile.getString(foaf.name)
}
Two things to note here. First, we call getString
to indicate that we are looking for an actual
value (i.e. a Literal), rather than a URL. (Likewise, we could use getInteger
or getDecimal
if we expected a number instead.) However, the value could also have been a URL pointing to a different
Subject, in which case we could in turn fetch that Document. If that was what we expected, we
could have used the method getRef
instead.
The second thing to consider is that we cannot make any assumptions about what data is, or is not,
present in the user's Pod. Thus, profile.getString(foaf.name)
might also return null
. This
could happen if the Document does not include the user's name, if the name is stored differently
(e.g. using foaf:firstName
and foaf:familyName
), or the value of foaf:name
is not a literal string.
Now that we're able to read data from the user's WebID, let's find out how we can read arbitrary other data.