0.1.30 • Published 5 years ago

spjsomfluent v0.1.30

Weekly downloads
-
License
MIT
Repository
-
Last release
5 years ago

spJsomFluent

spJsom is a library that simplies usage of the SharePoint Client Side Object Model (JavaScript/JSOM). Using a fluent API, the library allows chaining multiple commands together with conditions and progress monitoring. Goals of this library are:

  • Simply using the CSOM
  • Avoid nesting promises
  • Reduce boiler plate code
  • Provide an easy to read syntax
  • Speed up development

This solution can be used in TypeScript or plain JavaScript projects.

Repository: https://github.com/TjWheeler/spJsomFluent

Examples

A quick example

In this example we are get getting the current user profile properties. All the difficulty behind loading the correct scripts and calling the PeopleManager are handled for you.

var context = SP.ClientContext.get_current();
new spJsom.Fluent()
    .withContext(context)
    .user.getCurrentUserProfileProperties()
    .execute()
    .fail(function(sender, args) {
        console.error(args.get_message());
    })
    .done(function(results) {
        console.log(results);
        console.log("Your profile properties", results[0].result[0]);
    });

TypeScript Examples

For more examples, including more complex scenarios with multiple commands, see TypeScript examples

JavaScript Examples

Coming soon!

Dependencies

jQuery must be loaded as the library uses jQuery Promises.

Usage

Install - npm

npm i spjsomfluent --save

Importing spJsom

import * as spJsom from "spjsomfluent"

Development commands - NodeJs

Install modules

npm install

Run the dev build

npm run debug

Run the production build

npm run release

Watch the dev configuration, and recompile as files change

npm run dev

Getting started using the sample app for TypeScript and WebPack

  1. Clone the repository and copy the sampleApp folder to your own location. git clone https://github.com/TjWheeler/spJsomFluent
  2. run npm install from the sampleApp folder you copied using a Node Shell
  3. run npm run debug to build the sample app. (The development commands listed above are valid for this app too.)
  4. Upload the resulting .js and .js.map to SharePoint or use Fiddlers autoresponder to a location of your chosing. eg; /style library/myApp
  5. Add a script reference in a Script Editor web part: ​​​<script src="https://yoursharepoint.sharepoint.com/sites/yoursite/style library/myApp/myApp.js"></script>
  6. Modify the app as needed (use npm run dev to watch the file updates you make and immediately rebuild)

Note: The default sample app is designed to create a List called MyList1 and a single list item.
Once the script is loaded, it will execute as soon as SP.js is loaded.

Events

To monitor activity there are 2 events you can wire up to. These are: 1. onExecuting(commandName, step, totalSteps) 2. onExecuted(commandName, success, results)

onExecuting

To show progress, this method will give you the details you need.

.onActionExecuting((actionName:string, current:number, total:number) => {
    let progress = Math.ceil(100 * current / total);
    console.log(`Executing: ${actionName}, we are ${progress}% through.`);
})
            

onExecuted

.onActionExecuted((actionName:string, success:boolean, results: Array<any>) => {
    console.log(`Executed: ${actionName}:${success}`);
    if (!success) {
        console.error(actionName, results);
    }
})

Commands

whenTrue & whenFalse

These commands .whenTrue() and .whenFalse() are a conditional check. They take the value from the previous step then compare it with True/False to determine if execution of the chain should continue. For example:

.permission.hasWebPermission(SP.PermissionKind.createSSCSite, context.get_web())
.whenTrue() //stops executing the chain if the user doesn't have permission

Note that the when commands do not reject a promise even when their condition is not met. The chain of execution simply stops at that point.

when

You can supply your own predicate to determine if execution of the chain should continue.
For example:

.listItem.get(context.get_web(), "MyList", 1)
.when(function(listItem) {
	if(listItem.get_item("Title") === "My Title") {
		return true; //the chain execution will continue
	} 
	return false; //the chain execution will stop
})

The result of the previous step is passed into the when predicate allowing you the opportunity to evaluate the result and continue or stop.

whenAll

Similar to when, but instead of the previous steps result being passed in, an array with all previous steps are passed to the predicate.

