Last active
September 16, 2020 10:39
-
-
Save phillipharding/6fd5622bf1ec45bc08c79373c65abb7d to your computer and use it in GitHub Desktop.
Create new ClientsidePage using PnPJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { sp, ClientsidePageFromFile, PromotedState, IListItemFormUpdateValue, IClientsidePage, IFileInfo } from "@pnp/sp/presets/all"; | |
console.clear(); | |
function SafeFilename(fileName: string, convertToLower?: boolean): string { | |
const name = (fileName || "") | |
.replace(/[^ a-zA-Z0-9-_]*/gi, "") | |
.replace(/ /gi, "-") | |
.replace(/-*$/gi, "") | |
.replace(/[-]{2,}/gi, "-"); | |
return convertToLower ? name.toLowerCase() : name; | |
} | |
(async () => { | |
console.clear(); | |
const web = await sp.web.select("Title")() | |
console.log("Web Title: ", web.Title); | |
const currentWebUrl = "/sites/newsandeventscentre"; | |
//const currentWebUrl = "/sites/ICC_corporatedemocraticservices"; | |
/* get the source page from the page template URL */ | |
//const basicSourceTemplate = `${currentWebUrl}/sitepages/templates/Basic-Intranet-Content-Page.aspx`; | |
//const extendedSourceTemplate = `${currentWebUrl}/sitepages/templates/Extended-Intranet-Content-Page.aspx`; | |
const extendedSourceTemplate = `${currentWebUrl}/sitepages/templates/Basic-Intranet-News-Page.aspx`; | |
const sourcePageFile = sp.web.getFileByServerRelativeUrl(extendedSourceTemplate); | |
const sourcePageFileInfo = await sourcePageFile.select("*", "FileRef", "FileDirRef", "FileLeafRef").get(); | |
const sourcePageFileListItem = await sourcePageFile.listItemAllFields.select("*", "FileRef", "FileDirRef", "FileLeafRef").get(); | |
console.log("sourcePageFileInfo: ", {...sourcePageFileInfo}); | |
console.log("sourcePageFileListItem: ", sourcePageFileListItem); | |
const sourcePageContentData = { | |
ServerRelativeUrl: sourcePageFileInfo.ServerRelativeUrl, | |
Id: (sourcePageFileListItem as any).Id || (sourcePageFileListItem as any).ID, | |
Title: (sourcePageFileListItem as any).Title, | |
ContentTypeId: (sourcePageFileListItem as any).ContentTypeId, | |
intCouncilservicearea: (sourcePageFileListItem as any).intCouncilservicearea || undefined, | |
intContentresourcerole: (sourcePageFileListItem as any).intContentresourcerole || undefined, | |
intContentresourcetype: (sourcePageFileListItem as any).intContentresourcetype || undefined, | |
intNewscategory: (sourcePageFileListItem as any).intNewscategory || undefined, | |
intShowinspotlight: (sourcePageFileListItem as any).intShowinspotlight || undefined, | |
intNewscontentstatus: (sourcePageFileListItem as any).intNewscontentstatus || undefined, | |
intContentresourceowners: (sourcePageFileListItem as any).intContentresourceownerId || [], | |
}; | |
console.log("sourcePageContentData: ", sourcePageContentData); | |
/* create a client-side page from the source file */ | |
const sourcePage: IClientsidePage = await ClientsidePageFromFile(sourcePageFile); | |
console.log("sourcePage::> ", sourcePage); | |
console.log("sourcePage (json data)::> ", (sourcePage as any).json); | |
const random = `${Math.ceil(Math.random()*1000000)}`; | |
const newTitle = `Sample PKC News Content Post Number ${random}`; | |
//const newTitle = `Sample PKC Intranet Content Page Number #${random}`; | |
const newFilename = SafeFilename(newTitle, true); | |
/* create a new client-side page from the the source page */ | |
const copiedPage: IClientsidePage = await sourcePage.copy(sp.web, `${newFilename}`, `${newTitle}`, false, PromotedState.NotPromoted); | |
console.log("copiedPage::> ", copiedPage); | |
/* const copiedPageListItem = await copiedPage.getItem("*", "FileRef", "FileDirRef", "FileLeafRef"); */ | |
const copiedPageListItem = (copiedPage as any).json; | |
console.log("copiedPageListItem::> ", copiedPageListItem); | |
/* now update the listitem field properties for the new page */ | |
let sourceResourceOwners = []; | |
/* resolve content owners */ | |
for(let idx = 0; idx < sourcePageContentData.intContentresourceowners.length; idx++) { | |
const uid = sourcePageContentData.intContentresourceowners[idx]; | |
const user = await sp.web.getUserById(uid).get(); | |
console.log(`resolveResourceOwner: ${uid} --> [${user.Id}] ${user.LoginName}`); | |
if (user && user.LoginName) { | |
sourceResourceOwners.push({ Key: `${user.LoginName}` }); | |
} | |
} | |
let newPageValues: IListItemFormUpdateValue[] = [ | |
{ FieldName: "ContentTypeId", FieldValue: `${sourcePageContentData.ContentTypeId}` }, | |
]; | |
if (sourceResourceOwners && sourceResourceOwners.length) { | |
newPageValues.push({ FieldName: "intContentresourceowner", FieldValue: `${JSON.stringify(sourceResourceOwners)}` }); | |
} | |
if (sourcePageContentData.ContentTypeId.match(/0x0101009D1CB255DA76424F860D91F20E6C411800D76F1B3894D83144ADEE6BD6B1FCE10F/gi)) { | |
/* intranet content */ | |
const resourceRoleValue = (sourcePageContentData.intContentresourcerole || []).map( (role: any) => { | |
return `${role.Label}|-1|${role.TermGuid}`; | |
} ); | |
console.log("resourceRoleValue::> ", resourceRoleValue.join(";#")); | |
newPageValues = newPageValues.concat([ | |
{ FieldName: "intCouncilservicearea", FieldValue: `${sourcePageContentData.intCouncilservicearea.Label}|-1|${sourcePageContentData.intCouncilservicearea.TermGuid}` }, | |
{ FieldName: "intContentresourcerole", FieldValue: `${resourceRoleValue.join(";#")}` }, | |
{ FieldName: "intContentresourcetype", FieldValue: `${sourcePageContentData.intContentresourcetype.Label}|-1|${sourcePageContentData.intContentresourcetype.TermGuid}` } | |
]); | |
} else if (sourcePageContentData.ContentTypeId.match(/0x0101009D1CB255DA76424F860D91F20E6C411800A99ACF397B2C60429DB5FF8217451DF2/gi)) { | |
/* news */ | |
newPageValues = newPageValues.concat([ | |
{ FieldName: "intNewscategory", FieldValue: `${sourcePageContentData.intNewscategory}` }, | |
{ FieldName: "intShowinspotlight", FieldValue: `${sourcePageContentData.intShowinspotlight ? "1" : "0"}` }, | |
{ FieldName: "intNewscontentstatus", FieldValue: `${sourcePageContentData.intNewscontentstatus}` } | |
]); | |
} | |
console.log("copiedPage ::> newPageValues::> ", newPageValues); | |
const updatedPageValues = await sp.web.getList(`${currentWebUrl}/sitepages`).items.getById(copiedPageListItem.Id).validateUpdateListItem([ | |
...newPageValues | |
], true); | |
console.log("copiedPage ::> updatedPageValues::> ", updatedPageValues); | |
const updatedFileGetter = sp.web.getList(`${currentWebUrl}/sitepages`).items.getById(copiedPageListItem.Id).file; | |
/* retrieve updated new page file */ | |
let newPageUpdatedFile: IFileInfo = await updatedFileGetter.select("*", "FileRef", "FileDirRef", "FileLeafRef").get(); | |
console.log("copiedPage ::> newPageUpdatedFile::> ", newPageUpdatedFile); | |
/* IF MOVING: move new page file to another folder */ | |
const moveToUrl = `${currentWebUrl}/sitepages/Other/${newPageUpdatedFile.Name}`; | |
// const mover = await updatedFileGetter.moveTo(moveToUrl); | |
// console.log(`moveTo::> ${moveToUrl}`, mover); | |
/* IF MOVING: retrieve new page file possiblt moved to a new location) */ | |
newPageUpdatedFile = await updatedFileGetter.select("*", "FileRef", "FileDirRef", "FileLeafRef").get(); | |
console.log("movedPage ::> ", newPageUpdatedFile); | |
})().catch(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment