Skip to content

A small ES2015 function to look for a JSON response containing a specific property

Notifications You must be signed in to change notification settings

Ortanon/query-json

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

query-json

A small ES2015 function to look for a JSON response containing a specific property

API

import fn from './path/to/query-json'

fn('https://api.example.com', 'prop')
    .then(res => console.log(res.success.prop))

Error handling

The function always returns only { success: (the response) } or { failure: (details + response) }.

import query from './path/to/query-json'

// Check for success
query('https://jsonplaceholder.typicode.com/users', 'username')
    .then(res => {
        if ('success' in res) console.log(res.success[0].username)
        else throw 'oops'
    })

// Check for failure
query('https://jsonplaceholder.typicode.com/users', 'weather')
    .then(res => {
        if ('failure' in res) throw 'oh no!'
        else exampleCallback(res.success)
    })

// Check for failure using async/await
const answer = await query('https://jsonplaceholder.typicode.com/users', 'weather')
if ('failure' in answer) throw answer.failure
else return answer.success

About

A small ES2015 function to look for a JSON response containing a specific property

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published