npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sn-client-js

v3.0.3

Published

A JavaScript client for Sense/Net ECM that makes it easy to use the REST API of the Content Repository.

Downloads

2,603

Readme

sn-client-js

Gitter chat Build status Coverage Codacy Badge NPM version NPM downloads License semantic-release Commitizen friendly Greenkeeper badge

This component lets you work with the sensenet ECM Content Repository (create or manage content, execute queries, etc.) by providing a JavaScript client API for the main content operations. The library connects to a sensenet ECM portal's REST API, but hides the underlying HTTP requests. You can work with simple load or create Content operations in JavaScript, instead of having to construct ajax requests yourself.

It also provides you the full sensenet Content Type system hierarchy through Typescript classes with all the fields defined in the CTDs and the Content Type schemas with FieldSettings so that you can manage Content easy on client-side knowing the related fields and their settings.

Tested with the following Sense/Net Services version:

Sense/Net Services

Installation with node and npm

To install the latest stable version run

npm install --save sn-client-js

Usage

Creating a Repository instance

Your main entry point in this library is the Repository object. You can create an Instance by the following way:

import { Repository } from 'sn-client-js';

let repository = new Repository.SnRepository({
            RepositoryUrl: 'https://my-sensenet-site.com',
            ODataToken: 'OData.svc',
            JwtTokenKeyTemplate: 'my-${tokenName}-token-for-${siteName}',
            JwtTokenPersist: 'expiration',
			DefaultSelect: ['DisplayName', 'Icon'],
			RequiredSelect: ['Id', 'Type', 'Path', 'Name'],
			DefaultMetadata: 'no',
			DefaultInlineCount: 'allpages',
			DefaultExpand: [],
			DefaultTop: 1000
        });
  • RepositoryURL: The component will communicate with your repositoy using the following url. This will fall back to your window.location.href, if not specified. To enable your external app to send request against your sensenet portal change your Portal.settings. For further information about cross-origin resource sharing in sensenet check this article.
  • ODataToken: Check your Sense/Net portal's web.config and if the ODataServiceToken is set, you can configure it here for the client side.
  • JwtTokenKeyTemplate - This will be the template how your JWT tokens will be stored (in local/session storage or as a cookie). ${tokenName} will be replaced with the token's name ('access' or 'refresh'), ${siteName} will be replaced with your site's name
  • JwtTokenPersist - You can change how JWT Tokens should be persisted on the client, you can use 'session', whitch means the token will be invalidated on browser close, or 'expiration', in that case the token expiration property will be used (See JWT Token docs for further details)
  • DefaultSelect - These fields will be selected by default on each OData request. Can be a field, an array of fields or 'all'
  • RequiredSelect - These fields will always be included in the OData $select statement. Also can be a field, an array of fields or 'all'
  • DefaultMetadata - Default metadata value for OData requests. Can be 'full', 'minimal' or 'no'
  • DefaultInlineCount - Default inlinecount OData parameter. Can be 'allpages' or 'none'
  • DefaultExpand - Default fields to $expand, empty by default. Can be a field or an array of fields.
  • DefaultTop - Default value to the odata $top parameter

Create, Save, Update

You can create a new content instance in the following way:

import { ContentTypes } from 'sn-client-js';

let myTask = repository.CreateContent({
		Name: 'MyTask',
		Path: '/Root/MyWorkspace/MyTaskList'
	},
	ContentTypes.Task);

The content is not posted to the Reposiory yet, but you can bind it to a Create content form and update it's values like this:

myTask.DueDate = "2017-09-12T12:00:00Z";

You can always check if a specified content has been saved or not with the content.IsSaved property.

If you've finished with the editing, you can Save it the following way:

myTask.Save().subscribe(task=>{
	console.log('Task saved', task);
}, error => console.error);

Once the Task has been saved, you can continue working on the same object reference, update fields and call myTask.Save() again, the content will be updated in the sensenet ECM Repository.

If you want to update a specified field only, you can do that with an optional Save() parameter (other changed properties will be ignored):

myTask.Save({DisplayName: 'Updated Task Displayname'}).subscribe(task=>{
	console.log('Task saved', task);
}, error => console.error)

Load, Reload

You can load a content instance from the repository by the following way:

//by Path
repository.Load('Root/MyWorkspace/MyTaskList/MyTask1').subscribe(loadedTask=>{
	console.log('Task loaded', loadedTask);
}, error => console.error);

