Microsoft Lists: Delete List Item

Microsoft Lists: Delete List Item

Microsoft Lists: リストアイテム削除

This item deletes list items on Microsoft Lists. You can delete multiple list items at once. When you delete multiple ones, you should write one list item ID on each line.

Basic Configs
Step Name
Note
Auto Step icon
Configs for this Auto Step
conf_OAuth2
C1: OAuth2 Setting *
conf_SiteUrl
C2: SharePoint Site URL *
conf_ListTitle
C3: List Title *
conf_ListItemIds
C4: Data item with list item IDs to delete *

Notes

  • The SharePoint Site URL is the part before /Lists of the List URL
    • When the List is in My lists, it looks like https://{sub-domain}-my.sharepoint.com/personal/{user-identifier}_{domain}_onmicrosoft_com
    • When the List is in a SharePoint site, it looks like https://{sub-domain}.sharepoint.com/sites/{site-identifier}

Capture

See Also

Script (click to open)
  • An XML file that contains the code below is available to download
    • microsoft-lists-listitem-delete.xml (C) Questetra, Inc. (MIT License)
    • If you are using Professional, you can modify the contents of this file and use it as your own add-on auto step

// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://login.microsoftonline.com/{your-tenant-id}/oauth2/v2.0/authorize
// - Token Endpoint URL: https://login.microsoftonline.com/{your-tenant-id}/oauth2/v2.0/token
// - Scope: https://graph.microsoft.com/Sites.ReadWrite.All offline_access
// - Consumer Key: (Get by Microsoft Azure Active Directory)
// - Consumer Secret: (Get by Microsoft Azure Active Directory)

const GRAPH_URI = 'https://graph.microsoft.com/v1.0/';

const main = () => {
    //// == 工程コンフィグの参照 / Config Retrieving ==
    const oauth2 = configs.getObject('conf_OAuth2');
    const siteUrl = retrieveSiteUrl();
    const listTitle = configs.get('conf_ListTitle');
    const listItemIds = retrieveListItemIds();

    //// == 演算 / Calculating ==
    const siteId = getSiteIdByUrl(oauth2, siteUrl);
    listItemIds.forEach(listItemId => {
        deleteListItem(oauth2, siteId, listTitle, listItemId);
    });
};

/**
 * 工程コンフィグからサイトの URL を取得する
 * @returns {String} サイトの URL
 */
const retrieveSiteUrl = () => {
    let siteUrl = configs.get('conf_SiteUrl');
    // 末尾にスラッシュがある場合、削除
    if (siteUrl.endsWith('/')) {
        siteUrl = siteUrl.slice(0, -1);
    }
    return siteUrl;
};

/**
 * 工程コンフィグからリストアイテム ID を取得する
 * @returns {Set<String>} リストアイテム ID
 */
const retrieveListItemIds = () => {
    const dataDef = configs.getObject('conf_ListItemIds');
    let ids = [];
    if (dataDef.matchDataType('SELECT')) { // 選択型データ項目の場合
        const select = engine.findData(dataDef);
        if (select === null || select.size() === 0) { // 未選択
            throw new Error('No list item IDs selected.');
        }
        for (let i = 0; i < select.size(); i++) {
            ids.push(select.get(i).getValue());
        }
    } else { // 文字型データ項目の場合
        const value = engine.findData(dataDef);
        if (value === null) {
            throw new Error('No list item IDs.');
        }
        ids = value.split('\n').filter(id => id !== '');
        if (ids.length === 0) {
            throw new Error('No list item IDs.');
        }
    }
    const idsSet = new Set(ids); // 重複を除外
    if (idsSet.size + 1 > httpClient.getRequestingLimit()) { // 1 additional request to get site ID
        throw new Error('Too many list item IDs.');
    }
    return idsSet;
};

/**
 * サイトのメタデータを取得し、siteId を返す
 * APIの仕様: https://docs.microsoft.com/ja-jp/onedrive/developer/rest-api/api/shares_get?view=odsp-graph-online
 * @param {AuthSettingWrapper} oauth2  OAuth2 設定情報
 * @param {String} siteUrl  SharePoint サイトの URL
 * @returns {String} siteId
 */
const getSiteIdByUrl = (oauth2, siteUrl) => {
    // encoding sharing URL
    const encodedSharingUrl = encodeSharingUrl(siteUrl);

    // preparing for API Request
    const response = httpClient.begin()
        .authSetting(oauth2)
        .queryParam('select', 'id')
        .get(`${GRAPH_URI}shares/${encodedSharingUrl}/site`);
    const status = response.getStatusCode();
    const responseStr = response.getResponseAsString();
    if (status !== 200) {
        engine.log(responseStr);
        throw new Error(`Failed to get site info. status: ${status}`);
    }
    return JSON.parse(responseStr).id;
};

/**
 * 共有URLを unpadded base64url 形式にエンコードする
 * @param {String} sharingUrl  共有URL
 * @returns {String} encodedSharingUrl  エンコードされた共有URL
 */
const encodeSharingUrl = (sharingUrl) => {
    let encodedSharingUrl = base64.encodeToUrlSafeString(sharingUrl);
    while (encodedSharingUrl.slice(-1) === '=') {
        encodedSharingUrl = encodedSharingUrl.slice(0, -1);
    }
    return `u!${encodedSharingUrl}`;
};

/**
 * リストアイテムを削除する
 * @param {AuthSettingWrapper} oauth2  OAuth2 設定情報
 * @param {String} siteId  SharePoint サイトの ID
 * @param {String} listTitle  リストの名前
 * @param {String} listItemId  リストアイテム ID
 */
const deleteListItem = (oauth2, siteId, listTitle, listItemId) => {
    const url = `${GRAPH_URI}sites/${encodeURIComponent(siteId)}/lists/${encodeURIComponent(listTitle)}/items/${encodeURIComponent(listItemId)}`;
    const response = httpClient.begin()
        .authSetting(oauth2)
        .delete(url);
    const status = response.getStatusCode();
    if (status !== 204) {
        engine.log(response.getResponseAsString());
        throw new Error(`Failed to delete list item. id: ${listItemId}, status: ${status}`);
    }
};

    
Scroll to Top

Discover more from Questetra Support

Subscribe now to keep reading and get access to the full archive.

Continue reading