wkr-util
Version:
Utility library for wkr project.
89 lines (71 loc) • 2.9 kB
JavaScript
import {compose, curry, map, isString, split, last, liftA, pick, isObject} from '@cullylarson/f'
import isUuid from 'is-uuid'
import parseISO from 'date-fns/parseISO'
import fromUnixTime from 'date-fns/fromUnixTime'
const isPlainObj = x => typeof x === 'object' && x.constructor === Object
export const responseFromValidationResult = pick(['errors', 'paramErrors'])
export const responseError = messages => ({
errors: liftA(messages),
})
export const responseData = response => {
return response.json()
.then(data => ({response, data}))
.catch(_ => ({response, data: {}})) // just assume the JSON was bad, return empty object
}
// splits off any ipv6 stuff (e.g. node seems to like '::ffff:172.27.0.1' as an ip) and returns the ipv4 bit. if
// the ipv4 bit doesn't match an IP, will return undefined
export const formatIpv4 = x => x && isString(x) ? compose(
x => /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/.test(x) ? x : undefined,
last,
split(':'),
)(x) : undefined
// makes sure the provided value is an object
export const guardPlainObj = curry((defaultValue, x) => {
return isPlainObj(x)
? x
: defaultValue
})
// if x is an object, will just return it
export const fromJson = curry((defaultValue, x) => {
// already an object, just return it as-is
if(isObject(x)) return x
try {
return x && isString(x)
? JSON.parse(x)
: defaultValue
}
catch(_) {
return defaultValue
}
})
// takes a date string (that date-fns/parseISO can understand), a unix timestamp, or a Date object and returns an ISO 8601 date (the same outputted by Date.prototype.toISOString. E.g. 2011-10-05T14:48:00.000Z)
export const formatDatetime = x => {
if(!x) return x
const dateObj = isString(x)
? parseISO(x)
: isObject(x)
? x
: fromUnixTime(x)
return dateObj.toISOString()
}
// timestamp in ms
export const nowStampMs = () => new Date().valueOf()
// timestamp in s
export const nowStamp = () => Math.floor(nowStampMs() / 1000)
// converts a Date or a string that date-fns can understand to a timestamp (milliseconds)
export const dateToStampMs = x => isString(x)
? parseISO(x).valueOf()
: x.valueOf()
// converts a Date or a string that date_fns can understand to a timestamp (seconds)
export const dateToStamp = x => Math.floor(dateToStampMs(x) / 1000)
// if x is a uuid, will return it unaltered. otherwise will
// return an empty string.
export const toUuid = x => x && isUuid.v1(x) ? x : ''
// only trim if the value is a string, otherwise return the value unaltered
export const trimStr = x => isString(x) ? x.trim() : x
// trimStr except it will trim all children, children's children, etc.
export const trimStrDeep = x => {
return isObject(x) || Array.isArray(x)
? map(trimStrDeep, x)
: trimStr(x)
}