-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
SpPnPJsCrudWebPart.ts
285 lines (260 loc) · 10.2 KB
/
SpPnPJsCrudWebPart.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import styles from './SpPnPJsCrud.module.scss';
import * as strings from 'spPnPJsCrudStrings';
import { ISpPnPJsCrudWebPartProps } from './ISpPnPJsCrudWebPartProps';
import { IListItem } from './IListItem';
import * as pnp from 'sp-pnp-js';
import { Item, ItemAddResult, ItemUpdateResult } from '../../../node_modules/sp-pnp-js/lib/sharepoint/items';
export default class SpPnPJsCrudWebPart extends BaseClientSideWebPart<ISpPnPJsCrudWebPartProps> {
protected onInit(): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (error?: any) => void): void => {
pnp.setup({
headers: {
'Accept': 'application/json;odata=nometadata'
}
});
resolve();
});
}
public render(): void {
this.domElement.innerHTML = `
<div class="${styles.spPnPJsCrud}">
<div class="${styles.container}">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<span class="ms-font-xl ms-fontColor-white">
Sample SharePoint CRUD operations using the SP PnP JS library
</span>
</div>
</div>
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<button class="${styles.button} create-Button">
<span class="${styles.label}">Create item</span>
</button>
<button class="${styles.button} read-Button">
<span class="${styles.label}">Read item</span>
</button>
</div>
</div>
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<button class="${styles.button} readall-Button">
<span class="${styles.label}">Read all items</span>
</button>
</div>
</div>
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<button class="${styles.button} update-Button">
<span class="${styles.label}">Update item</span>
</button>
<button class="${styles.button} delete-Button">
<span class="${styles.label}">Delete item</span>
</button>
</div>
</div>
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<div class="status"></div>
<ul class="items"><ul>
</div>
</div>
</div>
</div>
`;
this.updateStatus(this.listNotConfigured() ? 'Please configure list in Web Part properties' : 'Ready');
this.setButtonsState();
this.setButtonsEventHandlers();
}
private setButtonsState(): void {
const buttons: NodeListOf<Element> = this.domElement.querySelectorAll(`button.${styles.button}`);
const listNotConfigured: boolean = this.listNotConfigured();
for (let i: number = 0; i < buttons.length; i++) {
const button: Element = buttons.item(i);
if (listNotConfigured) {
button.setAttribute('disabled', 'disabled');
}
else {
button.removeAttribute('disabled');
}
}
}
private setButtonsEventHandlers(): void {
const webPart: SpPnPJsCrudWebPart = this;
this.domElement.querySelector('button.create-Button').addEventListener('click', () => { webPart.createItem(); });
this.domElement.querySelector('button.read-Button').addEventListener('click', () => { webPart.readItem(); });
this.domElement.querySelector('button.readall-Button').addEventListener('click', () => { webPart.readItems(); });
this.domElement.querySelector('button.update-Button').addEventListener('click', () => { webPart.updateItem(); });
this.domElement.querySelector('button.delete-Button').addEventListener('click', () => { webPart.deleteItem(); });
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.DataGroupName,
groupFields: [
PropertyPaneTextField('listName', {
label: strings.ListNameFieldLabel
})
]
}
]
}
]
};
}
private listNotConfigured(): boolean {
return this.properties.listName === undefined ||
this.properties.listName === null ||
this.properties.listName.length === 0;
}
private createItem(): void {
this.updateStatus('Creating item...');
pnp.sp.web.lists.getByTitle(this.properties.listName).items.add({
'Title': `Item ${new Date()}`
}).then((result: ItemAddResult): void => {
const item: IListItem = result.data as IListItem;
this.updateStatus(`Item '${item.Title}' (ID: ${item.Id}) successfully created`);
}, (error: any): void => {
this.updateStatus('Error while creating the item: ' + error);
});
}
private readItem(): void {
this.updateStatus('Loading latest items...');
this.getLatestItemId()
.then((itemId: number): Promise<IListItem> => {
if (itemId === -1) {
throw new Error('No items found in the list');
}
this.updateStatus(`Loading information about item ID: ${itemId}...`);
return pnp.sp.web.lists.getByTitle(this.properties.listName)
.items.getById(itemId).select('Title', 'Id').get();
})
.then((item: IListItem): void => {
this.updateStatus(`Item ID: ${item.Id}, Title: ${item.Title}`);
}, (error: any): void => {
this.updateStatus('Loading latest item failed with error: ' + error);
});
}
private getLatestItemId(): Promise<number> {
return new Promise<number>((resolve: (itemId: number) => void, reject: (error: any) => void): void => {
pnp.sp.web.lists.getByTitle(this.properties.listName)
.items.orderBy('Id', false).top(1).select('Id').get()
.then((items: { Id: number }[]): void => {
if (items.length === 0) {
resolve(-1);
}
else {
resolve(items[0].Id);
}
}, (error: any): void => {
reject(error);
});
});
}
private readItems(): void {
this.updateStatus('Loading all items...');
pnp.sp.web.lists.getByTitle(this.properties.listName)
.items.select('Title', 'Id').get()
.then((items: IListItem[]): void => {
this.updateStatus(`Successfully loaded ${items.length} items`, items);
}, (error: any): void => {
this.updateStatus('Loading all items failed with error: ' + error);
});
}
private updateItem(): void {
this.updateStatus('Loading latest items...');
let latestItemId: number = undefined;
let etag: string = undefined;
this.getLatestItemId()
.then((itemId: number): Promise<Item> => {
if (itemId === -1) {
throw new Error('No items found in the list');
}
latestItemId = itemId;
this.updateStatus(`Loading information about item ID: ${itemId}...`);
return pnp.sp.web.lists.getByTitle(this.properties.listName)
.items.getById(itemId).get(undefined, {
headers: {
'Accept': 'application/json;odata=minimalmetadata'
}
});
})
.then((item: Item): Promise<IListItem> => {
etag = item["odata.etag"];
return Promise.resolve((item as any) as IListItem);
})
.then((item: IListItem): Promise<ItemUpdateResult> => {
return pnp.sp.web.lists.getByTitle(this.properties.listName)
.items.getById(item.Id).update({
'Title': `Item ${new Date()}`
}, etag);
})
.then((result: ItemUpdateResult): void => {
this.updateStatus(`Item with ID: ${latestItemId} successfully updated`);
}, (error: any): void => {
this.updateStatus('Loading latest item failed with error: ' + error);
});
}
private deleteItem(): void {
if (!window.confirm('Are you sure you want to delete the latest item?')) {
return;
}
this.updateStatus('Loading latest items...');
let latestItemId: number = undefined;
let etag: string = undefined;
this.getLatestItemId()
.then((itemId: number): Promise<Item> => {
if (itemId === -1) {
throw new Error('No items found in the list');
}
latestItemId = itemId;
this.updateStatus(`Loading information about item ID: ${latestItemId}...`);
return pnp.sp.web.lists.getByTitle(this.properties.listName)
.items.getById(latestItemId).select('Id').get(undefined, {
headers: {
'Accept': 'application/json;odata=minimalmetadata'
}
});
})
.then((item: Item): Promise<IListItem> => {
etag = item["odata.etag"];
return Promise.resolve((item as any) as IListItem);
})
.then((item: IListItem): Promise<void> => {
this.updateStatus(`Deleting item with ID: ${latestItemId}...`);
return pnp.sp.web.lists.getByTitle(this.properties.listName)
.items.getById(item.Id).delete(etag);
})
.then((): void => {
this.updateStatus(`Item with ID: ${latestItemId} successfully deleted`);
}, (error: any): void => {
this.updateStatus(`Error deleting item: ${error}`);
});
}
private updateStatus(status: string, items: IListItem[] = []): void {
this.domElement.querySelector('.status').innerHTML = status;
this.updateItemsHtml(items);
}
private updateItemsHtml(items: IListItem[]): void {
const itemsHtml: string[] = [];
for (let i: number = 0; i < items.length; i++) {
itemsHtml.push(`<li>${items[i].Title} (${items[i].Id})</li>`);
}
this.domElement.querySelector('.items').innerHTML = itemsHtml.join('');
}
}