README
Play State Utils
Get
Get data with path field, if it doesn't exist throw an error, or emit error on state (root) in case state is given
const get = require('play-state-utils/get')
var cmd = require('standard/test/cmd')
const data = {
foo: {
bar: 'Hell Yeah'
}
}
console.log(get(data)) // Returns data object
console.log(get(data, 'foo')) // returns {bar: 'Hell Yeah'}
console.log(get(data, 'foo.bar')) // returns 'Hell Yeah'
get(data, 'foo.error') // throws Error: 'field: "foo.error" doesn\'t exist'
The field path can also contain fallback fields. These are seperated with ||
const get = require('play-state-utils/get')
var cmd = require('standard/test/cmd')
const data = {
foo: {
bar: 'Hell Yeah'
}
}
console.log(get(data, 'foo.notExisting||foo.bar')) // returns 'Hell Yeah'
get.date
Get a date from data with path filed, if it doesn't exist or is not a date (all moment compatible inputs are valid).
const getDate = require('play-state-utils/get/date')
const data = {
foo: {
bar: 'Hell Yeah',
date: new Date()
}
}
console.log(getDate(data, 'foo.date')) // Returns Date()
console.log(getDate(data, 'foo.bar')) // throws Error: '"Hell Yeah" on field: "foo.bar" is not of type "date"'
get.number
Get a number like value from data with path field, if it doesn't exist or is not a number, throw an error, or emit error on state
const getNumber = require('play-state-utils/get/number'
const data = {
foo: {
bar: 'Hell Yeah',
number: 1
}
}
console.log(getNumber(data, 'foo.number')) // Returns 1
console.log(getNumber(data, 'foo.bar')) // throws Error: '"Hell Yeah" on field: "foo.bar" is not of type "number"'
get.string
Get a string from data with path field, if it doesn't exist or is not a string, throw an error, or emit error on state
const getString = require('play-state-utils/get/string')
const data = {
foo: {
bar: 'Hell Yeah',
number: 1
}
}
console.log(getString(data, 'foo.bar')) // Returns 'Hell Yeah'
console.log(getString(data, 'foo.number')) // throws Error: '"1" on field: "foo.number" is not of type "string"'
get.url
Get a url from data with path filed, if it doesn't exist or is not a url (including protocol: http
, https
or ws
).
const getDate = require('play-state-utils/get/url')
const data = {
foo: {
bar: 'Hell Yeah',
url: 'http://www.vigour.io'
}
}
console.log(getDate(data, 'foo.url')) // Returns http://www.vigour.io
console.log(getDate(data, 'foo.bar')) // throws Error: '"Hell Yeah" on field: "foo.bar" is not of type "date"'
Source
Setup a Source to retrieve data
Request
Retrieve data from a API via http
or https
.
const Request = require('play-state-utils/source/request')
const httpRequest = new Request({
hostname: 'www.http-server',
urlPath: '/api' // use urlPath instead of path
})
httpRequest.get((data) => { // Executes GET request to http://www.http-server/api
console.log(data) //→ data returned from the request
})