From c3eca4025c9979b4dcbceee2685c7eb1b5aca479 Mon Sep 17 00:00:00 2001 From: Simon Ho Date: Wed, 12 Oct 2016 20:58:07 -0700 Subject: [PATCH] Support {defaultFn: 'shortid'} (#1110) - Backport of strongloop/loopback-datasource-juggler#1107 (takeover of strongloop/loopback-datasource-juggler#1101) - Squashed relevant commits --- lib/model.js | 4 ++++ package.json | 1 + test/manipulation.test.js | 21 +++++++++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/lib/model.js b/lib/model.js index 8d2994a5..d6a5ae7c 100644 --- a/lib/model.js +++ b/lib/model.js @@ -23,6 +23,7 @@ var utils = require('./utils'); var fieldsToArray = utils.fieldsToArray; var uuid = require('node-uuid'); var deprecated = require('depd')('loopback-datasource-juggler'); +var shortid = require('shortid'); // Set up an object for quick lookup var BASE_TYPES = { @@ -295,6 +296,9 @@ ModelBaseClass.prototype._initProperties = function(data, options) { case 'now': propVal = new Date(); break; + case 'shortid': + propVal = shortid.generate(); + break; default: // TODO Support user-provided functions via a registry of functions g.warn('Unknown default value provider %s', defn); diff --git a/package.json b/package.json index 76932dcd..10941a9e 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,7 @@ "minimatch": "^3.0.3", "node-uuid": "^1.4.2", "qs": "^3.1.0", + "shortid": "^2.2.6", "strong-globalize": "^2.6.2", "traverse": "^0.6.6" }, diff --git a/test/manipulation.test.js b/test/manipulation.test.js index eea23f43..d31a0a7c 100644 --- a/test/manipulation.test.js +++ b/test/manipulation.test.js @@ -1573,6 +1573,27 @@ describe('manipulation', function() { }); }); + describe('shortid defaultFn', function() { + var ModelWithShortId; + before(createModelWithShortId); + + it('should generate a new id when "defaultFn" is "shortid"', function(done) { + var SHORTID_REGEXP = /^[0-9a-z_\-]{7,14}$/i; + ModelWithShortId.create(function(err, modelWithShortId) { + if (err) return done(err); + modelWithShortId.shortid.should.match(SHORTID_REGEXP); + done(); + }); + }); + + function createModelWithShortId(cb) { + ModelWithShortId = db.define('ModelWithShortId', { + shortid: { type: String, defaultFn: 'shortid' }, + }); + db.automigrate('ModelWithShortId', cb); + } + }); + // it('should work when constructor called as function', function() { // var p = Person({name: 'John Resig'}); // p.should.be.an.instanceOf(Person);