DEV Community

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

Posted on

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

Top comments (0)