export function getResourceName()

in tasks/Node/src/modules/task-utils/resourceutil.ts [15:52]


export function getResourceName(resourceId: string, resourceTypePlural: string, parts: string[] | null = null): string {
    // Determine if we should break the resourceId into its parts.
    if (!parts) {
        // Get all parts of the resource ID. This call will NOT affect casing, but it will remove
        // any trailing '/'.
        parts = getIdParts(resourceId);
    }

    // Determine if there's an error while parsing the resource ID.
    if (!parts || 4 > parts.length) {
        throw `ResourceUtil: Failed to parse string or too few resource type parts in resource ID '${resourceId}'.`;
    }
    
    // Ensure we have key/value pairs.
    if (parts.length % 2 != 0) {
        throw `ResourceUtil: Invalid resource ID '${resourceId}'.`;
    }

    // Determine if the requested resource type is present in the resource ID.
    const matchingPart = `/${resourceTypePlural}/`;
    const index = resourceId.toLowerCase().indexOf(matchingPart.toLowerCase());
    if (index == -1) {
        throw `ResourceUtil: Resource type '${resourceTypePlural}' is not present in resource ID '${resourceId}'.`;
    }

    // Traverse through the resource ID parts in reverse order, looking for the requested
    // resource type and extract its corresponding value.
    for (let i = parts.length - 2; i >= 0; i -= 2) {
        const key = parts[i];
        const value = parts[i + 1];
        if (key.toLowerCase() === resourceTypePlural.toLowerCase()) {
            return value;
        }
    }

    // Nothing found.
    throw `ResourceUtil: Unable to find value for requested resource type '${resourceTypePlural}'.`;
}