Skip to content
This repository has been archived by the owner on Nov 26, 2022. It is now read-only.

Commit

Permalink
Allow adding Yos.
Browse files Browse the repository at this point in the history
  • Loading branch information
RubenVerborgh committed Apr 24, 2018
1 parent 2721d8d commit 3e62258
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
14 changes: 13 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ <h2>Send a Yo</h2>
<input id="recipient" />
</p>
<p>
<input type="submit" id="send" value="Send" />
<input type="button" id="send" value="Send" />
</p>
</form>
</main>
Expand All @@ -59,6 +59,18 @@ <h2>Send a Yo</h2>
elements.from.innerText = await from;
elements.to.innerText = await to;
}

// Add a Yo on click
elements.send.addEventListener('click', async () => {
const from = 'https://ruben.verborgh.org/profile/#me';
const to = elements.recipient.value;
try {
await source.addYo({ from, to });
}
catch (error) {
alert(`Could not send Yo: ${error.message}`);
}
});
</script>
</body>
</html>
27 changes: 27 additions & 0 deletions scripts/YoSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,25 @@ class YoSource {
return yos[Math.floor(Math.random() * yos.length)];
}

// Adds a Yo to the source
async addYo({ from, to }) {
// Create the SPARQL UPDATE query
const query = `
INSERT DATA {
[] <${AS}actor> <${this._escape(from)}>;
<${AS}to> <${this._escape(to)}>;
<${AS}summary> "Yo"@en.
}`
// Send a PATCH request to update the source
const response = await this._fetch(this._source, {
method: 'PATCH',
headers: { 'Content-Type': 'application/sparql-update' },
body: query,
credentials: 'include',
});
return response.status === 200;
}

// Obtains a label for the given entity
async _getLabel(entity) {
// Try dereferencing the entity to obtain its label
Expand All @@ -84,4 +103,12 @@ class YoSource {
return entity.value;
}
}

// Escapes the IRI for use in a SPARQL query
_escape (iri) {
// More of a sanity check, really
if (!iri || !/^\w+:[^<> ]+$/.test(iri))
throw new Error(`Invalid IRI: ${iri}`);
return iri;
}
}

0 comments on commit 3e62258

Please sign in to comment.