Skip to content

Commit f0fd287

Browse files
committed
mapOne( ) now throws a NotFoundError if a mapped object is not found
1 parent b8bc462 commit f0fd287

2 files changed

Lines changed: 28 additions & 6 deletions

File tree

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "join-js",
33
"description": "A library to map complex database joins to nested objects.",
4-
"version": "0.1.0",
4+
"version": "0.2.0",
55
"author": "Naresh Bhatia",
66
"license": "MIT",
77
"homepage": "https://github.com/archfirst/joinjs",
@@ -16,6 +16,7 @@
1616
"prepublish": "npm run build"
1717
},
1818
"dependencies": {
19+
"create-error": "^0.3.1",
1920
"lodash": "^3.10.0"
2021
},
2122
"devDependencies": {

src/index.js

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
import _ from 'lodash';
2+
import createError from 'create-error';
3+
4+
/** Thrown when mapOne does not find an object in the resultSet and "isRequired" is passed in as true */
5+
let NotFoundError = createError('NotFoundError');
26

37
/**
48
* Maps a resultSet to a collection.
@@ -31,10 +35,26 @@ function map(resultSet, maps, mapId, columnPrefix) {
3135
* @param {Array} maps - an array of result maps
3236
* @param {String} mapId - mapId of the top-level objects in the resultSet
3337
* @param {String} [columnPrefix] - prefix that should be applied to the column names of the top-level objects
34-
* @returns {Object} one mapped object
38+
* @param {boolean} [isRequired] - is a mapped object required to be returned, default is true
39+
* @returns {Object} one mapped object or null
40+
* @throws {NotFoundError} if object is not found and isRequired is true
3541
*/
36-
function mapOne(resultSet, maps, mapId, columnPrefix) {
37-
return map(resultSet, maps, mapId, columnPrefix)[0];
42+
function mapOne(resultSet, maps, mapId, columnPrefix, isRequired) {
43+
if (isRequired === undefined) {
44+
isRequired = true;
45+
}
46+
47+
var mappedCollection = map(resultSet, maps, mapId, columnPrefix);
48+
49+
if (mappedCollection.length > 0) {
50+
return mappedCollection[0];
51+
}
52+
else if (isRequired) {
53+
throw new NotFoundError('EmptyResponse');
54+
}
55+
else {
56+
return null;
57+
}
3858
}
3959

4060
/**
@@ -131,7 +151,8 @@ function getIdProperty(resultMap) {
131151

132152
const joinjs = {
133153
map: map,
134-
mapOne: mapOne
154+
mapOne: mapOne,
155+
NotFoundError: NotFoundError
135156
};
136157

137-
export default joinjs;
158+
export default joinjs;

0 commit comments

Comments
 (0)