UNPKG

7.41 kBJavaScriptView Raw
1/**
2 * Created by Andy Likuski on 2017.07.03
3 * Copyright (c) 2017 Andy Likuski
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 *
7 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 *
9 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10 *
11 * Functions that the trowing versions from functions.js
12 */
13import {reqPath, reqPathPropEq, findOne, onlyOne, onlyOneValue, keyStringToLensPath} from './functions';
14import * as Result from 'folktale/result';
15import * as R from 'ramda';
16import {inspect} from 'util';
17
18/**
19 * Throw and exception if Result is Result.Error
20 * @param {Result} result Result.Error value is an array of Errors to throw. Result.Ok value is success to return
21 * @returns {Object} Throws or returns the contents of Result.Ok. Values are '; ' separated
22 */
23export const throwIfResultError = result =>
24 result.mapError(
25 // Throw if Result.Error
26 resultErrorValue => {
27 throw new Error(R.join('; ', resultErrorValue));
28 }
29 ).unsafeGet();
30
31/**
32 * Throw and exception if Result is Result.Error
33 * @param {String} message The custom error message to precede the error dump
34 * @param {Result} either Result.Error value is a single error
35 * @returns {Object} Throws or returns the contents of Result.Ok
36 */
37export const throwIfSingleResultError = R.curry((message, result) =>
38 result.mapError(
39 // Throw if Result.Error
40 resultErrorValue => {
41 throw new Error(`${message}: ${inspect(resultErrorValue, {showHidden: false, depth: 3})}`);
42 }
43 ).unsafeGet()
44);
45
46/**
47 * Like throwIfResultError but allows mapping of the unformatted Error values in Result
48 * @param {Result} either Result.Error value is an error to throw. Result.Ok value is success to return
49 * The Result value (not just the Result itself) must be a Container in order to apply the mapping function
50 * @param {Function} func Mapping function that maps Result.Error value. If this value is
51 * an array it maps each value. If not it maps the single value
52 * @returns {Result.Ok} Throws the mapped values or returns Result.Ok. Error values are '; ' separated
53 */
54export const mappedThrowIfResultError = R.curry((func, result) => {
55 return result.mapError(
56 // Throw if Result.Error
57 error => {
58 throw new Error(
59 R.join('; ', R.map(
60 e => {
61 return func(e);
62 },
63 error)
64 )
65 );
66 }).map(
67 // Return the Result.Ok value
68 R.identity
69 );
70 }
71);
72
73/**
74 * Calls functions.reqPath and throws if the reqPath does not resolve to a non-nil
75 * @params {[String]} Path the Ramda lens style path, e.g. ['x', 1, 'y']
76 * @params {Object} obj The obj to query
77 * @returns {Object|Exception} The value of the sought path or throws
78 * reqPath:: string -> obj -> a or throws
79 */
80export const reqPathThrowing = R.curry((pathList, obj) =>
81 reqPath(pathList, obj).mapError(
82 leftValue => {
83 // If left throw a helpful error
84 throw new Error(
85 R.join(' ', [
86 R.ifElse(
87 R.length,
88 resolved => `Only found non-nil path up to ${R.join('.', resolved)}`,
89 R.always('Found no non-nil value')
90 )(leftValue.resolved),
91 `of path ${R.join('.', pathList)} for obj ${inspect(obj, {depth: 3})}`
92 ]
93 )
94 );
95 },
96 // If right return the value
97 R.identity
98 ).unsafeGet()
99);
100
101/**
102 * Expects a prop path and returns a function expecting props,
103 * which resolves the prop indicated by the string. Throws if there is no match.
104 * Any detected standalone numbrer is assumed to be an index and converted to an int
105 * @param {String} str dot-separated prop path
106 * @param {Object} props Object to resolve the path in
107 * @return {function(*=)}
108 */
109export const reqStrPathThrowing = R.curry(
110 (str, props) => reqPathThrowing(keyStringToLensPath(str), props)
111);
112
113/**
114 * Calls functions.reqPathPropEq and throws if the reqPath does not resolve to a non-nil
115 * @params {[String]} Path the Ramda lens style path, e.g. ['x', 1, 'y']
116 * @params {*} Value to compare to result of reqPath
117 * @params {Object} obj The obj to query
118 * @returns {Boolean|Exception} true|false if the path is valid depending whether if the
119 * resulting value matches val. throws if the path is invalid
120 * reqPath:: Boolean b = string -> obj -> b or throws
121 */
122export const reqPathPropEqThrowing = R.curry((path, val, obj) =>
123 reqPathPropEq(path, val, obj).mapError(
124 leftValue => {
125 // If left throw a helpful error
126 throw new Error(
127 [leftValue.resolved.length ?
128 `Only found non-nil path up to ${leftValue.resolved.join('.')}` :
129 'Found no non-nil value of path',
130 `of ${path.join('.')} for obj ${inspect(obj, {depth: 2})}`
131 ].join(' '));
132 }
133 ).unsafeGet()
134);
135
136/**
137 * Like R.find but expects only one match and works on both arrays and objects
138 * @param {Function} predicate
139 * @param {Array|Object} obj Container that should only match once with predicate
140 * @returns {Object} The single item container or throws
141 */
142export const findOneThrowing = R.curry((predicate, obj) =>
143 throwIfSingleResultError('Did not find exactly one match', findOne(predicate, obj))
144);
145
146/**
147 * Like findOne but without a predicate
148 * @param {Array|Object} obj Container that should only match once with predicate
149 * @returns {Object} The single item container or throws
150 */
151export const onlyOneThrowing = obj =>
152 throwIfSingleResultError('Did not find exactly one', R.omit(['matching'], onlyOne(obj))
153 );
154
155/**
156 * Like onlyOne but extracts the value from the functor
157 * @param {Array|Object} obj Functor that has a values property
158 * @returns {Object} The single item container or throws
159 */
160export const onlyOneValueThrowing = obj =>
161 throwIfSingleResultError('Did not find exactly one', R.omit(['matching'], onlyOneValue(obj)));
162
163/**
164 * Expects the given params when used to filter the given items to result in one item that matches
165 * @param {Object} params key values where keys might match the item keys and values might match the item values
166 * @param {[Object]} items Objects to test on the params
167 * @returns {Object} The matching item or throw an error
168 */
169export const findOneValueByParamsThrowing = (params, items) =>
170 throwIfSingleResultError('Did not find exactly one', findOne(
171 // Compare all theeeqProps against each item
172 R.allPass(
173 // Create a eqProps for each prop of params
174 R.map(prop => R.eqProps(prop, params),
175 R.keys(params)
176 )
177 ),
178 R.values(items)
179 ).map(R.head));
180