Home Reference Source Repository

src/util/sp/getList.js

/**
 * Fetches a list.
 *
 * @param {string}	list Name of the list
 * @param {Object}	options
 * @param {string[]} options.fields List of fields to get
 * @param {function(item: Object): Object} options.mapper Mapper function
 *
 * @example
 * getList('List', {
 *     fields: [ 'Id', 'Title' ],
 *     mapper: function(item) {
 *         return {
 *             id: item.get_id(),
 *             title: item.get_item('Title')
 *         };
 *     }
 * })
 * .then((items) => {})
 * .catch((sender, args) => {});
 *
 * @return {Promise<Object[]>}  a list of items.
 */
export default function getList(list, {fields, mapper}) {
    const includes = fields && Array.isArray(fields) && `Include(${fields.join(',')})`;

    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 items = ctx.get_web().getList(path).getItems(window.SP.CamlQuery.createAllItemsQuery());

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

            ctx.executeQueryAsync(
                function() {
                    const result = items.get_data();
                    if (typeof mapper === "function") {
                        resolve(result.map(mapper));
                    }
                    else {
                        resolve(result);
                    }
                },
                function(sender, args){reject(sender, args);}
            );
        });
    });
}