UNPKG

1.6 kBJavaScriptView Raw
1/*
2 * Copyright (c) 2018 One Hill Technologies, LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17const { plural } = require('pluralize');
18const { get, isArray, isString } = require ('lodash');
19
20module.exports = function (resources, component) {
21 let type, name;
22
23 if (isString (component)) {
24 // The component name is a string. This means we need to split the string
25 // such that the part before the colon is the type, and the part after the
26 // colon is the name.
27 [type, name] = component.split (':');
28 }
29 else if (isArray (component)) {
30 // The component name is an array. This means the first item is the type,
31 // and remaining values are the name of the resource.
32 [type, ...name] = component;
33 }
34 else {
35 throw new Error ('The component must be a String or an Array');
36 }
37
38 const types = plural (type);
39 const entities = resources[types];
40
41 if (!entities)
42 throw new Error (`${type} is not a valid type.`);
43
44 let entity = get (entities, name);
45
46 if (!entity)
47 throw new Error (`${component} does not exist.`);
48
49 return entity;
50};
51
\No newline at end of file