import immer from 'immer' ; import _ from 'lodash' ; import { Column , ColumnCreation , ColumnSubscription , ColumnSubscriptionCreation , Installation , NormalizedInstallations , } from '../types' ; import { getUniqueIdForSubscription } from './github/shared' ; import { guid , normalizeUsername } from './shared' ; export function normalizeColumns ( columns , updatedAt ? ) { const items = columns || [ ] ; const byId = { } ; const allIds = items . map ( ( column ) => { const id = column . id || guid ( ) ; byId [ id ] = immer ( column , ( draft ) => { draft . id = id ; draft . subscriptionIds = column . subscriptionIds || [ ] ; draft . subscriptionIdsHistory = column . subscriptionIdsHistory || [ ] ; draft . createdAt = column . createdAt || new Date ( ) . toISOString ( ) ; draft . updatedAt = column . updatedAt || new Date ( ) . toISOString ( ) ; draft . subscriptionIds . forEach ( ( subscriptionId ) => { if ( ! subscriptionId ) return ; if ( ! draft . subscriptionIdsHistory . includes ( subscriptionId ) ) { draft . subscriptionIdsHistory . push ( subscriptionId ) ; } } ) ; } ) as Column ; return id ; } ) ; return { allIds , byId , updatedAt : updatedAt || new Date ( ) . toISOString ( ) } ; } export function normalizeSubscriptions ( subscriptions , updatedAt ? ) { const items = subscriptions || [ ] ; const byId = { } ; const allIds = items . map ( ( subscription ) => { const id = subscription . id || getUniqueIdForSubscription ( subscription ) ; byId [ id ] = immer ( subscription as ColumnSubscription , ( draft ) => { draft . id = id ; draft . data = subscription . data || { } ; draft . createdAt = subscription . createdAt || new Date ( ) . toISOString ( ) ; draft . updatedAt = subscription . updatedAt || new Date ( ) . toISOString ( ) ; } ) ; return id ; } ) ; return { allIds , byId , updatedAt : updatedAt || new Date ( ) . toISOString ( ) } ; } export function normalizeInstallations ( installations ) { const items = _ . orderBy ( ( installations || [ ] ) . filter ( Boolean ) , [ 'account.login' , 'asc' , ] ) ; const allIds = [ ] ; const allOwnerNames = [ ] ; const byId = { } ; const byOwnerName = { } ; items . forEach ( ( installation ) => { if ( ! ( installation && installation . id ) ) return ; allIds . push ( installation . id ) ; byId [ installation . id ] = installation ; const ownerName = normalizeUsername ( ( installation . account && installation . account . login ) || undefined ) ; if ( ownerName ) { allOwnerNames . push ( ownerName ) ; byOwnerName [ ownerName ] = installation . id ; } } ) ; return { allIds : _ . uniq ( allIds ) , allOwnerNames : _ . uniq ( allOwnerNames ) , byId , byOwnerName , } ; }