import { IHubRequestOptions , IModelTemplate , serializeModel , uploadResourcesFromUrl , getWithDefault , IItemResource , IModel } from "@esri/hub-common" ; import { ensureRequiredPageProperties } from "./ensure-required-page-properties" ; import { linkSiteAndPage } from "../link-site-and-page" ; import { createItem , protectItem , shareItemWithGroup , ISharingResponse } from "@esri/arcgis-rest-portal" ; param { Object } model param { Object } options param { IHubRequestOptions } hubRequestOptions export function createPage ( model , options , hubRequestOptions ) { if ( ! hubRequestOptions . authentication ) { throw new Error ( `createPage must be passed hubRequestOptions.authentication` ) ; } const newPage = ensureRequiredPageProperties ( model , { username : hubRequestOptions . authentication . username , isPortal : hubRequestOptions . isPortal } ) ; const serializedModel = serializeModel ( newPage ) ; return createItem ( { item : serializedModel , owner : newPage . item . owner , authentication : hubRequestOptions . authentication } ) . then ( createResponse => { newPage . item . id = createResponse . id ; return protectItem ( { id : newPage . item . id , owner : newPage . item . owner , authentication : hubRequestOptions . authentication } ) ; } ) . then ( protectReponse => { let sharingPromises = [ ] ; if ( Array . isArray ( options . shareTo ) && options . shareTo . length ) { sharingPromises = options . shareTo . map ( ( groupInfo ) => { return shareItemWithGroup ( { id : newPage . item . id , groupId : groupInfo . id , authentication : hubRequestOptions . authentication , confirmItemControl : groupInfo . confirmItemControl || false } ) ; } ) ; newPage . item . access = "shared" ; } return Promise . all ( sharingPromises ) ; } ) . then ( response => { const sites = getWithDefault ( newPage , "data.values.sites" , [ ] ) ; const requestOptions = { authentication : hubRequestOptions . authentication } ; return Promise . all ( sites . map ( ( entry ) => { const opts = Object . assign ( { siteId : entry . id , pageModel : newPage } , requestOptions ) ; return linkSiteAndPage ( opts ) ; } ) ) ; } ) . then ( siteLinkingResponse => { const assets = getWithDefault ( options , "assets" , [ ] ) as IItemResource [ ] ; return uploadResourcesFromUrl ( newPage , assets , hubRequestOptions ) ; } ) . then ( ( ) => newPage ) . catch ( err => { throw Error ( `createPage: Error creating page: ${ err }` ) ; } ) ; }