### Install @ldo/connected-solid Source: https://ldo.js.org/latest/guides/solid Installs the @ldo/connected-solid library using npm. This is the first step to integrating LDO with Solid Pods. ```bash npm install @ldo/connected-solid ``` -------------------------------- ### Install @ldo/connected-nextgraph and nextgraph Source: https://ldo.js.org/latest/guides/nextgraph Installs the necessary libraries for integrating LDO with NextGraph using npm. ```bash npm install nextgraph @ldo/connected-nextgraph ``` -------------------------------- ### Install LDO Dependencies (NPM) Source: https://ldo.js.org/latest/api/cli Installs the necessary LDO core and CLI dependencies using npm. This is part of the manual setup process. ```bash npm install @ldo/ldo npm install @ldo/cli --save-dev ``` -------------------------------- ### Install LDO Solid/React Library Source: https://ldo.js.org/latest/guides/solid_react Installs the '@ldo/solid-react' package, which provides hooks and components for integrating LDO with Solid and React applications. This is a prerequisite for using LDO's data manipulation features. ```bash npm install @ldo/solid-react ``` -------------------------------- ### SolidResource createAndOverwrite Example Source: https://ldo.js.org/latest/api/connected-solid/classes/SolidResource Example demonstrating how to use the `createAndOverwrite` method to create a Solid resource, handling the result to check for errors. ```typescript const result = await resource.createAndOverwrite(); if (!result.isError) { // Do something } ``` -------------------------------- ### SolidResource createIfAbsent Example Source: https://ldo.js.org/latest/api/connected-solid/classes/SolidResource Example showcasing the usage of `createIfAbsent` to create a resource only if it does not already exist, with subsequent error checking. ```typescript const result = await leaf.createIfAbsent(); if (!result.isError) { // Do something } ``` -------------------------------- ### Example: Initiating and Committing a LDO Transaction Source: https://ldo.js.org/latest/api/connected/classes/ConnectedLdoTransactionDataset Demonstrates how to create a ConnectedLdoDataset, read a resource, start a transaction, modify a profile, and commit the changes. This example requires `@ldo/connected`, `connected-solid`, and a defined `ProfileShapeType`. It shows error handling for the commit operation. ```typescript import { createConnectedLdoDataset, } from "@ldo/connected"; import { ProfileShapeType } from "./.ldo/profile.shapeTypes.ts"; import { solidConnectedPlugin } from "connected-solid"; // ... const connectedLdoDataset = createConnectedLdoDataset([ solidConnectedPlugin, ]); const profileDocument = connectedLdoDataset .getResource("https://example.com/profile"); await profileDocument.read(); const transaction = connectedLdoDataset.startTransaction(); const profile = transaction .using(ProfileShapeType) .fromSubject("https://example.com/profile#me"); profile.name = "Some Name"; const result = await transaction.commitToRemote(); if (result.isError) { // handle error } ``` -------------------------------- ### Initialize LDO Project CLI Source: https://ldo.js.org/latest/guides/solid_react Initializes a new LDO project using the command-line interface. This command installs necessary libraries and generates initial project folders (.shapes and .ldo) for shape definitions and generated code. ```bash npx @ldo/cli init ``` -------------------------------- ### Manual Installation of LDO Libraries Source: https://ldo.js.org/latest/api/solid-react Allows for manual installation of the core @ldo/ldo, @ldo/solid, and @ldo/solid-react libraries if ShapeTypes have already been generated. This is an alternative to the standard installation process. ```bash npm i @ldo/ldo @ldo/solid @ldo/solid-react ``` -------------------------------- ### Initialize LDO using global installation Source: https://ldo.js.org/latest/api/cli/init Initializes LDO using the `ldo` command after global installation of `@ldo/cli`. This method is convenient if the CLI is frequently used. ```bash npm i -g @ldo/cli cd my_project/ ldo init ``` -------------------------------- ### Example of Structured Post Data on Solid Pod Source: https://ldo.js.org/latest/guides/solid_react This is an example of the Turtle (TTL) format representing a social media post stored on a Solid Pod. It shows how the `articleBody`, `image`, `a` (type), and `uploadDate` properties are represented as RDF triples. ```turtle "Hello this is a post"; ; a ; "2023-09-26T19:01:17.263Z"^^. ``` -------------------------------- ### Install @ldo/solid and @ldo/solid-react Source: https://ldo.js.org/latest/api/solid-react Installs the necessary @ldo/solid and @ldo/solid-react libraries for integrating Solid with React applications. This is typically done after initializing the project with @ldo/cli. ```bash cd my_project/ npx run @ldo/cli init npm i @ldo/solid @ldo/solid-react ``` -------------------------------- ### Container Helper Functions Source: https://ldo.js.org/latest/guides/solid Provides helper functions for managing containers within a Solid Pod, such as getting a child resource URI or creating a child resource. ```javascript const container = dataset.getResource("https://pod.example.com/posts/"); const childContainer = container.child("newPost.ttl"); // Quick child URI // Shorthand for creating a file const childResult = container.createChildAndOverwrite("newPost.ttl"); if (!containerResult.isError) { const childResource = childResult.resource; } ``` -------------------------------- ### Create and Subscribe to a Link Query in TypeScript Source: https://ldo.js.org/latest/api/connected/classes/ResourceLinkQuery This example demonstrates how to create a link query using `ldoDataset.usingType` and `startLinkQuery`. It specifies the types, starting resource, and the desired query input, including nested properties. The `subscribe()` method is then called to enable automatic updates to the dataset when changes occur within the queried link. ```typescript import { ProfileShapeType } from "./.ldo/Profile.shapeType.ts"; // Create a link query const linkQuery = ldoDataset .usingType(ProfileShapeType) .startLinkQuery( "http://example.com/profile/card", "http://example.com/profile/card#me", { name: true, knows: { name: true, }, }, } ); // Susbscribe to this link query, automaticically updating the dataset when // something from the link query is changed. await linkQuery.subscribe(); ``` -------------------------------- ### Setup ConnectedLdoDataset with @ldo/connected-nextgraph Source: https://ldo.js.org/latest/guides/nextgraph Initializes a `ConnectedLdoDataset` which manages RDF data for NextGraph resources. This is the first step in setting up the integration. ```javascript import { createNextGraphLdoDataset } from "@ldo/connected-nextgraph"; // Create the dataset const ldoDataset = createNextGraphLdoDataset(); ``` -------------------------------- ### Connect to NextGraph Wallet Session with nextgraph Source: https://ldo.js.org/latest/guides/nextgraph Demonstrates how to connect to a NextGraph wallet session by reading a wallet file, opening it with mnemonic words and pins, and starting an in-memory session. This is required before creating or accessing NextGraph resources. ```javascript import ng from "nextgraph"; // ... // load the wallet file const wallet = await ng.wallet_read_file(binary_buffer); // Open your nextgraph wallet const mnemonic = ["word0",...]; // the 12 words of your mnemonic const openedWallet = await ng.wallet_open_with_mnemonic_words( wallet, mnemonic, [pin0,pin1,pin2,pin3] ); // Start a session const session = await ng.session_in_memory_start( openedWallet.V0.wallet_id, openedWallet.V0.personal_site ); ``` -------------------------------- ### Create Resource if Absent on Solid Pod Source: https://ldo.js.org/latest/guides/solid Creates a resource on a Solid Pod only if it does not already exist. `createIfAbsent` is for structured data, and `uploadIfAbsent` is for binary data. ```javascript const createResult = await resource.createIfAbsent(); if (createResult.isError) { // Handle Error } const uploadResult = await resource.uploadIfAbsent(blob, mimeType); if (createResult.isError) { // Handle Error } ``` -------------------------------- ### Wrap App with BrowserSolidLdoProvider in React Source: https://ldo.js.org/latest/api/solid-react/BrowserSolidLdoProvider This code snippet demonstrates how to use the BrowserSolidLdoProvider component to wrap the main application component. This setup is essential for initializing the SolidLdoProvider and integrating Solid login functionalities from @inrupt/solid-client-authn-browser within a React application running in a web browser. The provider expects to wrap the application's children, such as the Login component in this example. ```jsx import type { FunctionComponent } from "react"; import React from "react"; import { BrowserSolidLdoProvider } from "@ldo/solid-react"; // The base component for the app const App: FunctionComponent = () => { return ( /* The application should be surrounded with the BrowserSolidLdoProvider this will set up all the underlying infrastructure for the application */ ); }; ``` -------------------------------- ### Set Language Preferences and Use JSON-LD Dataset Proxy (TypeScript) Source: https://ldo.js.org/latest/guides/advanced_data_manipulation This example demonstrates how to create a JSON-LD Dataset Proxy, set language preferences using `setLanguagePreferences`, and retrieve data. It shows how language preferences affect read operations (e.g., `hospitalInfo.label` logs '병원' based on 'es', 'ko', '@none' preference) and write operations (adding a Spanish description). ```typescript // Create a dataset loaded with initial data const dataset = await serializedToDataset(initialData); // Make a JSONLD Dataset Proxy const hospitalInfo = jsonldDatasetProxy(dataset, PersonContext) .setLanguagePreferences("es", "ko", "@none") .fromSubject(namedNode("http://example.com/Hospital")); console.log(hospitalInfo.label); // Logs "병원" console.log(hospitalInfo.description.size); // Logs "2" for the 2 korean entries console.log(hospitalInfo.description.toArray()[0]); // Logs "환자를 치료하다" console.log(hospitalInfo.description.toArray()[1]); // Logs "의사 있음" // Adds a string to the description in spanish, because spanish if the first // language in the language preference hospitalInfo.description.add("Cura a las pacientes"); // Now that a spanish entry exists, JSON-LD dataset proxy focuses on that console.log(hospitalInfo.description.size); // Logs "1" for the 1 spanish entry console.log(hospitalInfo.description.toArray()[0]); // Logs "Cura a las pacientes" ``` -------------------------------- ### Initialize Connected Solid LdoDataset with Authentication Source: https://ldo.js.org/latest/guides/solid Initializes a Solid LDO dataset and sets the authenticated fetch object. It requires an authentication library like @inrupt/solid-client-authn-browser. ```javascript import { createSolidLdoDataset } from "@ldo/connected-solid"; // Use inrupt's auth library or any other Solid auth library for example import { fetch } from "@inrupt/solid-client-authn-browser"; // Create an LdoDataset const dataset = createSolidLdoDataset(); // Set the authenticated fetch dataset.setContext("solid", { fetch: fetch }); ``` -------------------------------- ### Get and Create Main Application Container in Solid React (TypeScript) Source: https://ldo.js.org/latest/guides/solid_react This snippet demonstrates how to obtain the main application container URI from a user's WebId and create it if it doesn't exist. It utilizes the `useLdo` and `useSolidAuth` hooks from `@ldo/solid-react` to access Solid functionalities. The process involves fetching the WebId resource, finding its root container, identifying a specific child container for the application, and then creating that container if absent. This ensures a dedicated space for application data. ```typescript import { useLdo, useSolidAuth } from "@ldo/solid-react"; import { ContainerUri } from "@ldo/solid"; import { FunctionComponent, useEffect, useState } from "react"; export const Blog: FunctionComponent = () => { const { session } = useSolidAuth(); const { getResource } = useLdo(); const [mainContainerUri, setMainContainerUri] = useState(); useEffect(() => { if (session.webId) { // Get the WebId resource const webIdResource = getResource(session.webId); // Get the root container associated with that WebId webIdResource.getRootContainer().then((rootContainerResult) => { // Check if there is an error if (rootContainerResult.isError) return; // Get a child of the root resource called "my-solid-app/" const mainContainer = rootContainerResult.child("my-solid-app/"); setMainContainerUri(mainContainer.uri); // Create the main container if it doesn't exist yet mainContainer.createIfAbsent(); }); } }, [getResource, session.webId]); if (!session.isLoggedIn) return

