Skip to content

Commit

Permalink
Add models#getModel helper
Browse files Browse the repository at this point in the history
It provide a utility for getting majifix module models
already registered in mongoose odm plus a check on
thrown exception to allow ignore schema not registered error
  • Loading branch information
lykmapipo committed Jun 8, 2018
1 parent 987959e commit b534e6b
Show file tree
Hide file tree
Showing 5 changed files with 173 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# v0.3.0 / 2018-06-08
- Expose models name as constants
- Add get models helper

# v0.1.0 / 2018-05-22

Expand Down
28 changes: 28 additions & 0 deletions lib/models.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@


/* dependencies */
const mongoose = require('mongoose');
const { MissingSchemaError } = mongoose.Error;


/* constants */
Object.defineProperties(exports, {
JURISDICTION_MODEL_NAME: {
get: function () {
Expand Down Expand Up @@ -36,3 +39,28 @@ Object.defineProperties(exports, {
}
}
});


/* helpers */
exports.getModel = function getModel(modelName) {

//try obtain model
try {
const Model = mongoose.model(modelName);
return Model;
}

//catch error
catch (error) {

//ignore missing schema error
if (!(error instanceof MissingSchemaError)) {
throw error;
}

//unknown model
return undefined;

}

};
129 changes: 123 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"sinon-chai": "^3.0.0"
},
"dependencies": {
"lodash": "^4.17.10"
"lodash": "^4.17.10",
"mongoose": "^5.1.2"
}
}
19 changes: 19 additions & 0 deletions test/default.models.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

/* dependencies */
const path = require('path');
const mongoose = require('mongoose');
const { Schema } = mongoose;
const { expect } = require('chai');


Expand Down Expand Up @@ -56,6 +58,23 @@ describe('default', function () {
expect(common.models).to.be.eql(models);
});

it('should get model', function () {
expect(models.getModel).to.exist;
expect(models.getModel).to.be.a('function');
});

it('should get model', function () {
const Any = models.getModel('Any');
expect(Any).to.be.undefined;
});

it('should get model', function () {
mongoose.model('Any', new Schema({ name: String }));
const Any = models.getModel('Any');
expect(Any).to.exist;
});


});

});

0 comments on commit b534e6b

Please sign in to comment.