3

With PnPJS, is there a way to check if a site collection exists given several URL?

Something like this:

import {Site} from '@pnp/sp';

const sitesToCheck = [
'myspsite.net/sites/sc1' // exists
'myspsite.net/sites/sc2' // doesn't exist
'myspsite.net/sites/sc3' // doesn't exist
] 
for( const siteUrl of siteToCheck){
   const site = new Site(siteUrl)
   const rootWeb = site.getRootWeb();
}
2

You can check whether site collection exists or not as below:

1) Add the below import statement, we will be using the SPHttpClient provided by PnPJS to make a REST call to /_api/SP.Site.Exists endpoint to determine if a site collection exists or not

import { sp } from "@pnp/sp";
import { SPHttpClient } from "@pnp/sp";

2) Modify your code as below, I created a helper method check if site collection exists or not and also used the render method, you can change it as per your requirement.:

public fetchData(siteUrl: string) : Promise<any> {
    return new Promise(function (resolve, reject) {
      var client = new SPHttpClient();

      client.post("https://myspsite.net/_api/SP.Site.Exists", {
        body: JSON.stringify({
          url: siteUrl
        }),
        headers: {
          "accept": "application/json;",
        },
      }).then(d => {        
        d.json().then((v: any) => {
          resolve(v.value);
        })
      }).catch(d => {
        reject(d);
      });

    });
}

public async render() {

    var sitesToCheck = [
      'https://myspsite.net/sites/sc1',
      'https://myspsite.net/sites/sc2', 
      'https://myspsite.net/sites/sc3'
    ];

    for (var i = 0; i < sitesToCheck.length; i++) {
          await this.fetchData(sitesToCheck[i]).then(d => {
            if(d){
                console.log("Site collection " + sitesToCheck[i] + " exists");
            }else{
                console.log("Site collection " + sitesToCheck[i] + " doesnt exist");
            }
          });
    }
}
  • I got this running, but ran into a CORS issue. If I'm running this client side do I need to set a a header with sp.setup mode:"no-cors" or something like that ?? – Ryan Dec 3 '18 at 19:19
1

I guess you could do something like this. You could play around with the return, but I made a returnobject with the url you sent in, a boolean if it exists, and the status (200, 403 or 404)

import { sp, Web } from "@pnp/sp";

// Class for return onject
export class WebExistsObj {
    url: string;
    status: number;
    doesExists: boolean;
}

// Methof for checking the site
public async checkSiteExists(webUrl: string): Promise<WebExistsObj> {

    try {
        // Make new web from url    
        const web = new Web(webUrl);

        // Try to get web and only select Title
        const webWithTitle = await web.select('Title').get();

        // If web does exist make a return object and return
        if (webWithTitle.Title.length > 0) {
            const returnObj: WebExistsObj = {
                url: webUrl,
                doesExists: true,
                status: 200
            };
            return returnObj;
        }

    }
    catch (error) {

        // If status is 403 it does exist but you don't have permissions
        // If 404 it just doesn't exist
        const exists = error.status === 403 ? true : false;

        const returnObj: WebExistsObj = {
            url: webUrl,
            doesExists: exists,
            status: error.status
        };
        return returnObj;
    }
}

public async mainFunctionThatYouRun(): Promise<void> {
    // let's see if it exists
    const returnData = await checkSiteExists("https://<tenant>.sharepoint.com/sites/test3");

    console.log(returnData);
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.