mui-spfx-controls
Version:
SPFx component library built with MUI
264 lines • 12.6 kB
JavaScript
import { __asyncValues, __awaiter, __generator } from "tslib";
import { Logger } from '@pnp/logging';
import { FieldTypes } from '@pnp/sp/fields';
import { PermissionKind } from '@pnp/sp/security';
import { getSp } from '../config/pnp.config';
/**
* Service class for interacting with SharePoint lists.
*/
var ListService = /** @class */ (function () {
/**
* Initializes the ListService instance.
* @param {WebPartContext} context - The SharePoint WebPart context.
* @param {string} listId - The ID of the SharePoint list.
*/
function ListService(context, listId) {
this.sp = getSp(context);
this.list = this.sp.web.lists.getById(listId);
}
/**
* Checks if a field is visible and not hidden.
* @param {IFieldInfo} field - The field information.
* @returns {boolean} True if the field is not hidden, otherwise false.
*/
ListService.prototype.checkCustomFieldType = function (field) {
return !field.Hidden;
};
/**
* Retrieves the total item count of the list.
* @returns {Promise<number>} The total number of items in the list.
*/
ListService.prototype.getListSize = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.list
.select('ItemCount')()
.then(function (response) { return response.ItemCount; })];
});
});
};
/**
* Fetches all lists available in the SharePoint site.
* @returns {Promise<IListInfo[]>} A list of SharePoint lists.
*/
ListService.prototype.getLists = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.sp.web.lists()];
});
});
};
/**
* Retrieves fields from the specified list, optionally filtering by internal names.
* @param {string[]} [fieldInternalNames] - Optional array of field internal names to filter.
* @returns {Promise<IFieldInfo[]>} A list of field information objects.
*/
ListService.prototype.getListFields = function (fieldInternalNames) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, this.list
.fields()
.then(function (response) {
return response.filter(function (value) {
return fieldInternalNames
? _this.checkCustomFieldType(value) &&
fieldInternalNames.indexOf(value.InternalName) !== -1
: _this.checkCustomFieldType(value);
});
})];
});
});
};
/**
* Retrieves list items with specified fields, filters, and sorting options.
* @param {IFieldInfo[]} fields - The fields to include.
* @param {string} [filter] - Optional OData filter query.
* @param {string} [orderBy] - Optional sorting field.
* @param {number} [top] - Optional limit on number of records.
* @returns {Promise<any[]>} The list items.
*/
ListService.prototype.getListItems = function (fields, filter, orderBy, top) {
return __awaiter(this, void 0, void 0, function () {
var selectFields, expandFields, totalItems, totalCount, _a, _b, _c, _d, _e, _f, items, e_1_1;
var _g, _h, _j, _k;
var _l, e_1, _m, _o;
return __generator(this, function (_p) {
switch (_p.label) {
case 0:
selectFields = ['Id'];
expandFields = [];
totalItems = [];
fields.forEach(function (value) {
if (value.FieldTypeKind === FieldTypes.User) {
selectFields.push("".concat(value.InternalName, "/Id"), "".concat(value.InternalName, "/Title"), "".concat(value.InternalName, "/EMail"));
expandFields.push(value.InternalName);
}
else {
selectFields.push(value.InternalName);
}
});
return [4 /*yield*/, this.getListSize()];
case 1:
totalCount = _p.sent();
if (!top) return [3 /*break*/, 3];
_b = (_a = totalItems.push).apply;
_c = [totalItems];
return [4 /*yield*/, (_g = (_h = this.list.items)
.select.apply(_h, selectFields))
.expand.apply(_g, expandFields).filter(filter !== null && filter !== void 0 ? filter : '')
.orderBy(orderBy !== null && orderBy !== void 0 ? orderBy : '', false)
.top(top)()];
case 2:
_b.apply(_a, _c.concat([(_p.sent())]));
return [3 /*break*/, 14];
case 3:
_p.trys.push([3, 8, 9, 14]);
_d = true, _e = __asyncValues((_j = (_k = this.list.items)
.select.apply(_k, selectFields))
.expand.apply(_j, expandFields).filter(filter !== null && filter !== void 0 ? filter : '')
.orderBy(orderBy !== null && orderBy !== void 0 ? orderBy : '', false));
_p.label = 4;
case 4: return [4 /*yield*/, _e.next()];
case 5:
if (!(_f = _p.sent(), _l = _f.done, !_l)) return [3 /*break*/, 7];
_o = _f.value;
_d = false;
items = _o;
if (totalItems.length >= totalCount)
return [3 /*break*/, 7];
totalItems.push.apply(totalItems, items);
_p.label = 6;
case 6:
_d = true;
return [3 /*break*/, 4];
case 7: return [3 /*break*/, 14];
case 8:
e_1_1 = _p.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 14];
case 9:
_p.trys.push([9, , 12, 13]);
if (!(!_d && !_l && (_m = _e.return))) return [3 /*break*/, 11];
return [4 /*yield*/, _m.call(_e)];
case 10:
_p.sent();
_p.label = 11;
case 11: return [3 /*break*/, 13];
case 12:
if (e_1) throw e_1.error;
return [7 /*endfinally*/];
case 13: return [7 /*endfinally*/];
case 14: return [2 /*return*/, totalItems];
}
});
});
};
/**
* Creates a new list item with specified values.
* @param {Record<string, any>} value - The values for the new item.
* @returns {Promise<Record<string, any>>} The created list item.
* @throws {Error} If the user lacks AddListItems permission.
*/
ListService.prototype.createListItem = function (value) {
return __awaiter(this, void 0, void 0, function () {
var userPermissions;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.list.getCurrentUserEffectivePermissions()];
case 1:
userPermissions = _a.sent();
if (!this.list.hasPermissions(userPermissions, PermissionKind.AddListItems)) {
throw new Error('Permission Error');
}
return [4 /*yield*/, this.list.items.add(value)];
case 2: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Updates an existing list item by ID.
* @param {number} id - The ID of the list item.
* @param {Record<string, any>} newRow - The updated values.
* @returns {Promise<void>} Resolves when the update is successful.
* @throws {Error} If the user lacks EditListItems permission.
*/
ListService.prototype.updateListItem = function (id, newRow) {
return __awaiter(this, void 0, void 0, function () {
var userPermissions, excludedFields, resolveUserId, processedRow, _i, _a, key, value, userId;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.list.getCurrentUserEffectivePermissions()];
case 1:
userPermissions = _b.sent();
if (!this.list.hasPermissions(userPermissions, PermissionKind.EditListItems)) {
throw new Error('Permission Error');
}
excludedFields = new Set([
'ID',
'Created',
'Modified',
'Author',
'Editor',
'GUID',
'Version',
'Attachments',
'odata.editLink',
'odata.id',
'odata.type',
'odata.metadata',
'odata.etag',
]);
resolveUserId = function (email) { return __awaiter(_this, void 0, void 0, function () {
var user, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.sp.web.siteUsers.getByEmail(email)()];
case 1:
user = _a.sent();
return [2 /*return*/, user.Id];
case 2:
error_1 = _a.sent();
Logger.error(error_1);
return [2 /*return*/, null];
case 3: return [2 /*return*/];
}
});
}); };
processedRow = {};
_i = 0, _a = Object.keys(newRow);
_b.label = 2;
case 2:
if (!(_i < _a.length)) return [3 /*break*/, 6];
key = _a[_i];
value = newRow[key];
if (!(!excludedFields.has(key) && key.indexOf('@odata.') === -1)) return [3 /*break*/, 5];
if (!(value && typeof value === 'object' && 'EMail' in value)) return [3 /*break*/, 4];
return [4 /*yield*/, resolveUserId(value.EMail)];
case 3:
userId = _b.sent();
if (userId)
processedRow[key + 'Id'] = userId;
return [3 /*break*/, 5];
case 4:
processedRow[key] = value;
_b.label = 5;
case 5:
_i++;
return [3 /*break*/, 2];
case 6: return [4 /*yield*/, this.list.items.getById(id).update(processedRow)];
case 7:
_b.sent();
return [2 /*return*/];
}
});
});
};
return ListService;
}());
export { ListService };
//# sourceMappingURL=ListService.js.map