11import _ 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
132152const 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