...
.listItem.get(context.get_web(), "MyList", 1)
.whenAll(function(results) {
	var listItem = results[0];
	if(listItem.get_item("Title") === "My Title") {
		return true; //the chain execution will continue
	} 
	return false; //the chain execution will stop
})

File Commands

Fluent API spJsom.file

CommandResultDescriptionExample
get(serverRelativeUrl: string)SP.FileGet a file from a document libraryget(_spPageContextInfo.siteServerRelativeUrl + "/documents/doc.docx")
getListItem(serverRelativeUrl: string)SP.ListItemGet the list item for the filegetListItem(_spPageContextInfo.siteServerRelativeUrl + "/documents/doc.docx")
checkIn(web: SP.Web, serverRelativeUrl: string, comment: string, checkInType: SP.CheckinType)SP.FileCheck in a filecheckIn(SP.ClientContext.get_current().get_web(), _spPageContextInfo.webServerRelativeUrl + '/pages/mypage.aspx', "Checked in by spJsomFluent", SP.CheckinType.majorCheckIn)

List Commands

Fluent API spJsom.list

CommandResultDescriptionExample
create(web: SP.Web, listName: string, templateId: number)SP.ListCreate new listcreate(context.get_web(), "My Task List", 107)
exists(web: SP.Web, listName: string)booleanCheck if the list existsexists(context.get_web(), "My List")
delete(web: SP.Web, listName: string)voidDelete a listdelete(context.get_web(), "My List")
get(web: SP.Web, listName: string)SP.ListGet a listget(context.get_web(), "My List")
addContentTypeListAssociation(web: SP.Web, listName: string, contentTypeName: string)SP.ContentTypeAdds a Content Type to a List. Resolves the new associated list content type.addContentTypeListAssociation(context.get_web(), "My List", "My Content Type Name")
removeContentTypeListAssociation(web: SP.Web, listName: string, contentTypeName: string)voidRemoves a Content Type associated from a list.removeContentTypeListAssociation(context.get_web(), "My List", "My Content Type Name")
setDefaultValueOnList(web: SP.Web, listName: string, fieldInternalName: string, defaultValue: any)voidSets a default value on a field in a listsetDefaultValueOnList(context.get_web(), "My Task List", "ClientId", 123)
setAlerts(web: SP.Web, listName: string, enabled: boolean)voidEnable email alerts on a list. Note: will not work for 2010/2013.setAlerts(context.get_web(), "My Task List", true)

ListItem Commands

Fluent API spJsom.listItem

CommandResultDescriptionExample
update(listItem: SP.ListItem, properties: any)SP.ListItemUpdate a list item with propertiesupdate(listItem, { 'Title': 'Title value here', ClientId: 123 })
createWithContentType(web: SP.Web, listName: string, contentTypeName: string, properties: any)SP.ListItemCreate a list item, specifying the Content TypecreateWithContentType(context.get_web(), "My list", "My Content Type Name", { 'Title': 'Title value here', ClientId: 123 })
create(web:SP.Web, listName: string, properties: any)SP.ListItemCreate a list item with propertiesupdate(listItem, { 'Title': 'Title value here', ClientId: 123 })
get(web: SP.Web, listName: string, id: number, viewFields: Array = null)SP.ListItemGet the listitem using the ID with optional view fieldsget(context.get_web(), "MyList", 1, "ID", "Title")
getFileListItem(serverRelativeUrl: string, viewFields: Array = null)SP.ListItemGet the listitem for a File using the ID with optional view fieldsgetFileListItem("/sites/site/documents/mydoc.docx", "ID", "Title", "FileLeafRef")
deleteById(web: SP.Web, listName: string, id: number)voidDelete List ItemdeleteById(context.get_web(), "MyList", 7)
query(web: SP.Web, listName: string, viewXml: string)SP.ListItemCollectionExecute a query using supplied CAML.query(context.get_web(), "MyList", "12")

Navigation Commands

Fluent API spJsom.navigation

