REST APIs

I've already talked a bit about APIs elsewhere, but just so that you don't have to go looking for it, I've included it as a standalone piece of tech with which I am familiar.

Most of my experience comes from working with DNN Evoq, which is a CMS that no one's ever heard of, but it is headless, which means that if I couldn't do something in the CMS, I could do it on the front-end with JS.

Turns out that there were a lot of things I couldn't do with the CMS. For example, you cannot pull in over 100 pieces of content - probably for good reason. But what if I wanted to pull in 500 and lazy load it? That was not possible out of the box, but it was possible with the API, because the cap there was 1000.

I've included some code samples in the JavaScript section, but below are others.

Code Sample

Filter Tool

The below JavaScript fetches data for a filtering tool that sorts through thousands of pieces of content to a user who inputs basic criteria.

This tool is currently located here.


const urlParams = new URLSearchParams(window.location.search);
const filter = urlParams.get('filter');

var localStorageKeys = ['bl', 'catTag', 'spcTag'];

function clearStorage(){
    localStorage.removeItem('bl');
    localStorage.removeItem('catTag');
    localStorage.removeItem('spcTag');
}

var businessLines = ['property and casualty', 'benefits & life', 'personal insurance', 'wealth & retirement', 'all business lines']

var categories = ['press_release','latest insights','insightsfromtheexperts','webinars and training','podcast','resources','legislativeperspectives','article'];

var specialtyArray = [
    'Benefit Compliance',
    'Captives and Aternative Risk',
    'Complex Risk Solutions',
    'Construction',
    'Cybersecurity',
    'Disability Insurance',
    'Employee Benefits',
    'Environmental',
    'Executive Benefits',
    'Financial Institutions',
    'General',
    'Healthcare and Life Sciences',
    'Hospitality and Leisure',
    'HR Solutions',
    'Life Insurance',
    'M and A Risk Solutions',
    'Management and Professional Liability',
    'News Articles',
    'Personal Risk',
    'Pharmacy',
    'Retirement',
    'Risk Management and Complex Risk',
    'Sports and Entertainment',
    'Surety',
    'Trade Credit',
    'Transportation',
    'Voluntary Benefits',
    'Wealth Management',
    'Well-Being and Engagement'
]

var specialtyArrayLowerCase = specialtyArray.map(v => v.toLowerCase());
var categoriesArrayLowerCase = categories.map(v => v.toLowerCase());

const loadFilters = async (blTxt, spcTxt) => {
    $('#categories input[tag-name="insights"]').prop('checked', true)
    var arr = [];
    try {
        $('#categories input').removeAttr('disabled').removeClass('disabled');
        $('#categories .card.is-loading').removeClass('d-none').addClass('w-100');
        $('#categories').removeClass('d-none').addClass('d-flex').addClass('w-100')
        $('#categories div').not('.card').addClass('d-none');
        if(spcTxt === undefined){
            var tags = blTxt;
        }else{
            var tags = blTxt + '|' + spcTxt;
        }
        const res = await fetch('https://dnnapi.com/content/api/ContentItems/?maxItems=1000&contentTypeId=71529551-ddf4-498b-966a-6de35c2ec27f&tags=insights|'+tags, {headers: {authorization: 'Bearer **hidden**'}});
        filtered1 = await res.json();
        filtered = await filtered1.documents
        filtered.map(item =>{
            arr.push(item.tags)
        })
        
        function flatten(arr) {
            var flat = [];
            for (var i = 0; i < arr.length; i++) {
                flat = flat.concat(arr[i]);
            }
            return flat;
        }
        var uniq = [...new Set(flatten(arr))];
        var intersection = uniq.filter(element => categories.includes(element));
        let difference = categories.filter(x => !intersection.includes(x));
        
        difference.forEach(function(part, index) {
            this[index] = part.replace(/ /g,'-');
            $('input[tag-name="'+this[index]+'"]').attr('disabled','disabled').addClass('disabled');
        }, difference);
          
        $('#categories').removeClass('w-100');
        $('#categories div').not('.card').removeClass('d-none');
        $('#categories .card.is-loading').addClass('d-none');
        
    } catch (err) {
        console.log(err);
    }
};

