Introduction
In this blog, we will learn to perform Create, Read and Update operations using factory methods in the SharePoint Framework (SPFx).
A Factory Pattern or Factory Method Pattern defines an interface or abstract class for creating an object, but lets the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.
The Advantage of Factory Design Pattern Factory Method Pattern is that it allows the sub-classes to choose the type of objects to create. It also promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class so that it will work with any classes that implement that interface or that extend the abstract class.
To start with, we require an interface or abstract class to define for our methods. In my example, I have defined my interface class as "
IFactory.ts" as shown below. Method body is defined in "
ListItemFactory.ts"
IFactory.ts
Install @microsoft/sp-http to your .ts file as shown below.
- npm install --save @microsoft/sp-http
Import
@microsoft/sp-http to your .ts file as shown below.
- import * as pnp from "@microsoft/sp-http";
- import { SPHttpClient, SPHttpClientResponse } from "@microsoft/sp-http";
- export interface IFactory {
- getItems(requester: SPHttpClient, siteUrl: string, listName: string, params: string, oListItemID: string): Promise<any[]>;
- addItems(requester: SPHttpClient, siteUrl: string, listName: string, body:string): Promise<any[]>;
- updateItems(requester: SPHttpClient, siteUrl: string, listName: string, oListItemID: string, body:string): Promise<any[]>;
- }
ListItemFactory.ts
Install Jquery and @microsoft/sp-http to your .ts file as shown below.
- npm install --save @microsoft/sp-http
- npm install --save jquery
Import
@microsoft/sp-http and Jquery to your .ts file as shown below.
- import * as pnp from "@microsoft/sp-http";
- import $ from "jquery";
- import { SPHttpClient, SPHttpClientResponse } from "@microsoft/sp-http";
- import { IFactory } from "../factory/IFactory";
- import $ from 'jquery';
-
- export class ListItemFactory implements IFactory {
-
-
- public async getItems(requester: SPHttpClient, siteUrl: string, listName: string, params: string, oListItemID: string): Promise<any[]> {
- try {
- return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items(${oListItemID})?${params}`,
- SPHttpClient.configurations.v1,
- {
- headers: {
- "Accept": "application/json;odata=verbose",
- "odata-version": ""
- }
- })
- .then((response: SPHttpClientResponse) => {
- return response.json();
- })
- .then((json) => {
- return json;
- });
-
- } catch (error) {
- console.log(`Error occured in getItems method in ListFactory.ts. Error message: ${error.message}`);
- throw error;
- }
- }
-
- public addItems(requester: SPHttpClient, siteUrl: string, listName: string, body:string): Promise<any[]>{
- try{
- return requester.post(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items`,
- SPHttpClient.configurations.v1,
- {
- headers: {
- "Accept": "application/json;odata=verbose",
- 'Content-type': 'application/json;odata=verbose',
- "odata-version": ""
- },
- body: body
- })
- .then((response: SPHttpClientResponse) => {
- return response.json();
- })
- .then((json) => {
- return(json);
- });
-
- }catch(error){
- console.log(`Error occured in addItems method in ListFactory.ts. Error message: ${error.message}`);
- throw error;
- }
- }
-
- public updateItems(requester: SPHttpClient, siteUrl: string, listName: string, oListItemID: string, body:string): Promise<any[]>{
- try {
- return requester.post(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items(${oListItemID})`,
- SPHttpClient.configurations.v1,
- {
- headers: {
- "Accept": "application/json;odata=verbose",
- 'Content-type': 'application/json;odata=verbose',
- "odata-version": "",
- 'IF-MATCH': '*',
- 'X-HTTP-Method': 'MERGE'
- },
- body: body
- })
- .then((response: SPHttpClientResponse): any => {
- return true;
- },(error: any): any => {
- return false;
- });;
- } catch (error) {
- console.log(`Error occured in updateItems method in ListFactory.ts. Error message: ${error.message}`);
- throw error;
- }
- }
- }
Usage : Import "ListItemFactory.ts" to your .tsx file as shown below.
- import { ListItemFactory} from "../ListItemFactory";
Intitiate your class as shown below:
- const factory: ListItemFactory = new ListItemFactory();
Create - To Insert items to sharepoint list.
Parameter : SPHttpClient,SiteURL, ListName and ListItemID.
-
- private insertItemsToSharePointList(): void {
- try {
- const body = this.loadNCMRBody();
- factory.addItems(this.props.spHttpClient, this.props.siteUrl, "SharePoint ListName", body)
- .then((items: any[]) => {
- if (items["d"].ID !== null) {
- alert("Item Inserted successfully");
- }
- });
- } catch (error) {
- console.log(`Error occured in insertItemsToSharePointList method in Error message: ${error.message}`);
- }
- }
-
-
- private loadNCMRBody(button:string): string {
- try {
- const body: string = JSON.stringify({
- __metadata: { 'type': "SP.Data.<ListName>ListItem" },
- Title:"Tested",
- Description: "This is to test the description"
- });
- return body;
- } catch (error) {
- console.log(`Error occured in loadActionItemBody method in Process.tsx. Error message: ${error.message}`);
- }
- }
Read - To Retrieve items to sharepoint list.
Parameter : SPHttpClient,SiteURL, ListName and ListItemID.
-
- private readItemsAndSetStatus(oListItemID) : void{
- factory.getItems(this.props.spHttpClient, this.props.siteUrl, <SharePoint ListName>, "$select=*", oListItemID)
- .then((items: any[]) => {
- this.setstate({Title:items["d"].Title,Description:items["d"].Description});
- });
- }
Update - To Update items in SharePoint list.
Parameter : SPHttpClient,SiteURL, ListName and ListItemID.
-
- private updateItemsToSharePointList(): void {
- try {
- const body = this.loadNCMRBody();
- factory.updateItems(this.props.spHttpClient, this.props.siteUrl, "SharePoint ListName", body)
- .then((items: any) => {
- if (items) {
- alert("Item updated successfully");
- }
- });
- } catch (error) {
- console.log(`Error occured in updateItemsToSharePointList method in Error message: ${error.message}`);
- }
- }
-
-
- private loadNCMRBody(button:string): string {
- try {
- const body: string = JSON.stringify({
- __metadata: { 'type': "SP.Data.<ListName>ListItem" },
- Title:"Item Updated",
- Description: "This is to test the update method"
- });
- return body;
- } catch (error) {
- console.log(`Error occured in loadActionItemBody method in Process.tsx. Error message: ${error.message}`);
- }
- }
Please feel free to share your comments.
Hope this helps!!!!!