This is an abstract class that makes it easy to create models based on SharePoint list items in TypeScript. It is made for use with the SharePoint Framework and Node.js and uses the SharePoint pnp-js.
Import the dependencies:
import {SPListItemModel, SPList, SPField} from "sp-list-item-model"
Create a class that extends SPListItemModel
and decorate it with @SPList(ListName: string, SiteURL: string)
SiteURL
is optional and defaults to the site that is the current execution context.
The fields with the @SPField(InternalName: string)
decorator represent fields in the list item. InternalName
is optional and defaults to the class property name. If the internal name of the field is different from your property name, then specify it here.
@SPList("employees", "https://mysite.sharepoint.com")
class Employee extends SPListItemModel {
@SPField()
Name: string
@SPField()
Address: string
@SPField()
Salary: number
@SPField("aabbcc")
HiredOn: Date
//Add your own methods or properties
NotASharePointField: string
SomeMethod(): void {
//do something
}
}
let e = new Employee();
e.Name = "John Doe";
e.Address = "123 Some Street";
e.Salary = 50000;
e.HiredOn = new Date();
e.submit()
.then(()=>console.log("Item created"))
Employee.getItemById(123)
.then(e=>console.log(e.Name))
Employee.getAllItems()
.then(employees=>{
employees.forEach(employee=>console.log(employee.Name))
})
Employee.getItemsByFilter(`${Employee.getInternalName("Salary")} Ge 5000`)
.then(employees=>{
employees.forEach(employee=>console.log(employee.Name))
})
Note: the submit
method checks if the fields you are updating have been changed since the item was loaded, and if so, will reject the promise. If you do not want this, then you can call e.submit(false)
.
Employee.getItemById(123)
.then(e=>{
e.Name = "Joe Bloggs";
return e.submit();
})
.then(()=>console.log("Updated"))
let e = new Employee();
e.ID=123;
e.Name = "Joe Bloggs";
e.submit()
.then(()=>console.log("Updated"));
Employee.deleteItemById(123)
.then(()=>{
//do something
})
If you are accessing SharePoint data from the Sharepoint Framework, then this will be done on behalf of the currently authenticated user, so authentication is not needed. If you want to access data from Node.JS you will need to authenticate. You can use pnp-auth for this (see the documentation for pnp-auth for instructions).