const loadSpecialtyFilters = async (catTag) => {
    console.log('loadSpecialtyFilters was called')
    var bl = localStorage.getItem('bl');
    var newSpecialtyArray = [];
    $('#specialties-dropdown').addClass('d-none'); 
    $('#specialties .card.is-loading').removeClass('d-none');
    try {
        $('#specialties .card.is-loading').removeClass('d-none');
        
        const res = await fetch('https://dnnapi.com/content/api/ContentItems/?maxItems=1000&contentTypeId=71529551-ddf4-498b-966a-6de35c2ec27f&tags=insights|'+catTag+'|'+bl, {headers: {authorization: 'Bearer **hidden**'}});
        filtered1 = await res.json();
        filtered = await filtered1.documents
        filtered.map(item =>{
            newSpecialtyArray.push(item.tags)
        })
        function flatten(newSpecialtyArray) {
            var flat = [];
            for (var i = 0; i < newSpecialtyArray.length; i++) {
                flat = flat.concat(newSpecialtyArray[i]);
            }
            return flat;
        }
        
        var uniq = [...new Set(flatten(newSpecialtyArray))];
        var lowercasedDnnArr = uniq.map(v => v.toLowerCase());
        var lowercasedMyArr = specialtyArray.map(v => v.toLowerCase());
        var intersection = lowercasedDnnArr.filter(element => lowercasedMyArr.includes(element));

        function upperCaseFirstLetter(str) {
            return str.split(' ').map(item => item.charAt(0).toUpperCase() + item.slice(1).toLowerCase()).join(' ').replace('And', 'and').replace('M and A', 'M&A');
        }

        console.log()
        
        if(intersection.length !== 0){
           
            $('#specialties select option').slice(1).remove();
            for(let i = 0; i < intersection.length; i++){

                $('[tag-name='+intersection[i].replace(/ /g,'-')+']').remove();
                $('#specialties .card.is-loading').addClass('d-none');
                $('#specialties-dropdown').removeClass('d-none'); 
                $('#specialties select').append('<option tag-name="'+intersection[i]+'" value="All Business Line Content">'+upperCaseFirstLetter(intersection[i])+'</option>')
            }
        }else{
            $('#specialties .card.is-loading').addClass('d-none');
            $('#specialties-dropdown').addClass('d-none'); 
        }

        var getSpcLocalStorage = localStorage.getItem('spcTag');
        if(getSpcLocalStorage !== null){
            $('#specialties option[tag-name="'+getSpcLocalStorage+'"]').attr('selected',true)
        }
        if(bl === 'insights'){
            $('#specialties-dropdown').addClass('d-none');
            whenThereIsNoSpecialty()
        }
    } catch (err) {
        console.log(err);
    }
};

function allStorage() {
    var values = [];
    var keys = Object.keys(localStorage);
    const result = keys.filter(check);
    function check(p) {
        return p == 'bl' || p === 'catTag' || p === 'spcTag';
    }
    var i = result.length;
    while (i--) {
        values.push(localStorage.getItem(result[i]));
    }
    var x = values.filter(n => n)
    return x;
}

function whenThereIsNoSpecialty(){
    $('.noSpecialty').removeClass('d-none').addClass('d-flex')
    $('.specialtyDisplayed').addClass('d-none').removeClass('d-flex')
}

function whenThereIsSpecialty(){
    $('.noSpecialty').addClass('d-none').removeClass('d-flex')
    $('.specialtyDisplayed').removeClass('d-none').addClass('d-flex')
}

