import * as pnp from 'sp-pnp-js' ; import { Environment , EnvironmentType } from '@microsoft/sp-core-library' ; const LOCALSTORAGE_PREFIX = "SPFXPlaceholders_" ; const PLACEHOLDERS_LISTNAME = "SPFx Placeholders" ; const FIELD_TITLENAME = "Title" ; const FIELD_SPFXCONTENTNAME = "SPFxContent" ; const CACHE_EXPIRATIONMINUTES = 5 ; export interface IPlaceholderItem { Title : string ; SPFxContent : string ; } export interface IPlaceholderCache { Expiration : Number ; Content : IPlaceholderItem [ ] ; } export class PlaceholderItems { public static GetItems ( webID ) { return ( Environment . type === EnvironmentType . Local ) ? this . GetMockListItems ( ) : this . GetRealListItems ( webID ) ; } private static GetRealListItems ( webID ) { return new Promise < IPlaceholderItem [ ] > ( ( resolve ) => { const cachedPlaceholders = localStorage ? JSON . parse ( localStorage . getItem ( LOCALSTORAGE_PREFIX + webID ) ) : null ; if ( cachedPlaceholders && cachedPlaceholders . Expiration > new Date ( ) . getTime ( ) ) { resolve ( cachedPlaceholders . Content ) ; } else { pnp . sp . web . lists . getByTitle ( PLACEHOLDERS_LISTNAME ) . items . select ( FIELD_TITLENAME , FIELD_SPFXCONTENTNAME ) . get ( ) . then ( ( data ) => { if ( localStorage ) { localStorage . setItem ( LOCALSTORAGE_PREFIX + webID , JSON . stringify ( { Expiration : new Date ( ) . getTime ( ) + ( CACHE_EXPIRATIONMINUTES * 60 * 1000 ) , Content : data } ) ) ; } console . log ( 'got it from the list' ) ; resolve ( data ) ; } ) ; } } ) ; } private static GetMockListItems ( ) { return new Promise < IPlaceholderItem [ ] > ( ( resolve ) => { resolve ( [ { Title : "PageHeader" , SPFxContent : "Header Content" } , { Title : "PageFooter" , SPFxContent : "Footer Content" } ] ) ; } ) ; } }