Оптимизация получения списков SharePoint

Приведенный ниже фрагмент кода извлекает все элементы в каждом списке на дочернем сайте. Затем выполняется фильтрация по заголовку списка, чтобы анализировалась только информация из списков, содержащих «RDTEN» или «закупки» в заголовке. В конечном результате мне нужно построить график для агрегированной информации.

Мне нужна помощь в оптимизации этого кода, использование лучшего запроса улучшит время отклика, поскольку я могу искать элементы RegEx в самом запросе, удаляя двойной цикл for. Однако можно ли сделать все это в одном запросе?

// Loads libraries from CDNs... 
javascript: ( function() {
    function l( u, i ) {
         var d = document;
        if ( !d.getElementById( i ) ) {
           var s = d.createElement( 'script' );
            s.src = u;
            s.id = i;
            s.async = true;
            d.body.appendChild( s );
        }
      }
    // l( url, idForElem )
    l( '//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js', 'msAjax' )
    l( '//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js', 'jQuery' )
} )();

// Wait for SP.js to finish loading before we run the queries.
SP.SOD.executeOrDelayUntilScriptLoaded( getSPListData, 'SP.js' );

function getSPListData() {
    // Set up the first query
    this.result = [];
     this.siteUrl = 
'https://sites/orgs/subsite';
     this.ctx = new SP.ClientContext( siteUrl )
    this.lists = ctx.get_web().get_lists();
    this.expr = /(RDTEN)|(procurement)/i 
    this.ctx.load( this.lists, "Include(Id,Title)" );

    ctx.executeQueryAsync( 
      this.getSPListData_SecondQuery.bind(this), 
      this.getSPListData_LogError.bind(this) 
    );

     }

function getSPListData_SecondQuery(sender, args){
    lists.get_data().forEach( function( list ) {
      // Set up the second query and push its results into the "Result" 
     array
      var items = list.getItems( SP.CamlQuery.createAllItemsQuery() );
      ctx.load( items );
       // This entry is the list's base data
      var listEntry = {
           id: list.get_id().toString(),
           title: list.get_title()
      } 
      // Push the data into result, items will have all items in each list.
      result.push( {
           list: listEntry,
           items: items
      } );
   } );
   ctx.executeQueryAsync(
      this.getSPListData_SecondQuery_Success.bind(this),
      this.getSPListData_LogError.bind(this)
   );
}

function getSPListData_SecondQuery_Success(sender, args){
    //transform listitem properties. This is where the "items" section of 
    "Result" is filled out.
   result.forEach( function( item ) {
       item.items = item.items.get_data().map( function( listItem ) {
         return listItem.get_fieldValues();
       } );
   } );

   // Filter each by the ReGex expression earlier on the Title field.
    var oListData = [];
    var itemTitle;
   for ( listNum = 0, listTot = result.length; listNum < listTot; listNum++ 
   ) {
   for ( itemNum = 0, itemTot = result[ listNum ].items.length; itemNum < 
   itemTot; itemNum++ ) {
    itemTitle = result[ listNum ].items[ itemNum ].Title
    if ( itemTitle && itemTitle.match( expr ) ) {
       // put data into a list
         oListData.push( result[ listNum ].items[ itemNum ] )
     }
     }
   }
  // you can make the data visible here
  manageData( oListData, result );
  }

// incase an error comes up in the execution of the queries
 function getSPListData_LogError( sender, args ) {
  console.log( args.get_message() ); 
}

function manageData( oListData, allData ) {
     // Do stuff with list items here...
   var oListDataField = document.getElementById( "listItemData" );
  var stringBuilding = '';

  for(i=0, itemMax = Math.min(5, oListData.length); i < itemMax; i++){
      stringBuilding += " Title = " + oListData[i].Title + "<br/>"
      stringBuilding += " Library = " + oListData[i].FileDirRef + "<br/> 
 <br/>"
  }
 oListDataField.innerHTML = stringBuilding

  // For seeing the relative data:
   console.log(allData)
   console.log(oListData)
 }

person seaandtea    schedule 11.01.2019    source источник


Ответы (1)


Лучший способ справиться с этим случаем — использовать поисковый API, чтобы вы получали каждый элемент списка, который содержит ваше ключевое слово в своих заголовках.

/_api/search/query?querytext='(Заголовок:RDTEN ИЛИ Заголовок:закупки)'

Язык запросов по ключевым словам ( KQL) справочник по синтаксису

person Tany3450    schedule 12.01.2019
comment
хм, я не очень хорошо знаком с тем, как я буду интегрировать это в свой JS, и мне нужно, чтобы это было включено. - person seaandtea; 14.01.2019
comment
Проверь это; docs.microsoft.com/ en-us/sharepoint/dev/общее-развитие/ - person Tany3450; 15.01.2019