//or by Id
let myTaskId = 12345
repository.Load(myTaskId).subscribe(loadedTask=>{
	console.log('Task loaded', loadedTask);
}, error => console.error);

//you can also specify which fields you want to load or expand
repository.Load(myTaskId, {
	select: ['Name', 'DisplayName'],
	expand: 'Owner'
}).subscribe(loadedTask => {
	console.log('Task loaded', loadedTask);
}, error => console.error);

If you load or reload the same content from the same repository, you will get the same object reference

If you use Schema definition and you need to reload a content for a specified action (can be 'view' or 'edit' for now) you can do that with:

myTask.Reload('view').subscribe(reloadedTask=>{
	console.log('Task reloaded', reloadedTask);
}, error => console.error)

If you want to reload only specific fields or references, you can do that in the following way:

myTask.ReloadFields('Owner', 'Name', 'ModifiedBy').subscribe(reloadedTask=>{
	console.log('Fields loaded', reloadedTask);
}, error => console.error)

Reference fields

You can query reference fields like the following:

myTask.CreatedBy.GetContent().subscribe(createdBy => {
	console.log('Task is created by', createdBy);
});

Reference fields are loaded lazily. This means that if their value isn't loaded yet, it will make an additional HTTP request. If you know exactly what reference fields will be used, call content.Reload('view' | 'edit') or content.ReloadFields(...fields) to speed things up.

Delete

If you want to delete a content permanently (or just move it to the Trash folder), you can simply call:

let permanently = false;
myTask.Delete(permanently).subscribe(()=>{
	console.log('Moved to trash.');
}, err=> console.error);

Tracking changes

There are several methods to track the state of content instances

  • content.IsSaved - Shows if the content is just created or is saved to the Repository
  • content.IsDirty - Indicates if some of its fields has changed
  • content.IsValid - Indicates if all complusory fields has been filled
  • content.SavedFields - Returns an object with the last saved fields
  • content.GetChanges() - Returns an object with the changed fields and their new values

If the content is partially loaded, only their loaded fields or references will be tracked.

Hierarchical content comparison

As sensenet ECM stores content in a tree-based repository, there are some methods for hierarchical comparison between content. These methods are:

  • content.IsParentOf(childContent: Content): boolean
  • content.IsChildOf(parentContent: Content): boolean
  • content.IsAncestorOf(descendantContent: Content): boolean
  • content.IsDescendantOf(ancestorContent: Content): boolean

Repository events

There are some Event Observables on the Repository level which you can subscribe for tracking changes. You can find them on the repository.Events namespace. They are:

  • OnContentCreated
  • OnContentCreateFailed
  • OnContentModified
  • OnContentModificationFailed
  • OnContentLoaded
  • OnContentDeleted
  • OnContentDeleteFailed
  • OnContentMoved
  • OnContentMoveFailed
  • OnCustomActionExecuted
  • OnCustomActionFailed

Content Queries

You can run queries from a repository instance or from a content instance. There is a fluent API for creating type safe and valid Content Queries

const query = repository.CreateQuery(q => 
	q.TypeIs(ContentTypes.Folder)
		.And
		.Equals('DisplayName', 'a*')
		.Top(10));

query.Exec()
	.subscribe(res => {
    	console.log('Folders count: ', res.Count);
    	console.log('Folders: ', res.Result);
} 

Get the Schema of the given ContentType

let schema = Content.GetSchema(ContentTypes.GenericContent);

Read Collection data


import { Collection } from 'sn-client-js';

let collection = new Collection([], repository, ContentTypes.Task);

let fetchContent = collection.Read('/NewsDemo/External', { select: 'all' }); //gets the list of  the external Articles with their Id, Type and DisplayName fields.
   fetchContent
   	.map(response => response.d.results)
    .subscribe({
    	next: response => {
     		//do something with the response
     	},
     	error: error => console.error('something wrong occurred: ' + error),
     	complete: () => console.log('done'),
	});

Delete a Content from a Collection

let deleteContent = myCollection.Remove(3);
	deleteContent
	.subscribe({
		next: response => {
			//do something after delete
		},
		error: error => console.error('something wrong occurred: ' + error),
		complete: () => console.log('done'),
	});

Building sn-client-js from source

  1. Clone the repository: git clone https://github.com/SenseNet/sn-client-js.git
  2. Go to the sn-client-js directory: cd sn-client-js
  3. Install dependencies: npm install
  4. Build the project: npm run build To run the linter and building the project, use:
npm run build

Running the unit tests

To execute all unit tests and generate the coverage report, run: npm run test

Related documents