Forem

Cover image for Access To Rest API Data Made Easy
Volker Schukai for schukai GmbH

Posted on

3 3

Access To Rest API Data Made Easy

Lately I had to read and set values in nested data structures of REST APIs very often. That was already slowly turning into work.

I can't remember how many times I wrote the following structures or similar in the last months.

const a = {}

if(typeof a ==='object') {
  if(a['b'] !==undefined ) {
    // do something 
  }
}
Enter fullscreen mode Exit fullscreen mode

Alternatively you can also work with Optional chaining. However, this also has its challenges.

For this reason I wrote the auxiliary class Pathfinder. This is a small class that bundles all the queries.

The integration is done via import.

import {Pathfinder} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.23.0/dist/modules/data/pathfinder.js';
Enter fullscreen mode Exit fullscreen mode

Methods

With this class come 4 methods exists, deleteVia, setVia and getVia. With these, structures can be manipulated quickly and easily.

getVia

First an example of how read access is possible.

new Pathfinder({
a: {
    b: {
        f: [
            {
                g: false,
            }
        ],
    }
}
}).getVia("a.b.f.0.g"); 

// ↦ false
Enter fullscreen mode Exit fullscreen mode

setVia

To write a value you can use the setVia method:

obj = {};

new Pathfinder(obj).setVia('a.b.0.c', true); 

// ↦ {a:{b:[{c:true}]}}

Enter fullscreen mode Exit fullscreen mode

Wildcards

A nice little additional feature is the use of wildcards. Here you can extract several values from a structure.

let value = new Pathfinder({
a: {
    b: {
        f: [
            {
                g: 1,
            },
            {
                g: 2,
            }
        ],
    }
}
}).getVia("a.b.f.*.g");

console.log(value.forEach((a,b)=>{console.log(a,b)}));
// ↦ 1 "0"
// ↦ 2 "1"

Enter fullscreen mode Exit fullscreen mode

The worst path you can choose is to choose none.

Voila that's it

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay