Home Reference Source Repository

src/util/sp/getItem.js

/**
 * Fetches an item by id from list.
 *
 * @example
 * getItem('List', '2', {
 *     fields: [ 'Id', 'Title' ],
 *     mapper: function(item) {
 *         return {
 *             id: item.get_id(),
 *             title: item.get_item('Title')
 *         };
 *     }
 * })
 * .then((item) => {})
 * .catch((sender, args) => {});
 *
 * @param {string}	list Name of list
 * @param {string}	id Id of item
 * @param {Object}	options
 * @param {string[]} options.fields List of fields to get
 * @param {function(item: Object): Object} options.mapper Mapper function
 * @param {boolean} attachments Also fetch attachments
 *
 * @return {Promise<Object>} object of item data.
 */
export default function getItem(list, id, {fields, mapper, attachments}) {
    const includes = fields && Array.isArray(fields) && `Include(${fields.join(',')})`;
    if (typeof mapper !== "function") {
        mapper = (item) => item;
    }

    return new Promise(function(resolve, reject) {
        window.SP.SOD.executeFunc('sp.js', 'SP.ClientContext', () => {
            const ctx = window.SP.ClientContext.get_current();
            const path = `${window._spPageContextInfo.webAbsoluteUrl}/Lists/${list}`;
            const item = ctx.get_web().getList(path).getItemById(id);

            if (includes) { ctx.load(item, includes); }
            else { ctx.load(item); }

            if (attachments) { ctx.load(item.get_attachmentFiles()); }

            ctx.executeQueryAsync(
                function() {
                    resolve(mapper(item));
                },
                function(sender, args){reject(sender, args);}
            );
        });
    });
}