No blog available. Log in first.

; // Component rendering logic would go here return (
{/* Render blog content */}
); }; ``` -------------------------------- ### Create or Overwrite Resource on Solid Pod Source: https://ldo.js.org/latest/guides/solid Creates a new resource or overwrites an existing one on a Solid Pod. `createAndOverwrite` is for structured data, while `uploadAndOverwrite` is for binary data. ```javascript const createResult = await resource.createAndOverwrite(); if (createResult.isError) { // Handle Error } const uploadResult = await resource.uploadAndOverwrite(blob, mimeType); if (uploadResult.isError) { // Handle Error } ``` -------------------------------- ### Create Shapes Directory (CLI) Source: https://ldo.js.org/latest/api/cli Creates a directory named 'shapes' to store ShEx shape files, a step in the manual setup process for LDO. ```bash mkdir shapes ``` -------------------------------- ### Setup and Data Reading with LDO.js Source: https://ldo.js.org/latest/api/connected Initializes a connected LDO dataset with Solid and NextGraph plugins, sets contexts for authenticated requests, and demonstrates reading data from remote Solid and NextGraph resources. It also shows how to handle potential errors during the read operation. ```typescript import { changeData, commitData, createConnectedLdoDataset } from "@ldo/connected"; import { solidConnectedPlugin } from "@ldo/connected-solid"; import { nextGraphConnectedPlugin } from "@ldo/connected-nextgraph"; // Shape Types import { FoafProfileShapeType } from "./.ldo/foafProfile.shapeTypes"; import { SocialMediaPostShapeType } from "./.ldo/socialMediaPost.shapeTypes"; // These are tools for Solid and NextGraph outside of the LDO ecosystem import { fetch, getDefaultSession } from "@inrupt/solid-client-authn-browser"; import ng from "nextgraph"; async function main() { /** * =========================================================================== * SETTING UP A CONNECTED LDO DATASTORE WITH 2 PLUGINS * =========================================================================== */ const connectedLdoDataset = createConnectedLdoDataset([ solidConncetedPlugin, nextGraphConnectedPlugin ]); // Set context to be able to make authenticated requests connectedLdoDataset.setContext("solid", { fetch }); const session = await ng.session_in_memory_start( openedWallet.V0.wallet_id, openedWallet.V0.personal_site ); connectedLdoDataset.setContext("nextGraph", { sessionId: session.sessionId }); /** * =========================================================================== * READING DATA FROM REMOTE * =========================================================================== */ // We can get a Solid resource by including a Solid-Compatible URL const solidResource = solidLdoDataset.getResource( "https://pod.example.com/profile.ttl" ); // Similarly, we can get a NextGraph resource by including a // NextGraph-Compatible URL const nextGraphResource = solidLdoDataset.getResource( "did:ng:o:W6GCQRfQkNTLtSS_2-QhKPJPkhEtLVh-B5lzpWMjGNEA:v:h8ViqyhCYMS2I6IKwPrY6UZi4ougUm1gpM4QnxlmNMQA" ); // Optionally, you can provide the name of the specific plugin you want to use const anotherSolidResource = solidLdoDataset.getResource("", "solid"); // This resource is currently unfetched console.log(solidResource.isUnfetched()); // Logs true console.log(nextGraphResource.isUnfetched()); // Logs true // So let's fetch it! Running the `read` command will make a request to get // the WebId. const solidReadResult = await solidResource.read(); const ngReadResult = await nextGraphREsource.read(); // @ldo/connected will never throw an error. Instead, it will return errors. // This design decision was made to force you to handle any errors. It may // seem a bit annoying at first, but it will result in more resiliant code. // You can easily follow intellisense tooltips to see what kinds of errors // each action can throw. if (solidReadResult.isError) { switch (solidReadResult.type) { case "serverError": console.error("The solid server had an error:", solidReadResult.message); return; case "noncompliantPodError": console.error("The Pod responded in a way not compliant with the spec"); return; default: console.error("Some other error was detected:", solidReadResult.message); } } // When fetching a data resource, read triples will automatically be added to // the solidLdoDataset. You can access them using Linked Data Objects. In // the following example we're using a Profile Linked Data Object that was // generated with the init step. const profile = connectedLdoDataset .usingType(FoafProfileShapeType) .fromSubject("https://pod.example.com/profile#me"); // Now you can read "profile" like any JSON. console.log(profile.name); /** * =========================================================================== * MODIFYING DATA * =========================================================================== */ // When we want to modify data the first step is to use the `changeData` // function. We pass in an object that we want to change (in this case, // "profile") as well an a list of any resources to which we want those // changes to be applied (in this case, just the webIdResource). This gives // us a new variable (conventionally named with a c for "changed") that we can // write changes to. const cProfile = changeData(profile, solidResource); // We can make changes just like it's regular JSON cProfile.name = "Captain Cool Dude"; // Committing data is as easy as running the "commitData" function. const commitResult = await commitData(cProfile); // Remember to check for and handle errors! We'll keep it short this time. if (commitResult.isError) throw commitResult; /** * =========================================================================== */ } ``` -------------------------------- ### Initialize LDO Project (CLI) Source: https://ldo.js.org/latest/api/cli Initializes a new LDO project by navigating to the project directory and running the 'init' command. ```bash cd my-typescript-project npx @ldo/cli init ``` -------------------------------- ### Get and Set LDO Data like TypeScript Objects - JavaScript/TypeScript Source: https://ldo.js.org/latest/guides/raw_rdf Linked Data Objects can be manipulated as if they were standard TypeScript objects. You can access properties directly and use methods like `set` to update values. The example demonstrates reading properties like `name`, `type`, and `knows`, and then updating `name` and adding a new entry to `knows`. ```javascript import { LinkedDataObject, set } from "@ldo/ldo"; import { FoafProfileFactory } from "./.ldo/foafProfile.ldoFactory.ts"; import { FoafProfile } from "./.ldo/foafProfile.typings"; aysnc function start() { const profile: FoafProfile = // Create LDO // Logs "Aang" console.log(profile.name); // Logs "Person" console.log(profile.type.toArray()[0]?.["@id"]); // Logs 1 console.log(profile.knows?.size); // Logs "Katara" console.log(profile.knows?.toArray()[0]?.name); profile.name = "Bonzu Pippinpaddleopsicopolis III" // Logs "Bonzu Pippinpaddleopsicopolis III" console.log(profile.name); profile.knows?.add({ type: set({ "@id": "Person" }), name: "Sokka" }); // Logs 2 console.log(profile.knows?.size); // Logs "Katara" and "Sokka" profile.knows?.forEach((person) => console.log(person.name)); } ``` -------------------------------- ### Create New Solid and NextGraph Resources Source: https://ldo.js.org/latest/api/connected Demonstrates creating new resources for both Solid Pods and NextGraph using the `createResource` method. This is a fundamental operation for adding new data stores. ```javascript const newSolidResource = await connectedLdoDataset.createResource("solid"); const newNgResource = await connectedLdoDataset.createResource("nextGraph"); ``` -------------------------------- ### Instantiate SolidLeaf Source: https://ldo.js.org/latest/api/connected-solid/classes/SolidLeaf Demonstrates how to create an instance of the SolidLeaf class. This involves providing the URI of the leaf and a SolidLdoDatasetContext. The context is crucial for establishing the connection to the Solid Pod and its associated plugins. ```javascript const leaf = solidLdoDataset .getResource("https://example.com/container/resource.ttl"); ``` -------------------------------- ### Get Resource from Solid Pod Source: https://ldo.js.org/latest/guides/solid Retrieves a resource (file or container) from a Solid Pod using its URI. The resource can be a SolidLeaf or SolidContainer. ```javascript const resource = dataset.getResource("https://pod.example.com/posts/myPost.ttl"); ``` -------------------------------- ### Create New Resources in Solid Pod using @ldo/solid Source: https://ldo.js.org/latest/api/connected-solid Illustrates the process of creating new resources, such as a container for social media posts, within a Solid Pod using @ldo/solid. It demonstrates how to find the root container of the Pod and then create a new child container if it doesn't already exist. Error handling for container creation is included. ```javascript async function createSolidResource(webIdResource) { const rootContainer = await webIdResource.getRootContainer(); if (rootContainer.isError) { console.error("Error getting root container:", rootContainer.message); return; } const createPostContainerResult = await rootContainer.createChildIfAbsent("social-posts/"); if (createPostContainerResult.isError) { console.error("Error creating social-posts container:", createPostContainerResult.message); return; } console.log("Social posts container created or already exists."); } ``` -------------------------------- ### Create Solid Resources and Data using Javascript Source: https://ldo.js.org/latest/api/connected-solid This snippet demonstrates how to create a Solid container, a data resource for a social media post, and a binary resource for an image. It then shows how to add data to the post resource, including a reference to the image, and commit the changes. Finally, it shows how to delete the container and its contents. ```javascript const postContainer = createPostContainerResult.resource; const postResourceResult = await postContainer.createChildAndOverwrite("post1.ttl"); if (postResourceResult.isError) throw postResourceResult; const postResource = postResourceResult.resource; const imageResourceResult = await postContainer.uploadChildAndOverwrite( "image1.svg", new Blob([``]), "image/svg+xml", ); if (imageResourceResult.isError) throw imageResourceResult; const imageResource = imageResourceResult.resource; const cPost = solidLdoDataset.createData( SocialMediaPostShapeType, postResource.uri, postResource, ); cPost.text = "Check out this bad svg:"; cPost.image = { "@id": imageResource.uri }; const newDataResult = await commitData(cPost); if (newDataResult.isError) throw newDataResult; const deleteResult = await postContainer.delete(); if (deleteResult.isError) throw deleteResult; ``` -------------------------------- ### Get Storage Container from WebID Source: https://ldo.js.org/latest/guides/solid Retrieves the storage containers associated with a given WebID using the connected-solid library. This is useful for discovering where a user's data is stored. ```javascript import { getStorageFromWebId } from "@ldo/connected-solid"; const result = await getStorageFromWebId(webIdUri, dataset); console.log(result.storageContainers); // array of root URIs ``` -------------------------------- ### Get Mime Type of SolidLeaf (JavaScript) Source: https://ldo.js.org/latest/api/connected-solid/classes/SolidLeaf Retrieves the MIME type of a SolidLeaf if it represents a binary resource. If the resource is not binary, it returns undefined. The example demonstrates logging the MIME type. ```javascript // Logs "text/txt" console.log(leaf.getMimeType()); ``` -------------------------------- ### Create Solid Resources at a Predefined Location Source: https://ldo.js.org/latest/api/connected Shows how to create Solid resources, such as posts, at a specific URI. It includes checking for the existence of a container and creating child resources, along with error handling. ```javascript const postContainer = connectedLdoDataset .getResource("https://pod.example.com/socialPosts/"); const createPostContainerResult = await solidSocialPostsContainer.createIfAbsent(); if (createPostContainerResult.isError) throw createPostContainerResult; const postResourceResult = await postContainer.createChildAndOverwrite("post1.ttl"); if (postResourceResult.isError) throw postResourceResult; const postResource = postResourceResult.resource; ``` -------------------------------- ### Update Data using SPARQL Patch Source: https://ldo.js.org/latest/guides/solid Updates structured data on a Solid Pod using SPARQL Patch. This involves starting a transaction, modifying data, and committing it to the remote server. ```javascript const transaction = dataset.startTransaction(); const profile = transaction .usingType(FoafShapeType) .write(resource) .fromSubject("https://example.com/profile#name"); profile.name = "John Doe"; const result = await transaction.commitToRemote(); ``` -------------------------------- ### Read Data from Solid Pod using @ldo/solid Source: https://ldo.js.org/latest/api/connected-solid Demonstrates how to initialize and use the @ldo/solid library to read data from a user's Solid Pod. It covers setting up the SolidLdoDataset, fetching a resource using its URI, and accessing the data as a typed Linked Data Object. Error handling for server and non-compliant Pod responses is included. ```javascript import { createSolidLdoDataset } from "@ldo/solid"; import { fetch, getDefaultSession } from "@inrupt/solid-client-authn-browser"; import { FoafProfileShapeType } from "./.ldo/foafProfile.shapeTypes"; async function readSolidData() { const webIdUri = getDefaultSession().info.webId; if (!webIdUri) throw new Error("User is not logged in"); const solidLdoDataset = createSolidLdoDataset(); solidLdoDataset.setContext({ fetch }); const webIdResource = solidLdoDataset.getResource(webIdUri); const readResult = await webIdResource.read(); if (readResult.isError) { console.error("Error fetching resource:", readResult.message); return; } const profile = solidLdoDataset .usingType(FoafProfileShapeType) .fromSubject(webIdUri); console.log(profile.name); } ``` -------------------------------- ### Get Blob Data from SolidLeaf (JavaScript) Source: https://ldo.js.org/latest/api/connected-solid/classes/SolidLeaf Retrieves the Blob content of a SolidLeaf if it represents a binary resource. If the resource is not binary, it returns undefined. The example shows how to log the string representation of the Blob. ```javascript // Logs "some text." console.log(leaf.getBlob()?.toString()); ``` -------------------------------- ### Upload Binary Resources to Solid Source: https://ldo.js.org/latest/api/connected Illustrates uploading binary resources, like images, to a Solid Pod. This involves specifying the file name, providing the binary data as a Blob, and defining the MIME type. ```javascript const imageResourceResult = await postContainer.uploadChildAndOverwrite( // name of the binary "image1.svg", // A blob for the binary new Blob([""]), // mime type of the binary "image/svg+xml", ); if (imageResourceResult.isError) throw imageResourceResult; const imageResource = imageResourceResult.resource; ``` -------------------------------- ### Get Parent Container of SolidLeaf (JavaScript) Source: https://ldo.js.org/latest/api/connected-solid/classes/SolidLeaf Fetches the parent container of a SolidLeaf resource by making a network request. It returns a Promise that resolves to the SolidContainer. The example shows how to access the URI of the parent container. ```javascript const leaf = solidLdoDataset .getResource("https://example.com/container/resource.ttl"); const leafParent = await leaf.getParentContainer(); if (!leafParent.isError) { // Logs "https://example.com/container/" console.log(leafParent.uri); } ``` -------------------------------- ### JavaScript: Delete Entire Object from LDO Dataset Source: https://ldo.js.org/latest/guides/advanced_data_manipulation This example illustrates how to delete all triples associated with an object by calling 'delete' on its '@id' property within the LDO dataset. It requires 'serializedToDataset' and 'jsonldDatasetProxy'. ```javascript const dataset = await serializedToDataset(` @prefix example: . @prefix foaf: . @prefix xsd: . example:Person1 foaf:name "Alice"^^xsd:string; foaf:bestFriend example:Person2. example:Person2 foaf:name "Bob"^^xsd:string; foaf:bestFriend example:Person1. `); const person = jsonldDatasetProxy( dataset, PersonContext ).fromSubject(namedNode("http://example.com/Person1")); delete person["@id"]; console.log(dataset.toString()); // "Bob" . ``` -------------------------------- ### Import and Initialize LdoDataset Source: https://ldo.js.org/latest/api/ldo/LdoBuilder Demonstrates how to import necessary components from the '@ldo/ldo' library and initialize an LdoDataset. It then shows how to use the dataset to create an LdoBuilder for a specific type, `FoafProfileShapeType`, and begin building an LDO from a subject. ```typescript import { LdoDataset, createLdoDatasetFactory } from "@ldo/ldo"; import { FoafProfileShapeType } from "./.ldo/foafProfile.shapeTypes"; const ldoDataset = createLdoDataset(); const ldoBuilder = ldoDataset.usingType(FoafProfileShapeType); const profile = ldoBuilder .write("https://example.com/someGraph") .fromSubject("https://example.com/profile#me"); ``` -------------------------------- ### Initialize LDO using NPX Source: https://ldo.js.org/latest/api/cli/init Initializes LDO in the current directory using NPX. This is the recommended way to run the command in an existing project's package.json folder. ```bash cd my_project/ npx run @ldo/cli init ``` -------------------------------- ### Get RDFJS Dataset from Linked Data Object (JavaScript) Source: https://ldo.js.org/latest/guides/raw_rdf Retrieves the underlying RDFJS dataset for a given Linked Data Object. Modifications to this dataset directly alter the Linked Data Object. It requires the `@ldo/ldo` package. ```javascript import { getDataset } from "@ldo/ldo" const dataset = getDataset(profile); ``` -------------------------------- ### Get Root Container using useRootContainer (React) Source: https://ldo.js.org/latest/api/solid-react/useRootContainer The `useRootContainer` hook fetches the root container of a Solid resource given its URI. It's a React hook that returns the container or undefined if it hasn't been fetched. Ensure the `@ldo/solid-react` library is installed. ```javascript import { useRootContainer } from "@ldo/solid-react"; import React, { FunctionComponent } from "react"; const Component: FunctionComponent = () => { const rootContainer = useRootContainer("https://example.com/profile"); return

Root Container: {rootContainer?.uri}

; }; ``` -------------------------------- ### createIfAbsent Source: https://ldo.js.org/latest/api/connected-solid/classes/SolidContainer Creates a container at the current URI if it does not already exist. ```APIDOC ## POST /websites/ldo_js/SolidContainer/createIfAbsent ### Description Creates a container at this URI if the container doesn't already exist. ### Method POST ### Endpoint /websites/ldo_js/SolidContainer/createIfAbsent ### Parameters (No parameters) ### Request Body (Not applicable) ### Request Example ```javascript const result = await container.createIfAbsent(); if (!result.isError) { // Do something } ``` ### Response #### Success Response (200) - **ContainerCreateIfAbsentResult** - The result of creating the container. ``` -------------------------------- ### Write Graph on JSON-LD Dataset Proxy Creation Source: https://ldo.js.org/latest/guides/advanced_data_manipulation Sets the graph to write to when creating a jsonld dataset proxy using the `write` method. This method accepts any number of graphs. The example demonstrates adding a name to a person within a specified named graph. ```javascript const person1 = jsonldDatasetProxy(dataset, PersonContext) .write(namedNode("http://example.com/ExampleGraph")) .fromSubject(namedNode("http://example.com/Person1")); person1.name.add("Jack"); console.log(dataset.toString()); // Logs: // "Jack" . ``` -------------------------------- ### Initialize React Project with TypeScript Source: https://ldo.js.org/latest/guides/solid_react Initializes a new React project using create-react-app with the TypeScript template. This command sets up the basic project structure and necessary configurations for a TypeScript-based React application. ```bash npx create-react-app my-solid-app --template typescript cd my-solid-app ``` -------------------------------- ### Get Root Container of SolidLeaf (JavaScript) Source: https://ldo.js.org/latest/api/connected-solid/classes/SolidLeaf Retrieves the root container for a given SolidLeaf resource. This method returns a Promise that resolves to either the SolidContainer, an error indicating a check failure, or an error for a missing root container. The example logs the URI of the root container if found. ```javascript const leaf = ldoSolidDataset .getResource("https://example.com/container/resource.ttl"); const rootContainer = await leaf.getRootContainer(); if (!rootContainer.isError) { // logs "https://example.com/" console.log(rootContainer.uri); } ``` -------------------------------- ### Define Language Preferences (Array Syntax) Source: https://ldo.js.org/latest/guides/advanced_data_manipulation This snippet shows examples of defining language preferences as ordered arrays. These arrays dictate the priority for reading and writing language-tagged literals. Special tags like '@none' (for literals without tags) and '@other' (for languages not explicitly listed) are supported. ```javascript // Read Spansih first, then Korean, then language strings with no language\n// New writes are in Spanish ["es", "ko", "@none"] // Read any language other than french, then french // New writes are in French ["@other", "fr"] ``` -------------------------------- ### Manipulate Linked Data Object with LDO JS Source: https://ldo.js.org/latest/guides/raw_rdf This example shows how to parse raw Turtle RDF into an LDO dataset, extract and manipulate a Linked Data Object (LDO), and then convert the modified LDO back into Turtle and SPARQL Update formats. It requires the `@ldo/ldo` package and generated shape types. ```javascript import { parseRdf, startTransaction, toSparqlUpdate, toTurtle, set, } from "@ldo/ldo"; import { FoafProfileShapeType } from "./.ldo/foafProfile.shapeTypes"; async function run() { const rawTurtle = " <#me> a ; \"Jane Doe\". "; /** * Step 1: Convert Raw RDF into a Linked Data Object */ const ldoDataset = await parseRdf(rawTurtle, { baseIRI: "https://solidweb.me/jane_doe/profile/card", }); // Create a linked data object by telling the dataset the type and subject of // the object const janeProfile = ldoDataset // Tells the LDO dataset that we're looking for a FoafProfile .usingType(FoafProfileShapeType) // Says the subject of the FoafProfile .fromSubject("https://solidweb.me/jane_doe/profile/card#me"); /** * Step 2: Manipulate the Linked Data Object */ // Logs "Jane Doe" console.log(janeProfile.name); // Logs "Person" console.log(janeProfile.type); // Logs 0 console.log(janeProfile.knows?.size); // Begins a transaction that tracks your changes startTransaction(janeProfile); janeProfile.name = "Jane Smith"; janeProfile.knows?.add({ "@id": "https://solidweb.me/john_smith/profile/card#me", type: set({ "@id": "Person", }), name: "John Smith", knows: set(janeProfile), }); // Logs "Jane Smith" console.log(janeProfile.name); // Logs "John Smith" console.log(janeProfile.knows?.toArray()[0]?.name); // Logs "Jane Smith" console.log(janeProfile.knows?.toArray()[0]?.knows?.toArray()[0]?.name); /** * Step 3: Convert it back to RDF */ // Logs: // a ; // "Jane Smith"; // . // a ; // "John Smith"; // . console.log(await toTurtle(janeProfile)); // Logs: // DELETE DATA { // "Jane Doe" . // }; // INSERT DATA { // "Jane Smith" . // . // "John Smith" . // . // . // } console.log(await toSparqlUpdate(janeProfile)); } run(); ``` -------------------------------- ### Install @ldo/ldo CLI Source: https://ldo.js.org/latest/api/ldo Initializes the @ldo/ldo project in your project's root folder using the CLI. This is a convenient way to set up the necessary configurations for using the library. ```bash cd my_project/ npx run @ldo/cli init ``` -------------------------------- ### Manage LDO Changes with Transactions - JavaScript/TypeScript Source: https://ldo.js.org/latest/guides/raw_rdf Transactions allow you to track changes made to an LDO without immediately applying them to the original dataset. You can start a transaction, make modifications, inspect added/removed changes using `transactionChanges` or generate SPARQL updates with `toSparqlUpdate`, and finally commit the changes to the dataset using `commitTransaction`. ```javascript import { startTransaction, transactionChanges, toSparqlUpdate, commitTransaction, } from "@ldo/ldo"; // ... Get the profile linked data object startTransaction(profile); profile.name = "Kuzon" const changes = transactionChanges(profile); // Logs: "Kuzon" console.log(changes.added?.toString()) // Logs: "Aang" console.log(changes.removed?.toString()) console.log(await toSparqlUpdate(profile)); commitTransaction(profile); ``` -------------------------------- ### Initialize SolidLdoProvider in React Application Source: https://ldo.js.org/latest/api/solid-react/SolidLdoProvider This snippet demonstrates how to import and use the `SolidLdoProvider` component from the `@ldo/solid-react` library to wrap the root of a React application. It highlights the basic structure for integrating LDO context into a React app. No specific dependencies beyond React and the `@ldo/solid-react` library are shown here. ```jsx import type { FunctionComponent } from "react"; import React from "react"; import { SolidLdoProvider } from "@ldo/solid-react"; // The base component for the app const App: FunctionComponent = () => { return ( ); }; ``` -------------------------------- ### Write to Specific Graphs using JSON-LD Proxies Source: https://ldo.js.org/latest/guides/advanced_data_manipulation The `write(...).using(...)` function allows specifying graphs to write to using particular jsonldDatasetProxies. It also returns an `end` function to reset the graph context, useful for nested modifications. The example shows adding names to different graphs using the same person proxy. ```javascript import jsonldDatasetProxy, { write } from "jsonld-dataset-proxy"; const person1 = jsonldDatasetProxy( dataset, PersonContext ).fromSubject(namedNode("http://example.com/Person1")); // Now all additions with person1 will be on ExampleGraph1 write(namedNode("http://example.com/ExampleGraph1")).using(person1); person1.name.add("Jack"); // Now all additions with person1 will be on ExampleGraph2 write(namedNode("http://example.com/ExampleGraph2")).using(person1); person1.name.add("Spicer"); console.log(dataset.toString()); // Logs: // "Jack" . // "Spicer" . ``` ```javascript const person1 = jsonldDatasetProxy( dataset, PersonContext ).fromSubject(namedNode("http://example.com/Person1")); person1.name.add("default"); const end1 = write(namedNode("http://example.com/Graph1")).using(person1); person1.name.add("1"); const end2 = write(namedNode("http://example.com/Graph2")).using(person1); person1.name.add("2"); const end3 = write(namedNode("http://example.com/Graph3")).using(person1); person1.name.add("3"); end3(); person1.name.add("2 again"); end2(); person1.name.add("1 again"); end1(); person1.name.add("default again"); console.log(dataset.toString()); // Logs: // "default" . // "default again" . // "1" . // "1 again" . // "2" . // "2 again" . // "3" . ``` -------------------------------- ### Create and Commit Data to a Resource Source: https://ldo.js.org/latest/api/connected Explains how to create and commit new data to a Solid resource using `createData` and `commitData`. This involves defining the data shape, associating it with a resource URI, and then updating fields before committing. ```javascript const cPost = solidLdoDataset.createData( // An LDO ShapeType saying that this is a social media psot SocialMediaPostShapeType, // The URI of the post (in this case we'll make it the same as the resource) postResource.uri, // The resource we should write it to postResource, ); // We can add new data cPost.text = "Check out this bad svg:"; cPost.image = { "@id": imageResource.uri }; // And now we commit data const newDataResult = await commitData(cPost); if (newDataResult.isError) throw newDataResult; ``` -------------------------------- ### Create LdoDatasetFactory Instance Source: https://ldo.js.org/latest/api/ldo/LdoDatasetFactory Demonstrates how to instantiate and use the LdoDatasetFactory to create an LdoDataset. It requires an existing RDF/JS Dataset Factory and optionally accepts initial quads. ```javascript import { LdoDatasetFactory } from "ldo"; const datasetFactory = // some RDF/JS Dataset Factory const ldoDatasetFactory = new LdoDatasetFactory(datasetFactory); const ldoDataset = ldoDatasetFactory.dataset(initialDataset); ```