### Basic Example: Get All Web Templates Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp-admin/index.md A basic example demonstrating how to retrieve all web template information using the sp.admin.tenant node. Ensure you have imported both '@pnp/sp' and '@pnp/sp-admin'. ```TS import { spfi } from "@pnp/sp"; import "@pnp/sp-admin"; const sp = spfi(...); // note the "admin" node now available const templates = await sp.admin.tenant.getSPOTenantAllWebTemplates(); ``` -------------------------------- ### Installation and Basic Usage Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp-admin/index.md Instructions on how to install the @pnp/sp-admin package and import it into your TypeScript solution. It also provides a basic example of retrieving web template information. ```CMD npm install @pnp/sp-admin --save ``` ```TS import "@pnp/sp-admin"; import { spfi } from "@pnp/sp"; const sp = spfi(...); // note the "admin" node now available const templates = await sp.admin.tenant.getSPOTenantAllWebTemplates(); ``` -------------------------------- ### Start PnPjs Project Source: https://github.com/pnp/pnpjs/blob/version-4/docs/contributing/npm-scripts.md Executes the 'serve' command to start a debugging server for the PnPjs project. ```cmd npm start ``` -------------------------------- ### Install Project Dependencies with npm Source: https://github.com/pnp/pnpjs/blob/version-4/docs/contributing/setup-dev-machine.md Run this command in the root of the cloned project to install all necessary dependencies for development. This requires Node.js and npm to be installed. ```bash npm install ``` -------------------------------- ### Install @pnp/sp-admin Package Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp-admin/index.md Install the @pnp/sp-admin package using npm. This is the first step to using the library. ```CMD npm install @pnp/sp-admin --save ``` -------------------------------- ### Get Installed Apps for Current User Source: https://github.com/pnp/pnpjs/blob/version-4/docs/graph/teams.md Retrieves all applications installed for the currently authenticated user. ```TypeScript import { graphfi } from "@pnp/graph"; import "@pnp/graph/teams"; const graph = graphfi(...); const installedApps = await graph.me.installedApps(); ``` -------------------------------- ### Get folder files with aliasing Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/alias-parameters.md This example demonstrates how to use parameter aliasing with @pnp/sp to shorten the URL when retrieving files from a folder. It shows the same query as the previous example but with an aliased folder path. ```TypeScript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files"; import "@pnp/sp/folders"; const sp = spfi(...); // same query with aliasing const query = sp.web.getFolderByServerRelativeUrl("!@p1::/sites/dev/Shared Documents/").files.select("Title").top(3); console.log(query.toUrl()); // _api/web/getFolderByServerRelativeUrl('!@p1::/sites/dev/Shared Documents/')/files console.log(query.toRequestUrl()); // _api/web/getFolderByServerRelativeUrl(@p1)/files?@p1='/sites/dev/Shared Documents/'&$select=Title&$top=3 const r = await query(); console.log(r); ``` -------------------------------- ### Install MkDocs Redirects Plugin Source: https://github.com/pnp/pnpjs/blob/version-4/docs/contributing/documentation.md Installs the mkdocs-redirects plugin, which handles redirection from moved documentation pages. ```bash pip install mkdocs-redirects ``` -------------------------------- ### Start Local Development Server Source: https://github.com/pnp/pnpjs/blob/version-4/docs/contributing/debugging.md Command to start a local development server for PnPjs, which serves files using `./debug/serve/main.ts` as the entry point. This is useful for in-browser debugging. ```bash npm run serve ``` -------------------------------- ### Combine Batching and Caching for GET Requests Source: https://github.com/pnp/pnpjs/blob/version-4/docs/concepts/batching-caching.md This example demonstrates how to use batching with caching for GET requests. On the first execution, requests are batched and sent to the server. On subsequent executions within the same session, if the data is found in the cache, it's returned immediately without being added to the batch. ```TypeScript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; import { Caching } from "@pnp/queryable"; const sp = spfi(...); const [batchedSP, execute] = sp.batched(); batchedSP.using(Caching()); batchedSP.web().then(console.log); batchedSP.web.lists().then(console.log); // execute the first set of batched requests, no information is currently cached await execute(); // create a new batch const [batchedSP2, execute2] = await sp.batched(); batchedSP2.using(Caching()); // add the same requests - this simulates the user navigating away from or reloading the page batchedSP2.web().then(console.log); batchedSP2.web.lists().then(console.log); // executing the batch will return the cached values from the initial requests await execute2(); ``` -------------------------------- ### Get folder files with aliasing and batching Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/alias-parameters.md This example illustrates how to use parameter aliasing in conjunction with batching in @pnp/sp. It shows how to alias a folder path within a batched request. ```TypeScript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; const sp = spfi(...); // same query with aliasing and batching const [batchedWeb, execute] = await sp.web.batched(); const query = batchedWeb.web.getFolderByServerRelativePath("!@p1::/sites/dev/Shared Documents/").files.select("Title").top(3); console.log(query.toUrl()); // _api/web/getFolderByServerRelativeUrl('!@p1::/sites/dev/Shared Documents/')/files console.log(query.toRequestUrl()); // _api/web/getFolderByServerRelativeUrl(@p1)/files?@p1='/sites/dev/Shared Documents/'&$select=Title&$top=3 query().then(r => { console.log(r); }); execute(); ``` -------------------------------- ### Install TypeScript @next Source: https://github.com/pnp/pnpjs/blob/version-4/docs/getting-started.md Install the next version of TypeScript to ensure compatibility with Node.js 12 module resolution. ```bash npm install -D typescript@next ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/pnp/pnpjs/blob/version-4/samples/nodejs-app/readme.md Run this command in your project directory to install all the necessary npm packages listed in the package.json file. ```Shell npm install ``` -------------------------------- ### Install MkDocs Material Theme Source: https://github.com/pnp/pnpjs/blob/version-4/docs/contributing/documentation.md Installs the MkDocs Material theme, which is used for processing and rendering the documentation. ```bash python -m pip install mkdocs-material ``` -------------------------------- ### Full Broadcast Example Source: https://github.com/pnp/pnpjs/blob/version-4/docs/core/moments.md An example demonstrating the import, definition, subscription, and emission of a broadcast moment. It shows how to define observer types and use `this` within the observer. ```TypeScript import { broadcast } from "@pnp/core"; // can have any method signature you want that returns void, "this" will always be set type BroadcastObserver = (this: Timeline, message: string) => void; const moments = { example: broadcast(), } as const; obj.on.example(function (this: Timeline, message: string) { this.log(message, 0); }); obj.emit.example("Hello"); ``` -------------------------------- ### Install SP Nightly Build Source: https://github.com/pnp/pnpjs/blob/version-4/docs/concepts/nightly-builds.md Use this command to install the nightly build for the SP package. This allows you to test the latest changes before the official release. ```CMD npm install @pnp/sp@v3nightly --save ``` -------------------------------- ### Install PNPJS Packages for SharePoint NodeJS Source: https://github.com/pnp/pnpjs/blob/version-4/docs/getting-started.md Install the necessary PNPJS packages for interacting with SharePoint from a NodeJS environment. ```cmd npm i @pnp/sp @pnp/nodejs ``` -------------------------------- ### PnPjs Test Function with Recording Enabled Source: https://github.com/pnp/pnpjs/blob/version-4/test/test-recording-setup.md This example shows how to integrate PnPjs test recording into a test function. It uses the `pnpTest` wrapper with a unique GUID and the `this.props` method to manage test properties, which are read from or written to `test-props.json` based on the recording mode. ```typescript import { pnpTest } from "../pnp-test.js"; it("attachmentFiles", pnpTest("9bc6dba6-6690-4453-8d13-4f42e051a245", async function () { const props = await this.props({ itemTitle: `Test_${getRandomString(4)}`, attachmentFile1Name: `att_${getRandomString(4)}.txt`, attachmentFile2Name: `att_${getRandomString(4)}.txt`, }); // add some attachments to an item const r = await list.items.add({ Title: props.itemTitle, }); await r.attachmentFiles.add(props.attachmentFile1Name, "Some Content"); await r.attachmentFiles.add(props.attachmentFile2Name, "Some Content"); return expect(list.items.getById(r.Id).attachmentFiles()).to.eventually.be.fulfilled.and.to.be.an("Array").and.have.length(2); })); ``` -------------------------------- ### Basic PnPjs Usage Example Source: https://github.com/pnp/pnpjs/blob/version-4/docs/getting-started.md A simple example demonstrating how to import and use the getRandomString function from @pnp/core. This snippet logs a random string of a specified length to the console. ```typescript import { getRandomString } from "@pnp/core"; (function() { // get and log a random string console.log(getRandomString(20)); })(); ``` -------------------------------- ### Usage Example for AsyncPager Source: https://github.com/pnp/pnpjs/blob/version-4/docs/concepts/async-paging.md Instantiate and use the `AsyncPager` class to navigate through paged results from a SharePoint list. This example shows how to fetch the first page of items. ```typescript const pager = new AsyncPager(sp.web.lists.getByTitle("BigList").items.top(1000)); const items1 = await pager.next(); ``` -------------------------------- ### PNPJS Internal Class Implementation Example Source: https://github.com/pnp/pnpjs/blob/version-4/docs/contributing/extending-the-library.md Example of a concrete class implementation (_HubSite) used internally by PNPJS, demonstrating inheritance and method definition. This class is wrapped by a Proxy and not directly exposed to consumers. ```TypeScript export class _HubSite extends _SharePointQueryableInstance { /** * Gets the ISite instance associated with this hub site */ // the tag decorator is used to provide some additional telemetry on what methods are // being called. @tag("hs.getSite") public async getSite(): Promise { // we execute a request using this instance, selecting the SiteUrl property, and invoking it immediately and awaiting the result const d = await this.select("SiteUrl")(); // we then return a new ISite instance created from the Site factory using the returned SiteUrl property as the baseUrl return Site(d.SiteUrl); } } ``` ```TypeScript export interface IHubSite extends _HubSite { } /* This defines the HubSite factory function as discussed above binding the spInvokableFactory to a generic param of IHubSite and a param of _HubSite. This is understood to mean that HubSite is a factory function that returns a types of IHubSite which the spInvokableFactory will create using _HubSite as the concrete underlying type. */ export const HubSite = spInvokableFactory(_HubSite); ``` -------------------------------- ### Install PNPJS Packages for Graph NodeJS Source: https://github.com/pnp/pnpjs/blob/version-4/docs/getting-started.md Install the necessary PNPJS packages for interacting with the Microsoft Graph API from a NodeJS environment. ```cmd npm i @pnp/graph @pnp/nodejs ``` -------------------------------- ### Get Installed Languages Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/regional-settings.md Retrieves a list of installed languages available for the web. ```APIDOC ## GET /web/regionalSettings/getInstalledLanguages ### Description Retrieves a list of installed languages for the current web. ### Method GET ### Endpoint /web/regionalSettings/getInstalledLanguages ### Response #### Success Response (200) - **value** (array) - An array of installed language objects. - **Id** (number) - The language ID. - **Title** (string) - The language name. ### Response Example ```json { "value": [ { "Id": 1033, "Title": "English (United States)" }, { "Id": 1031, "Title": "German (Germany)" } ] } ``` ``` -------------------------------- ### Get Installed Apps for a Specific User Source: https://github.com/pnp/pnpjs/blob/version-4/docs/graph/teams.md Retrieves applications installed for a specific user, identified by their email address. ```TypeScript import { graphfi } from "@pnp/graph"; import "@pnp/graph/teams"; const graph = graphfi(...); const installedAppsForUsers = await graph.users('user@contoso.com').installedApps(); ``` -------------------------------- ### Get Installed Languages Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/regional-settings.md Retrieve a list of languages installed on the web. The `installedLanguages` property accessor is deprecated in favor of `getInstalledLanguages`. ```typescript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/regional-settings/web"; const sp = spfi(...); const s = await sp.web.regionalSettings.getInstalledLanguages(); ``` -------------------------------- ### Get a Specific Installed App for User Source: https://github.com/pnp/pnpjs/blob/version-4/docs/graph/teams.md Retrieves details of a specific application installed for the current user, identified by its unique ID. ```TypeScript import { graphfi } from "@pnp/graph"; import "@pnp/graph/users"; import "@pnp/graph/teams"; const graph = graphfi(...); const addedApp = await graph.me.installedApps.getById('NWI2NDk4MzQtNzQxMi00Y2NlLTllNjktMTc2ZTk1YTM5NGY1IyNhNmI2MzM2NS0zMWE0LTRmNDMtOTJlYy03MTBiNzE1NTdhZjk')(); ``` -------------------------------- ### PNPJS Add Property Example (_View fields) Source: https://github.com/pnp/pnpjs/blob/version-4/docs/contributing/extending-the-library.md Example of adding a property ('fields') to a PNPJS class (_View). This demonstrates how to define a getter that returns an interface, utilizing a factory function to create the property's instance. ```TypeScript export class _View extends _SharePointQueryableInstance { // ... other code removed // add the property, and provide a return type // return types should be interfaces public get fields(): IViewFields { // we use the ViewFields factory function supplying "this" as the first parameter // this will create a url like ".../fields/viewfields" due to the defaultPath decorator // on the _ViewFields class. This is equivalent to: ViewFields(this, "viewfields") return ViewFields(this); } // ... other code removed } ``` -------------------------------- ### Get Installed Apps for a Team Source: https://github.com/pnp/pnpjs/blob/version-4/docs/graph/teams.md Retrieves a list of applications installed in a specific team. Ensure the team ID is correct and you have permissions. ```TypeScript import { graphfi } from "@pnp/graph"; import "@pnp/graph/teams"; const graph = graphfi(...); const installedApps = await graph.teams.getById('3531f3fb-f9ee-4f43-982a-6c90d8226528').installedApps(); ``` -------------------------------- ### Get Field by Id Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/fields.md Retrieves a field from a collection (web or list) using its unique GUID. Handles GUIDs with or without curly braces and is case-insensitive. ```APIDOC ## GET /sp/web/fields/getById(guid) ### Description Gets a field from the collection by id (guid). The library handles GUIDs with or without curly braces and is case-insensitive. ### Method GET ### Endpoint - For web fields: `/sp/web/fields.getById("guid")` - For list fields: `/sp/web/lists.getByTitle("listTitle").fields.getById("guid")` ### Parameters #### Path Parameters - **guid** (string) - Required - The unique identifier (GUID) of the field. #### Query Parameters None ### Request Body None ### Request Example ```typescript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists/web"; import "@pnp/sp/fields"; const sp = spfi("YOUR_SHAREPOINT_URL"); // Get field by Id for the web const field = sp.web.fields.getById("03b05ff4-d95d-45ed-841d-3855f77a2483"); // Get field by Id for a specific list const listField = await sp.web.lists.getByTitle("My List").fields.getById("03b05ff4-d95d-45ed-841d-3855f77a2483")(); // Select specific properties const fieldTitle = await field.select("Title")(); console.log(fieldTitle.Title); ``` ### Response #### Success Response (200) - **IFieldInfo** (object) - Contains information about the field. #### Response Example ```json { "Id": "03b05ff4-d95d-45ed-841d-3855f77a2483", "Title": "Example Field Title", "InternalName": "ExampleFieldName", "TypeAsString": "Text" } ``` ``` -------------------------------- ### Serve PnPjs Project Source: https://github.com/pnp/pnpjs/blob/version-4/docs/contributing/npm-scripts.md Starts a debugging server serving a bundled script with ./debug/serve/main.ts as the entry point. This allows for testing and debugging code within a webpage context. ```cmd npm run serve ``` -------------------------------- ### Get SharePoint List by ID Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/lists.md Retrieves a SharePoint list by its unique identifier (GUID). The library handles GUIDs with or without curly braces and is case-insensitive. ```TypeScript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; const sp = spfi(...); // get the list by Id const list = sp.web.lists.getById("03b05ff4-d95d-45ed-841d-3855f77a2483"); // we can use this 'list' variable to execute more queries on the list: const r = await list.select("Title")(); // show the response from the server console.log(r.Title); ``` -------------------------------- ### Add a Configured Web Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/webs.md Use this to add a new web with specific settings like title, URL, description, template, language, and permission inheritance. This example creates a German wiki site that does not inherit permissions. ```TypeScript import { spfi } from "@pnp/sp"; import { IWebAddResult } from "@pnp/sp/webs"; const sp = spfi(...); // create a German language wiki site with title, url, description, which does not inherit permissions sp.web.webs.add("wiki", "subweb2", "a wiki web", "WIKI#0", 1031, false).then((w: IWebAddResult) => { // ... }); ``` -------------------------------- ### Get List by Id Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/lists.md Retrieves a specific SharePoint list using its unique identifier (GUID). The library handles GUIDs with or without curly braces and is case-insensitive. ```APIDOC ## GET /web/lists/getById(guid) ### Description Gets a list from the collection by its unique identifier (GUID). ### Method GET ### Endpoint /web/lists/getById("{list-id}") ### Parameters #### Path Parameters - **guid** (string) - Required - The unique identifier of the list. ### Request Example ```typescript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; const sp = spfi(...); // get the list by Id const list = sp.web.lists.getById("03b05ff4-d95d-45ed-841d-3855f77a2483"); const r = await list.select("Title")(); console.log(r.Title); ``` ### Response #### Success Response (200) - **Title** (string) - The title of the list. #### Response Example ```json { "Title": "Example List Title" } ``` ``` -------------------------------- ### Run Build System Source: https://github.com/pnp/pnpjs/blob/version-4/tools/buildsystem/readme.md Execute the build system with a specific configuration name or default to 'build'. ```bash pnpbuild -n ``` ```bash pnpbuild ``` -------------------------------- ### Get App Details by GUID Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/alm.md Retrieve the details of a specific app from the catalog using its unique GUID. This is also the entry point for performing actions on the app. ```typescript const app = await catalog.getAppById("5137dff1-0b79-4ebc-8af4-ca01f7bd393c")(); ``` -------------------------------- ### Initialize with DefaultInit Behavior in @pnp/sp Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/behaviors.md Use DefaultInit to include Telemetry, RejectOnError, and ResolveOnData behaviors. It also configures cache and credentials for RequestInit. ```typescript import { spfi, DefaultInit } from "@pnp/sp"; import "@pnp/sp/webs"; const sp = spfi().using(DefaultInit()); await sp.web(); ``` -------------------------------- ### Create Site Script Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/site-scripts.md Demonstrates how to create a new site script with a title, description, and content. ```APIDOC ## POST /api/siteScripts/create ### Description Creates a new site script. ### Method POST ### Endpoint /api/siteScripts/create ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The title of the site script. - **description** (string) - Required - The description of the site script. - **content** (object) - Required - The content of the site script, including schema, actions, bindata, and version. ### Request Example ```json { "title": "Title", "description": "description", "content": { "$schema": "schema.json", "actions": [ { "themeName": "Theme Name 123", "verb": "applyTheme" } ], "bindata": {}, "version": 1 } } ``` ### Response #### Success Response (200) - **Title** (string) - The title of the created site script. #### Response Example ```json { "Title": "Title" } ``` ``` -------------------------------- ### Serve MkDocs Documentation Locally Source: https://github.com/pnp/pnpjs/blob/version-4/docs/contributing/documentation.md Serves the MkDocs documentation locally for previewing changes. Access the documentation by opening a browser to http://127.0.0.1:8000/. ```bash mkdocs serve ``` -------------------------------- ### Get Feature by ID - Site and Web Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/features.md Retrieves information about a specific feature using its GUID. Ensure the GUID is in the correct format. This method can be used for both web and site-scoped features. ```TypeScript import { spfi } from "@pnp/sp"; const sp = spfi(...); //Example of GUID format a7a2793e-67cd-4dc1-9fd0-43f61581207a const webFeatureId = "guid-of-web-feature"; const webFeature = await sp.web.features.getById(webFeatureId)(); const siteFeatureId = "guid-of-site-scope-feature"; const siteFeature = await sp.site.features.getById(siteFeatureId)(); ``` -------------------------------- ### Queryable Constructor Examples Source: https://github.com/pnp/pnpjs/blob/version-4/docs/queryable/queryable.md Demonstrates various ways to construct Queryable objects, including inheriting observers, appending paths, and rebasing to different hosts. Ensure the correct parameter types are used for desired behavior. ```typescript // represents a fully configured queryable with url and registered observers // url: https://something.com const baseQueryable; // child1 will: // - reference the observers of baseQueryable // - have a url of "https://something.com/subpath" const child1 = Child(baseQueryable, "subpath"); // child2 will: // - reference the observers of baseQueryable // - have a url of "https://something.com" const child2 = Child(baseQueryable); // nonchild1 will: // - have NO registered observers or connection to baseQueryable // - have a url of "https://somethingelse.com" const nonchild1 = Child("https://somethingelse.com"); // nonchild2 will: // - have NO registered observers or connection to baseQueryable // - have a url of "https://somethingelse.com/subpath" const nonchild2 = Child("https://somethingelse.com", "subpath"); // rebased1 will: // - reference the observers of baseQueryable // - have a url of "https://somethingelse.com" const rebased1 = Child([baseQueryable, "https://somethingelse.com"]); // rebased2 will: // - reference the observers of baseQueryable // - have a url of "https://somethingelse.com/subpath" const rebased2 = Child([baseQueryable, "https://somethingelse.com"], "subpath"); ``` -------------------------------- ### Get an App by ID Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/alm.md Retrieves details of a specific app from the app catalog using its GUID. ```APIDOC ## Get an App by ID ### Description Retrieves the details of a single app from the app catalog using its unique GUID. This method also serves as the entry point for performing specific app actions. ### Method GET ### Endpoint `/catalog/getAppById('{appId}')` (relative to the AppCatalog instance) ### Parameters #### Path Parameters - **appId** (string) - Required - The GUID of the app to retrieve. ### Request Example ```typescript const app = await catalog.getAppById("5137dff1-0b79-4ebc-8af4-ca01f7bd393c")(); ``` ### Response #### Success Response (200) An object containing the details of the specified app. #### Response Example ```json { "Id": "5137dff1-0b79-4ebc-8af4-ca01f7bd393c", "Title": "Example App", "Deployed": true // ... other app properties } ``` ``` -------------------------------- ### Test List Item Operations with PnPjs Source: https://github.com/pnp/pnpjs/blob/version-4/docs/contributing/debug-tests.md This example demonstrates how to set up tests for list item operations using Mocha and Chai. It includes setting up a test list, adding items in batches, and verifying item retrieval. Ensure web tests are enabled before running. ```TypeScript import { getRandomString } from "@pnp/core"; import { testSettings } from "../main"; import { expect } from "chai"; import { sp } from "@pnp/sp"; import "@pnp/sp/lists/web"; import "@pnp/sp/items/list"; import { IList } from "@pnp/sp/lists"; describe("Items", () => { // any tests that make a web request should be withing a block checking if web tests are enabled if (testSettings.enableWebTests) { // a block scoped var we will use across our tests let list: IList = null; // we use the before block to setup // executed before all the tests in this block, see the mocha docs for more details // mocha prefers using function vs arrow functions and this is recommended before(async function () { // execute a request to ensure we have a list const ler = await sp.web.lists.ensure("ItemTestList", "Used to test item operations"); list = ler.list; // in this case we want to have some items in the list for testing so we add those // only if the list was just created if (ler.created) { // add a few items to get started const batch = sp.web.createBatch(); list.items.inBatch(batch).add({ Title: `Item ${getRandomString(4)}` }); list.items.inBatch(batch).add({ Title: `Item ${getRandomString(4)}` }); list.items.inBatch(batch).add({ Title: `Item ${getRandomString(4)}` }); list.items.inBatch(batch).add({ Title: `Item ${getRandomString(4)}` }); list.items.inBatch(batch).add({ Title: `Item ${getRandomString(4)}` }); await batch.execute(); } }); // this test has a label "get items" and is run via an async function it("get items", async function () { // make a request for the list's items const items = await list.items(); // report that we expect that result to be an array with more than 0 items expect(items.length).to.be.gt(0); }); // ... remainder of code removed } }); ``` -------------------------------- ### Get Feature by ID Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/features.md Retrieves the information about a specific feature using its GUID at the web or site collection level. ```APIDOC ## GET /sp/web/features/getById(featureId) ### Description Gets the information about a feature for the given GUID at the web level. ### Method GET ### Endpoint ``` /sp/web/features/getById(featureId) ``` ### Parameters #### Path Parameters - **featureId** (string) - Required - The GUID of the feature to retrieve. ### Response #### Success Response (200) - **feature** (object) - Details of the feature. ### Response Example ```json { "Id": "a7a2793e-67cd-4dc1-9fd0-43f61581207a", "Title": "Feature Title", "Scope": 2 } ``` ## GET /sp/site/features/getById(featureId) ### Description Gets the information about a feature for the given GUID at the site collection level. ### Method GET ### Endpoint ``` /sp/site/features/getById(featureId) ``` ### Parameters #### Path Parameters - **featureId** (string) - Required - The GUID of the feature to retrieve. ### Response #### Success Response (200) - **feature** (object) - Details of the feature. ### Response Example ```json { "Id": "a7a2793e-67cd-4dc1-9fd0-43f61581207a", "Title": "Feature Title", "Scope": 3 } ``` ``` -------------------------------- ### Get List by Title Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/lists.md Retrieves a SharePoint list using its title. This is a convenient way to access lists when the GUID is not known. ```APIDOC ## GET /web/lists/getByTitle(title) ### Description Gets a list from the collection by its title. ### Method GET ### Endpoint /web/lists/getByTitle("{list-title}") ### Parameters #### Path Parameters - **title** (string) - Required - The title of the list. ### Request Example ```typescript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; const sp = spfi(...); // get the default document library 'Documents' const list = sp.web.lists.getByTitle("Documents"); const r = await list.select("Id")(); console.log(r.Id); ``` ### Response #### Success Response (200) - **Id** (string) - The unique identifier of the list. #### Response Example ```json { "Id": "03b05ff4-d95d-45ed-841d-3855f77a2483" } ``` ``` -------------------------------- ### Get Hub Site by Id Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/hubsites.md Retrieve a specific hub site by its unique site ID (GUID) using the `getById` method. ```typescript import { spfi } from "@pnp/sp"; import { IHubSiteInfo } from "@pnp/sp/hubsites"; import "@pnp/sp/hubsites"; const sp = spfi(...); const hubsite: IHubSiteInfo = await sp.hubSites.getById("3504348e-b2be-49fb-a2a9-2d748db64beb")(); // log hub site title to console console.log(hubsite.Title); ``` -------------------------------- ### Setup PnPjs and Graph Services in a Service Class Source: https://github.com/pnp/pnpjs/blob/version-4/docs/concepts/project-preset.md Configure PnPjs and GraphFI instances within a service class using ServiceKey and ServiceScope. This is useful when full context access is not available, such as in services. ```typescript import { ServiceKey, ServiceScope } from "@microsoft/sp-core-library"; import { PageContext } from "@microsoft/sp-page-context"; import { AadTokenProviderFactory } from "@microsoft/sp-http"; import { spfi, SPFI, SPFx as spSPFx } from "@pnp/sp"; import { graphfi, GraphFI, SPFx as gSPFx } from "@pnp/graph"; import "@pnp/sp/webs"; import "@pnp/sp/lists/web"; export interface ISampleService { getLists(): Promise; } export class SampleService { public static readonly serviceKey: ServiceKey = ServiceKey.create('SPFx:SampleService', SampleService); private _sp: SPFI; private _graph: GraphFI; constructor(serviceScope: ServiceScope) { serviceScope.whenFinished(() => { const pageContext = serviceScope.consume(PageContext.serviceKey); const aadTokenProviderFactory = serviceScope.consume(AadTokenProviderFactory.serviceKey); //SharePoint this._sp = spfi().using(spSPFx({ pageContext })); //Graph this._graph = graphfi().using(gSPFx({ aadTokenProviderFactory })); } public getLists(): Promise { return this._sp.web.lists(); } } ``` -------------------------------- ### Profiles API Overview Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/profiles.md The Profiles API allows you to work with the SharePoint User Profile Store. Import the necessary modules to get started. ```APIDOC ## Importing Profiles Module ### Description Import the profiles module to enable access to user profile functionalities. ### Code ```typescript import { spfi } from "@pnp/sp"; import "@pnp/sp/profiles"; ``` ``` -------------------------------- ### Get User Chats with graphGet Source: https://github.com/pnp/pnpjs/blob/version-4/docs/concepts/calling-other-endpoints.md Use graphGet to retrieve chats for a specific user. Construct the queryable by starting with a user instance and adding the 'chats' path. ```TypeScript import { graphfi } from "@pnp/graph"; import "@pnp/graph/users"; import { GraphQueryable, graphGet } from "@pnp/graph"; // Establish GRAPHFI instance passing in the appropriate behavior to register the initial observers. const graph = graphfi(...); // create an instance of the user queryable const user = graph.users.getById('jane@contoso.com'); // get the chats for the user const chat: any = await graphGet(GraphQueryable(user, "chats")); ``` -------------------------------- ### SPFx and SP Behaviors Initialization Source: https://github.com/pnp/pnpjs/blob/version-4/docs/graph/behaviors.md Demonstrates how to initialize both @pnp/sp and @pnp/graph with their respective SPFx behaviors using the provided SPFx context. ```typescript import { GraphFI, graphfi, SPFx as graphSPFx } from '@pnp/graph' import { SPFI, spfi, SPFx as spSPFx } from '@pnp/sp' const sp = spfi().using(spSPFx(this.context)); const graph = graphfi().using(graphSPFx(this.context)); ``` -------------------------------- ### Get SharePoint Form by ID Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/forms.md Retrieves a specific form from a SharePoint list using its unique ID. The library accepts GUIDs with or without curly braces and is case-insensitive. ```TypeScript import { spfi } from "@pnp/sp"; import "@pnp/sp/forms"; import "@pnp/sp/lists"; const sp = spfi(...); // get the field by Id for web const form = sp.web.lists.getByTitle("Documents").forms.getById("{c4486774-f1e2-4804-96f3-91edf3e22a19}")(); ``` -------------------------------- ### Perform App Actions (Tenant App Catalog Only) Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/alm.md Execute actions such as deploy, retract, install, uninstall, upgrade, and remove on an app. These actions are only supported within the tenant app catalog context and do not return a value, so success should be monitored via try/catch blocks. ```typescript const myAppId = "5137dff1-0b79-4ebc-8af4-ca01f7bd393c"; // deploy await catalog.getAppById(myAppId).deploy(); // retract await catalog.getAppById(myAppId).retract(); // install await catalog.getAppById(myAppId).install(); // uninstall await catalog.getAppById(myAppId).uninstall(); // upgrade await catalog.getAppById(myAppId).upgrade(); // remove await catalog.getAppById(myAppId).remove(); ``` -------------------------------- ### Basic SearchQueryBuilder Usage Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/search.md Demonstrates basic fluent query building with SearchQueryBuilder. Imports required for search functionality are included. ```typescript import { spfi } from "@pnp/sp"; import "@pnp/sp/search"; import { SearchQueryBuilder, SearchResults, ISearchQuery } from "@pnp/sp/search"; const sp = spfi(...); // basic usage let q = SearchQueryBuilder().text("test").rowLimit(4).enablePhonetic; sp.search(q).then(h => { /* ... */ }); ``` -------------------------------- ### Get Site Map Menu State Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/navigation.md Retrieves the menu state of a SiteMapProvider. Can specify a starting node key and depth. Handles exceptions for missing providers or nodes. ```typescript import { spfi } from "@pnp/sp"; import "@pnp/sp/navigation"; const sp = spfi(...); // Will return a menu state of the default SiteMapProvider 'SPSiteMapProvider' where the dump starts a the RootNode (within the site) with a depth of 10 levels. const state = await sp.navigation.getMenuState(); // Will return the menu state of the 'SPSiteMapProvider', starting with the node with the key '1002' with a depth of 5 const state2 = await sp.navigation.getMenuState("1002", 5); // Will return the menu state of the 'CurrentNavSiteMapProviderNoEncode' from the root node of the provider with a depth of 5 const state3 = await sp.navigation.getMenuState(null, 5, "CurrentNavSiteMapProviderNoEncode"); ``` -------------------------------- ### Get List Items with CAML Query Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/lists.md Fetch list items using a CAML query. This example includes the 'Title' field and limits results to 5 items. ```TypeScript import { ICamlQuery } from "@pnp/sp/lists"; // build the caml query object (in this example, we include Title field and limit rows to 5) const caml: ICamlQuery = { ViewXml: "5", }; // get list items const r = await list.getItemsByCAMLQuery(caml); // log resulting array to console console.log(r); ``` ```TypeScript import { ICamlQuery } from "@pnp/sp/lists"; // build the caml query object (in this example, we include Title field and limit rows to 5) const caml: ICamlQuery = { ViewXml: "5", }; // get list items const r = await list.getItemsByCAMLQuery(caml, "RoleAssignments"); // log resulting item array to console console.log(r); ``` -------------------------------- ### Setup supporting code for @pnp/sp/related-items Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/related-items.md This supporting code is required for all samples in this section. It sets up the PnPjs context and ensures necessary lists are available. ```typescript import { spfi, SPFx, extractWebUrl } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/related-items/web"; import "@pnp/sp/lists/web"; import "@pnp/sp/items/list"; import "@pnp/sp/files/list"; import { IList } from "@pnp/sp/lists"; import { getRandomString } from "@pnp/core"; const sp = spfi(...); // setup some lists (or just use existing ones this is just to show the complete process) // we need two lists to use for creating related items, they need to use template 107 (task list) const ler1 = await sp.web.lists.ensure("RelatedItemsSourceList", "", 107); const ler2 = await sp.web.lists.ensure("RelatedItemsTargetList", "", 107); const sourceList = ler1.list; const targetList = ler2.list; const sourceListName = await sourceList.select("Id")().then(r => r.Id); const targetListName = await targetList.select("Id")().then(r => r.Id); // or whatever you need to get the web url, both our example lists are in the same web. const webUrl = sp.web.toUrl(); // ...individual samples start here ``` -------------------------------- ### Get and Update a Collection of Items Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/items.md Retrieve a collection of items using `top` and `filter`, then update the first item found. This example demonstrates both string-based and fluent filter syntax. ```TypeScript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; import "@pnp/sp/items"; const sp = spfi(...); // you are getting back a collection here const items: any[] = await sp.web.lists.getByTitle("MyList").items.top(1).filter("Title eq 'A Title'")(); // Using fluent filter const items1: any[] = await sp.web.lists.getByTitle("MyList").items.top(1).filter(f => f.text("Title").equals("A Title"))(); // see if we got something if (items.length > 0) { const updatedItem = await sp.web.lists.getByTitle("MyList").items.getById(items[0].Id).update({ Title: "Updated Title", }); console.log(JSON.stringify(updatedItem)); } ``` -------------------------------- ### Apply and Get Available Web Templates Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/webs.md Apply a site definition or template to a web, typically used in provisioning. Also shows how to retrieve available web templates and filter them. ```typescript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; const sp = spfi(...); const web = sp.web; const templates = (await web.availableWebTemplates().select("Name")<{ Name: string }[]>()).filter(t => /ENTERWIKI#0/i.test(t.Name)); // apply the wiki template const template = templates.length > 0 ? templates[0].Name : "STS#0"; await web.applyWebTemplate(template); ``` -------------------------------- ### Initialize Graph with DefaultInit Behavior Source: https://github.com/pnp/pnpjs/blob/version-4/docs/graph/behaviors.md Use DefaultInit to include Telemetry, RejectOnError, and ResolveOnData behaviors. It also configures cache, credentials, and ensures absolute request URLs. ```typescript import { graphfi, DefaultInit } from "@pnp/graph"; import "@pnp/graph/users"; const graph = graphfi().using(DefaultInit()); await graph.users(); ``` -------------------------------- ### Get Current Team Photo Source: https://github.com/pnp/pnpjs/blob/version-4/docs/graph/photos.md Retrieves the profile photo of a specific team by its ID as a Blob. This is useful for displaying team avatars. The example assumes a browser environment; Node.js can use getBuffer(). ```TypeScript import { graphfi } from "@pnp/graph"; import "@pnp/graph/teams"; import "@pnp/graph/photos"; const graph = graphfi(...); const photoValue = await graph.teams.getById("7d2b9355-0891-47d3-84c8-bf2cd9c62177").photo.getBlob(); const url = window.URL || window.webkitURL; const blobUrl = url.createObjectURL(photoValue); document.getElementById("photoElement").setAttribute("src", blobUrl); ``` -------------------------------- ### Import All Sharing Methods Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/sharing.md Include all sharing sub-modules to attach sharing methods to Item, File, Folder, and Web objects. Ensure spfi is configured. ```typescript import "@pnp/sp/sharing"; import "@pnp/sp/webs"; import "@pnp/sp/site-users/web"; import { spfi } from "@pnp/sp"; const sp = spfi(...); const user = await sp.web.siteUsers.getByEmail("user@site.com")(); const r = await sp.web.shareWith(user.LoginName); ``` -------------------------------- ### Get folder files without aliasing Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/alias-parameters.md This example shows how to retrieve files from a folder using the standard @pnp/sp API without parameter aliasing. It demonstrates selecting specific properties and limiting the results. ```TypeScript import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files"; import "@pnp/sp/folders"; const sp = spfi(...); // still works as expected, no aliasing const query = sp.web.getFolderByServerRelativeUrl("/sites/dev/Shared Documents/").files.select("Title").top(3); console.log(query.toUrl()); // _api/web/getFolderByServerRelativeUrl('/sites/dev/Shared Documents/')/files console.log(query.toRequestUrl()); // _api/web/getFolderByServerRelativeUrl('/sites/dev/Shared Documents/')/files?$select=Title&$top=3 const r = await query(); console.log(r); ``` -------------------------------- ### Get Free/Busy Schedule Source: https://github.com/pnp/pnpjs/blob/version-4/docs/graph/calendars.md Fetches the free/busy schedule for a list of users within a specified time range. Requires the users' email addresses, start and end times, and the availability view interval. Ensure '@pnp/graph/calendars' and '@pnp/graph/users' are imported. ```TypeScript import { graphfi } from "@pnp/graph"; import '@pnp/graph/calendars'; import '@pnp/graph/users'; const graph = graphfi(...); const schedule = await graph.me.calendar.getSchedule({ schedules: ["martha@contoso.com", "user@contoso.com"], startTime: { dateTime: "2019-03-15T09:00:00", timeZone: "Pacific Standard Time", }, endTime: { dateTime: "2019-03-15T18:00:00", timeZone: "Pacific Standard Time", }, availabilityViewInterval: 60 }) ``` -------------------------------- ### Import Sharing Methods Source: https://github.com/pnp/pnpjs/blob/version-4/docs/sp/sharing.md Demonstrates how to import sharing methods, either all at once or selectively for specific objects (Web, Item, File, Folder). ```APIDOC ## Import All Sharing Methods ### Description Imports and attaches sharing methods to all four sharable types: Item, File, Folder, and Web. ### Code Example ```typescript import "@pnp/sp/sharing"; import "@pnp/sp/webs"; import "@pnp/sp/site-users/web"; import { spfi } from "@pnp/sp"; const sp = spfi("YOUR_SHAREPOINT_URL"); // Example usage: // const user = await sp.web.siteUsers.getByEmail("user@example.com")(); // const r = await sp.web.shareWith(user.LoginName); ``` ## Selective Import for Web Sharing Methods ### Description Imports only the sharing methods specifically for the Web object. ### Code Example ```typescript import "@pnp/sp/sharing/web"; import "@pnp/sp/webs"; import "@pnp/sp/site-users/web"; import { spfi } from "@pnp/sp"; const sp = spfi("YOUR_SHAREPOINT_URL"); // Example usage: // const user = await sp.web.siteUsers.getByEmail("user@example.com")(); // const r = await sp.web.shareWith(user.LoginName); ``` ```