CommandResultDescriptionExample
createNode(web: SP.Web, location: NavigationLocation, title: string, url: string, asLastNode: boolean = true)SP.NavigationNodeCreate new navigation nodecreateNode(context.get_web(), NavigationLocation.Quicklaunch, "Test Node", "/sites/mysite/pages/default.aspx")
deleteAllNodes(web: SP.Web, location: NavigationLocation)voidDelete all navigation nodes for the webdeleteAllNodes(context.get_web(), NavigationLocation.Quicklaunch)
deleteNode(web: SP.Web, location: NavigationLocation, title:string )voidDelete all navigation nodes that match the supplied title for the webdeleteNode(context.get_web(), NavigationLocation.Quicklaunch, "My link title")
setCurrentNavigation(web: SP.Web, type: NavigationType, showSubsites: boolean = false, showPages:boolean = false)voidSet navigation for the websetCurrentNavigation(context.get_web(), 3, true, true)

Note: Taxonomy based navigation is not currently supported

Permission Commands

Fluent API spJsom.permission

CommandResultDescriptionExample
hasWebPermission(permission: SP.PermissionKind, web: SP.Web)booleanCheck if the current user has specified Web permissionhasWebPermission(SP.PermissionKind.createSSCSite, context.get_web())
hasListPermission(permission: SP.PermissionKind, list: SP.List)booleanCheck if the current user has specified List permissionhasListPermission(SP.PermissionKind.addListItems, context.get_web().get_lists().getByTitle("MyList"))
hasItemPermission(permission: SP.PermissionKind, item: SP.ListItem)booleanCheck if the current user has specified ListItem permissionhasItemPermission(SP.PermissionKind.editListItems, context.get_web().get_lists().getByTitle("MyList").getItemById(0))

Fluent API spJsom.web

Publishing Page Commands

Fluent API spJsom.publishingPage

CommandResultDescriptionExample
create(web: SP.Web, name: string, layoutUrl: string)SP.Publishing.PublishingPageCreates a new publishing page..publishingPage.create(SP.ClientContext.GetCurrent().get_web(), "Home.aspx", _spPageContextInfo.siteServerRelativeUrl + "/_catalogs/masterpage/BlankWebPartPage.aspx")
getLayout(serverRelativeUrl:string)SP.ListItemGets a page layout

User Commands

Fluent API spJsom.user

CommandResultDescriptionExample
get(emailOrAccountName:string)SP.UserGet User by email or account nameget("my@email.address")
getById(id: number)SP.UserGet a user by their IdgetById(15)
getCurrentUser()SP.UserGet the current usergetCurrentUser()
getCurrentUserProfileProperties()SP.UserProfiles.PersonPropertiesGet the profile properties for the current usergetCurrentUserProfileProperties()
getCurrentUserManager()SP.USerGet the manager for the current usergetCurrentUserManager()

Web Commands

CommandResultDescriptionExample
setWelcomePage(web: SP.Web, url: string)SP.FolderSet the web welcome page. The url should be relative to the root folder of the web.setWelcomePage(context.get_web(), "pages/default.aspx")
create(name: string, parentWeb: SP.Web, title: string, template: string, useSamePermissionsAsParent: boolean = true)SP.WebCreate a new sub web.create("SubWebName", SP.ClientContext.get_current().get_rootWeb(), "My Web Title", "CMSPUBLISHING#0")
exists(url: string)booleanCheck if a web existsexists("/sites/myweb/mysubweb")
getWebs(fromWeb: SP.Web)Array<SP.Web>Get and load all webs starting from a web and its childrengetWebs(SP.ClientContext.get_current().get_rootWeb()))

Note: for template ids check out: See: https://blogs.technet.microsoft.com/praveenh/2010/10/21/sharepoint-templates-and-their-ids/

0.1.30

5 years ago

0.1.29

5 years ago

0.1.28

5 years ago

0.1.27

5 years ago

0.1.25

5 years ago

0.1.24

5 years ago

0.1.22

5 years ago

0.1.21

5 years ago

0.1.20

5 years ago

0.1.19

5 years ago

0.1.18

5 years ago

0.1.17

5 years ago

0.1.16

5 years ago

0.1.15

5 years ago

0.1.14

5 years ago

0.1.12

5 years ago

0.1.11

5 years ago

0.1.10

5 years ago

0.1.9

5 years ago

0.1.8

5 years ago

0.1.7

5 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago

0.0.11

5 years ago

0.0.10

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago