import moment from 'moment' ; import { ApiItem , NewsfeedItem } from '../types' ; import { NEWSFEED_FALLBACK_LANGUAGE } from '../../common/constants' ; export const convertItems = ( items , userLanguage ) : NewsfeedItem [ ] => { return items . filter ( validatePublishedDate ) . map ( ( item ) => localizeItem ( item , userLanguage ) ) . filter ( validateIntegrity ) ; } ; export const validatePublishedDate = ( item ) : boolean => { if ( moment ( item . expire_on ) . isBefore ( Date . now ( ) ) ) { return false ; } if ( moment ( item . publish_on ) . isAfter ( Date . now ( ) ) ) { return false ; } return true ; } ; export const localizeItem = ( rawItem , userLanguage ) : NewsfeedItem => { const { expire_on : expireOnUtc , publish_on : publishOnUtc , languages , title , description , link_text : linkText , link_url : linkUrl , badge , hash , } = rawItem ; let chosenLanguage = userLanguage ; if ( languages && ! languages . includes ( chosenLanguage ) ) { chosenLanguage = NEWSFEED_FALLBACK_LANGUAGE ; } return { title : title [ chosenLanguage ] , description : description [ chosenLanguage ] , linkText : linkText != null ? linkText [ chosenLanguage ] : null , linkUrl : linkUrl [ chosenLanguage ] , badge : badge != null ? badge ! [ chosenLanguage ] : null , publishOn : moment ( publishOnUtc ) , expireOn : moment ( expireOnUtc ) , hash : hash . slice ( 0 , 10 ) , } ; } ; export const validateIntegrity = ( item ) : boolean => { const hasMissing = [ item . title , item . description , item . linkText , item . linkUrl , item . publishOn , item . hash , ] . includes ( undefined ) ; return ! hasMissing ; } ;