$(document).ready(function () {
    clearStorage();
    function setStorExistingParams(){
        var filterSplit = filter.split(',');
        for(let i = 0; i < filterSplit.length; i++){
            businessLines.forEach(function(item){
                if(item.includes(filterSplit[i])){
                    localStorage.setItem('bl', filterSplit[i]);
                }
            })
            specialtyArrayLowerCase.forEach(function(item){
                if(item === filterSplit[i]){
                    localStorage.setItem('spcTag', filterSplit[i]);
                }
            })
            categoriesArrayLowerCase.forEach(function(item){
                if(item.includes(filterSplit[i])){
                    localStorage.setItem('catTag', filterSplit[i]);
                }
            })
        }
        
        var getExistingBl = localStorage.getItem('bl')
        var getExistingSpc = localStorage.getItem('spcTag')
        var getExistingCat = localStorage.getItem('catTag')

        var filtersObj = {
            'bl' : getExistingBl,
            'spc' : getExistingSpc,
            'cat' : getExistingCat
        }

        console.log(filtersObj)

        if(filtersObj.bl !== null){
            whenThereIsSpecialty()
            loadSpecialtyFilters(filtersObj.bl);
            loadFilters(filtersObj.bl);
            $('#businessLines option[tag-name="'+filtersObj.bl+'"]').attr('selected', true);
        }
        if(filtersObj.spc !== null){
            whenThereIsSpecialty()
            loadSpecialtyFilters(filtersObj.bl);
            loadFilters(filtersObj.bl, filtersObj.spc);
        }
        if(filtersObj.cat !== null){
            //whenThereIsNoSpecialty()
            $('input[tag-name="'+filtersObj.cat.replace(/ /g, '-')+'"]').prop('checked', true)
            if(getExistingBl !== null){ 
                loadSpecialtyFilters(filtersObj.cat)
            }
        }

        if((filtersObj.spc !== null) && (filtersObj.bl !== null) && (filtersObj.cat !== null)){
            whenThereIsSpecialty()
        }
    }

    
    //$('.hero .container').after('
') console.log(filter) if(filter === null){ $('#specialties-dropdown').addClass('d-none'); $('#businessLines option[tag-name="insights"]').attr('selected', true) $('#categories input[tag-name="insights"]').prop('checked', true) }else{ var getPageForwardValue = $('a.page-forward').attr('href') $('a.page-forward').attr('href', getPageForwardValue + '&filter='+filter) var getPageBackwardValue = $('a.page-backward').attr('href') $('a.page-backward').attr('href', getPageBackwardValue + '&filter='+filter) $('.btn-group a').attr(window.location.href+','+filter) setStorExistingParams(); } $('#specialties-dropdown').addClass('d-none'); $('#businessLines select, #specialties select').click(function(){ $(this).toggleClass('arrowToggleOn') }) $('#business-line-dropdown').change(function(){ whenThereIsSpecialty() clearStorage(); localStorage.setItem('bl', ''); $('#categories input').prop('checked', false); var txt = $('#business-line-dropdown').find(':selected').attr('tag-name') console.log(txt) if(txt === 'compliance corner'){ window.location = '/about-nfp/insights/compliance-corner'; }else{ localStorage.setItem('bl', txt); loadFilters(txt) loadSpecialtyFilters(txt) } }); //click functions $('body').on('click', '#categories input', function(e) { var catTag = $(e.target).attr('tag-name').replace(/-/g, ' '); localStorage.setItem('catTag', catTag); }); $('#specialties-dropdown').change(function(){ localStorage.removeItem('spcTag') localStorage.removeItem('catTag') $('#categories input').prop('checked', false); var getSpc = $('#specialties-dropdown').find(':selected').attr('tag-name') localStorage.setItem('spcTag', getSpc); var getBl = localStorage.getItem('bl') loadFilters(getSpc, getBl) }); //load search results $('body').on('click', '.loadSearchResultsBtn', function(e) { console.log(allStorage()) window.location = '?filter='+allStorage()+'&page=1#anchor'; }); })