-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspcrud.js
More file actions
471 lines (428 loc) · 14.3 KB
/
spcrud.js
File metadata and controls
471 lines (428 loc) · 14.3 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/**
* Library with AngularJS operations for CRUD operations to SharePoint 2013 lists over REST api
*
* Contains 6 core functions and other misc helper functions
*
* 1) Create - add item to List
* 2) Read - find all items or single item from List
* 3) Update - update item in List
* 4) Delete - delete item in List
* 5) jsonRead - read JSON to List
* 6) jsonWrite - write JSON to List ("upsert" = add if missing, update if exists)
*
* NOTE - 5 and 6 require the target SharePoint List to have two columns: "Title" (indexed) and "JSON" (mult-text). These are
* intendend to save JSON objects for JS internal application needs. For example, saving user preferences to a "JSON-Settings" list
* where one row is created per user (Title = current user Login) and JSON multi-text field holds the JSON blob.
* Simple and flexible way to save data for many scenarios.
*
* @spjeff
* spjeff@spjeff.com
* http://spjeff.com
*
* version 0.1.26
* last updated 07-17-2018
*
*/
//namespace
'use strict';
var spcrud = spcrud || {};
//----------SHAREPOINT GENERAL----------
//initialize
spcrud.init = function () {
//default to local web URL
spcrud.apiUrl = spcrud.baseUrl + '/_api/web/lists/GetByTitle(\'{0}\')/items';
//globals
spcrud.jsonHeader = 'application/json;odata=verbose';
spcrud.headers = {
'Content-Type': spcrud.jsonHeader,
'Accept': spcrud.jsonHeader
};
//request digest
var el = document.querySelector('#__REQUESTDIGEST');
if (el) {
//digest local to ASPX page
spcrud.headers['X-RequestDigest'] = el.value;
}
}
//change target web URL
spcrud.setBaseUrl = function (webUrl) {
if (webUrl) {
//user provided target Web URL
spcrud.baseUrl = webUrl;
} else {
//default local SharePoint context
if (window._spPageContextInfo) {
spcrud.baseUrl = window._spPageContextInfo.webAbsoluteUrl;
}
}
spcrud.init();
}
spcrud.setBaseUrl();
//string ends with
spcrud.endsWith = function (str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
spcrud.replaceAll = function(source, str1, str2, ignore)
{
return source.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}
//digest refresh worker
spcrud.refreshDigest = function ($http) {
var config = {
method: 'POST',
url: spcrud.baseUrl + '/_api/contextinfo',
headers: spcrud.headers
};
return $http(config).then(function (response) {
//parse JSON and save
spcrud.headers['X-RequestDigest'] = response.data.d.GetContextWebInformation.FormDigestValue;
});
}
//send email
spcrud.sendMail = function ($http, to, ffrom, subj, body) {
//append metadata
to = to.split(",");
var recip = (to instanceof Array) ? to : [to],
message = {
'properties': {
'__metadata': {
'type': 'SP.Utilities.EmailProperties'
},
'To': {
'results': recip
},
'From': ffrom,
'Subject': subj,
'Body': body
}
},
config = {
method: 'POST',
url: spcrud.baseUrl + '/_api/SP.Utilities.Utility.SendEmail',
headers: spcrud.headers,
data: angular.toJson(message)
};
return $http(config);
}
//----------SHAREPOINT USER PROFILES----------
//lookup SharePoint current web user
spcrud.getCurrentUser = function ($http) {
var url = spcrud.baseUrl + '/_api/web/currentuser?$expand=Groups',
config = {
method: 'GET',
url: url,
cache: true,
headers: spcrud.headers
};
return $http(config);
}
//lookup my SharePoint profile
spcrud.getMyProfile = function ($http) {
var url = spcrud.baseUrl + '/_api/SP.UserProfiles.PeopleManager/GetMyProperties?select=*',
config = {
method: 'GET',
url: url,
cache: true,
headers: spcrud.headers
};
return $http(config);
}
//lookup any SharePoint profile
spcrud.getProfile = function ($http, login) {
var url = spcrud.baseUrl + '/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=\'' + login + '\'&select=*',
config = {
method: 'GET',
url: url,
headers: spcrud.headers
};
return $http(config);
}
//lookup any SharePoint UserInfo
spcrud.getUserInfo = function ($http, Id) {
var url = spcrud.baseUrl + '/_api/web/getUserById(' + Id + ')',
config = {
method: 'GET',
url: url,
headers: spcrud.headers
};
return $http(config);
}
//ensure SPUser exists in target web
spcrud.ensureUser = function ($http, login) {
var url = spcrud.baseUrl + '/_api/web/ensureuser',
config = {
method: 'POST',
url: url,
headers: spcrud.headers,
data: login
};
return $http(config);
}
//----------SHAREPOINT LIST AND FIELDS----------
//create list
spcrud.createList = function ($http, title, baseTemplate, description) {
var data = {
'__metadata': { 'type': 'SP.List' },
'BaseTemplate': baseTemplate,
'Description': description,
'Title': title
},
url = spcrud.baseUrl + '/_api/web/lists',
config = {
method: 'POST',
url: url,
headers: spcrud.headers,
data: data
};
return $http(config);
}
//create field
spcrud.createField = function ($http, listTitle, fieldName, fieldType) {
var data = {
'__metadata': { 'type': 'SP.Field' },
'Type': fieldType,
'Title': fieldName
},
url = spcrud.baseUrl + '/_api/web/lists/GetByTitle(\'' + listTitle + '\')/fields',
config = {
method: 'POST',
url: url,
headers: spcrud.headers,
data: data
};
return $http(config);
}
//----------SHAREPOINT FILES AND FOLDERS----------
//create folder
spcrud.createFolder = function ($http, folderUrl) {
var data = {
'__metadata': {
'type': 'SP.Folder'
},
'ServerRelativeUrl': folderUrl
},
url = spcrud.baseUrl + '/_api/web/folders',
config = {
method: 'POST',
url: url,
headers: spcrud.headers,
data: data
};
return $http(config);
}
// upload file to folder
// https://kushanlahiru.wordpress.com/2016/05/14/file-attach-to-sharepoint-2013-list-custom-using-angular-js-via-rest-api/
// http://stackoverflow.com/questions/17063000/ng-model-for-input-type-file
// var binary = new Uint8Array(FileReader.readAsArrayBuffer(file[0]));
spcrud.uploadFile = function ($http, folderUrl, fileName, binary) {
var url = spcrud.baseUrl + '/_api/web/GetFolderByServerRelativeUrl(\'' + folderUrl + '\')/files/add(overwrite=true, url=\'' + fileName + '\')',
config = {
method: 'POST',
url: url,
headers: spcrud.headers,
data: binary,
transformRequest: []
};
return $http(config);
}
//upload attachment to item
spcrud.uploadAttach = function ($http, listName, id, fileName, binary, overwrite) {
var url = spcrud.baseUrl + '/_api/web/lists/GetByTitle(\'' + listName + '\')/items(' + id,
headers = JSON.parse(JSON.stringify(spcrud.headers));
if (overwrite) {
//append HTTP header PUT for UPDATE scenario
headers['X-HTTP-Method'] = 'PUT';
url += ')/AttachmentFiles(\'' + fileName + '\')/$value';
} else {
//CREATE scenario
url += ')/AttachmentFiles/add(FileName=\'' + fileName + '\')';
}
var config = {
method: 'POST',
url: url,
headers: headers,
data: binary
};
return $http(config);
}
//get attachment for item
spcrud.getAttach = function ($http, listName, id) {
var url = spcrud.baseUrl + '/_api/web/lists/GetByTitle(\'' + listName + '\')/items(' + id + ')/AttachmentFiles',
config = {
method: 'GET',
url: url,
headers: spcrud.headers
};
return $http(config);
}
//copy file
spcrud.copyFile = function ($http, sourceUrl, destinationUrl) {
var url = spcrud.baseUrl + '/_api/web/getfilebyserverrelativeurl(\'' + sourceUrl + '\')/copyto(strnewurl=\'' + destinationUrl + '\',boverwrite=false)',
config = {
method: 'POST',
url: url,
headers: spcrud.headers
};
return $http(config);
}
//----------SHAREPOINT LIST CORE----------
//CREATE item - SharePoint list name, and JS object to stringify for save
spcrud.create = function ($http, listName, jsonBody) {
//append metadata
if (!jsonBody.__metadata) {
jsonBody.__metadata = {
'type': 'SP.ListItem'
};
}
var data = angular.toJson(jsonBody),
config = {
method: 'POST',
url: spcrud.apiUrl.replace('{0}', listName),
data: data,
headers: spcrud.headers
};
return $http(config);
}
spcrud.readBuilder = function (url, options) {
if (options) {
if (options.filter) {
url += ((url.indexOf('?') > -1) ? "&" : "?") + "$filter=" + options.filter;
}
if (options.select) {
url += ((url.indexOf('?') > -1) ? "&" : "?") + "$select=" + options.select;
}
if (options.orderby) {
url += ((url.indexOf('?') > -1) ? "&" : "?") + "$orderby=" + options.orderby;
}
if (options.expand) {
url += ((url.indexOf('?') > -1) ? "&" : "?") + "$expand=" + options.expand;
}
if (options.top) {
url += ((url.indexOf('?') > -1) ? "&" : "?") + "$top=" + options.top;
}
if (options.skip) {
url += ((url.indexOf('?') > -1) ? "&" : "?") + "$skip=" + options.skip;
}
}
return url;
}
//READ entire list - needs $http factory and SharePoint list name
spcrud.read = function ($http, listName, options) {
//build URL syntax
//https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#bk_support
var url = spcrud.apiUrl.replace('{0}', listName);
url = spcrud.readBuilder(url, options);
//config
var config = {
method: 'GET',
url: url,
headers: spcrud.headers
};
return $http(config);
}
//READ single item - SharePoint list name, and item ID number
spcrud.readItem = function ($http, listName, id) {
var url = spcrud.apiUrl.replace('{0}', listName) + '(' + id + ')';
url = spcrud.readBuilder(url);
//config
var config = {
method: 'GET',
url: url,
headers: spcrud.headers
};
return $http(config);
}
//UPDATE item - SharePoint list name, item ID number, and JS object to stringify for save
spcrud.update = function ($http, listName, id, jsonBody) {
//append HTTP header MERGE for UPDATE scenario
var headers = JSON.parse(JSON.stringify(spcrud.headers));
headers['X-HTTP-Method'] = 'MERGE';
headers['If-Match'] = '*';
//append metadata
if (!jsonBody.__metadata) {
jsonBody.__metadata = {
'type': 'SP.ListItem'
};
}
var data = angular.toJson(jsonBody),
config = {
method: 'POST',
url: spcrud.apiUrl.replace('{0}', listName) + '(' + id + ')',
data: data,
headers: headers
};
return $http(config);
}
//DELETE item - SharePoint list name and item ID number
spcrud.del = function ($http, listName, id) {
//append HTTP header DELETE for DELETE scenario
var headers = JSON.parse(JSON.stringify(spcrud.headers));
headers['X-HTTP-Method'] = 'DELETE';
headers['If-Match'] = '*';
var config = {
method: 'POST',
url: spcrud.apiUrl.replace('{0}', listName) + '(' + id + ')',
headers: headers
};
return $http(config);
}
//JSON blob read from SharePoint list - SharePoint list name
spcrud.jsonRead = function ($http, listName, cache) {
return spcrud.getCurrentUser($http).then(function (response) {
//GET SharePoint Current User
spcrud.currentUser = response.data.d;
spcrud.login = response.data.d.LoginName.toLowerCase();
spcrud.login = spcrud.replaceAll(spcrud.login, '|', '');
spcrud.login = spcrud.replaceAll(spcrud.login, '#', '');
spcrud.login = spcrud.replaceAll(spcrud.login, '?', '');
spcrud.login = spcrud.replaceAll(spcrud.login, '@', '');
spcrud.login = spcrud.replaceAll(spcrud.login, '\'', '');
spcrud.login = spcrud.replaceAll(spcrud.login, '\\', '');
//default no caching
if (!cache) {
cache = false;
}
//GET SharePoint list item(s)
var config = {
method: 'GET',
url: spcrud.apiUrl.replace('{0}', listName) + '?$select=JSON,Id,Title&$filter=Title+eq+\'' + spcrud.login + '\'',
cache: cache,
headers: spcrud.headers
};
//GET SharePoint Profile
spcrud.getMyProfile($http).then(function (response) {
spcrud.myProfile = response.data.d;
});
//parse single SPListItem only
return $http(config).then(function (response) {
if (response.data.d.results) {
return response.data.d.results[0];
} else {
return null;
}
});
});
}
//JSON blob upsert write to SharePoint list - SharePoint list name and JS object to stringify for save
spcrud.jsonWrite = function ($http, listName, jsonBody) {
return spcrud.refreshDigest($http).then(function (response) {
return spcrud.jsonRead($http, listName).then(function (item) {
//HTTP 200 OK
if (item) {
//update if found
item.JSON = angular.toJson(jsonBody);
return spcrud.update($http, listName, item.Id, item);
} else {
//create if missing
item = {
'__metadata': {
'type': 'SP.ListItem'
},
'Title': spcrud.login,
'JSON': angular.toJson(jsonBody)
};
return spcrud.create($http, listName, item);
}
});
});
}