SenseNet / sn-client-js

A JavaScript client for sensenet ECM that makes it easy to use the REST API of the Content Repository.
https://www.sensenet.com/
GNU General Public License v2.0
11 stars 2 forks source link
ecms javascript sensenet typescript

sn-client-js


This package is not under active development. You can find our latest packages in the sensenset/sn-client monorepo.


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

sn-client-js has been refactored into several smaller packages within the @sensenet scope in NPM, therefore sn-client-js will not be updated. Please switch to the @sensenet scoped packages if possible. You can find more details in this post

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
        });

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

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:

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:

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