javascriptsolid

How can I add a new friend to a Solid Inrupt pod using Javascript (without Node.js)


I want to add a new friend directly using JavaScript from a UI. The main thing is that in my Solid Inrupt pod I have a property called knows. I tried to use this code but doesn't work:

//Function that adds a new friend to the user's pod
async function addNewFriend(webId, session, friendWebId) {
    // Get the Solid dataset of the profile
    const profileDataset = await solid.getSolidDataset(webId);

    const thing = solid.getThing(profileDataset, webId);

    // Get all the Things (resources) in the dataset that have the "knows" property
    solid.addIri(thing, FOAF.knows, friendWebId);

    solid.setThing(profileDataset, thing);

    const updatedDataset = await solid.saveSolidDatasetAt(webId, profileDataset, {
        fetch: session.fetch,
    });

    console.log("works!");
}

In a solid pod in the property knows you have something like this:

foaf:knows c0:me, c1:me, c:me;

that refers to:

@prefix c: https://uo281997.inrupt.net/profile/card#.

@prefix c0: https://arias.inrupt.net/profile/card#.

@prefix c1: https://uo277938.inrupt.net/profile/card#.

So i don't really know how to update the dataset of the profile to link new webId of a new Friend.


Solution

  • I'm assuming you're using @inrupt/solid-client. One thing that's important to know is that its functions do not mutate the data; instead, if returns new objects with updated data.

    So when you call e.g. addIri and setThing, you'll have to use the return values. For example:

    //Function that adds a new friend to the user's profile
    async function addNewFriend(webId, session, friendWebId) {
        // Get the Solid dataset of the profile
        const profileDataset = await solid.getSolidDataset(webId);
    
        const thing = solid.getThing(profileDataset, webId);
    
        const updatedThing = solid.addIri(thing, FOAF.knows, friendWebId);
    
        const updatedProfileDataset = solid.setThing(profileDataset, updatedThing);
    
        const storedProfileDataset = await solid.saveSolidDatasetAt(webId, updatedProfileDataset, {
            fetch: session.fetch,
        });
    }
    

    Also note that if the WebID is on pod.inrupt.com, Inrupt prevents your app from writing to the WebID. The above should work with e.g. https://solidcommunity.net or https://solidweb.me Pods, though.