Saving time and bandwidth by reviewing/refactoring old code

Prelude

I build multiple minor web apps at work. They might be forms for data collection, or registries with basic CRUD (Create, Read, Update, Delete) capabilities.

These are written in HTML/JS/CSS and hosted on SharePoint – utilizing the SharePoint REST API to handle storage and permissions.

When data is stored in a SharePoint list, I grab the field Description and possibly also Choices from the SharePoint field via a REST call to /_api/lists/getbytitle('listtitle')/fields?$filter=InternalNAme eq 'fieldName'. This ensures that users can also edit these options for the form by themself.

The issue

Since I did this the first time, I have simply copied the solution whenever I needed to. It was not until recently, that I discovered a design flaw causing many more HTTP requests than was actually needed.

Due to just copying the initial solution, I performed an HTTP request for each field that I needed to get. When having 20 fields, this led to 20 HTTP request – just to get the field descriptions. Crazy!

After looking into it, I found that all required fields can be picked up in one HTTP request if the filter is modified to $filter=((InternalNAme eq 'fieldName1') or (InternalNAme eq 'fieldName2') or (InternalNAme eq 'fieldName3')). The response will now contain all fields which can then be iterated. Saving time and bandwidth (Yes, both are important – just ask the users and the network dept :)).

The change (TLDR)

Changing my functions for fetching fields from SharePoint REST API from this – written in Angular by the way:

getField(fieldInternalName: string): Observable<any> {
    return this._http
      .get(
        `https://sharepointurl/sites/sitename/_api/lists/getbytitle('listtitle')/fields?$filter=InternalName eq '${fieldInternalName}'`,
        {
          headers: new Headers({
            'Content-Type': 'application/json;odata=minimalmetadata',
            Accept: 'application/json;odata=minimalmetadata'
          })
        }
      )
      .map(field => field.json().value);
  }

to this:

getFields(fieldInternalNames: string[]): Observable<any[]> {
    let filter: string = `?$filter=(`;
    filter += fieldInternalNames
      .map(name => `(InternalName eq '${name}')`)
      .join(' or ');
    filter += `)`;
    return this._http
      .get(
        `https://sharepointurl/sites/sitename/_api/lists/getbytitle('listtitle')/fields${filter}`,
        {
          headers: new Headers({
            'Content-Type': 'application/json;odata=minimalmetadata',
            Accept: 'application/json;odata=minimalmetadata',
            'X-RequestDigest': digest
          })
        }
      )
      .map(field => field.json().value);
  }

Saved me both time and bandwitdh!

Leave a Reply

  • Your email address will not be published.
  • Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: