Skip to content

Commit c3eca40

Browse files
authored
Support {defaultFn: 'shortid'} (#1110)
- Backport of #1107 (takeover of #1101) - Squashed relevant commits
1 parent a9d3816 commit c3eca40

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

lib/model.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ var utils = require('./utils');
2323
var fieldsToArray = utils.fieldsToArray;
2424
var uuid = require('node-uuid');
2525
var deprecated = require('depd')('loopback-datasource-juggler');
26+
var shortid = require('shortid');
2627

2728
// Set up an object for quick lookup
2829
var BASE_TYPES = {
@@ -295,6 +296,9 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
295296
case 'now':
296297
propVal = new Date();
297298
break;
299+
case 'shortid':
300+
propVal = shortid.generate();
301+
break;
298302
default:
299303
// TODO Support user-provided functions via a registry of functions
300304
g.warn('Unknown default value provider %s', defn);

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
"minimatch": "^3.0.3",
4848
"node-uuid": "^1.4.2",
4949
"qs": "^3.1.0",
50+
"shortid": "^2.2.6",
5051
"strong-globalize": "^2.6.2",
5152
"traverse": "^0.6.6"
5253
},

test/manipulation.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1573,6 +1573,27 @@ describe('manipulation', function() {
15731573
});
15741574
});
15751575

1576+
describe('shortid defaultFn', function() {
1577+
var ModelWithShortId;
1578+
before(createModelWithShortId);
1579+
1580+
it('should generate a new id when "defaultFn" is "shortid"', function(done) {
1581+
var SHORTID_REGEXP = /^[0-9a-z_\-]{7,14}$/i;
1582+
ModelWithShortId.create(function(err, modelWithShortId) {
1583+
if (err) return done(err);
1584+
modelWithShortId.shortid.should.match(SHORTID_REGEXP);
1585+
done();
1586+
});
1587+
});
1588+
1589+
function createModelWithShortId(cb) {
1590+
ModelWithShortId = db.define('ModelWithShortId', {
1591+
shortid: { type: String, defaultFn: 'shortid' },
1592+
});
1593+
db.automigrate('ModelWithShortId', cb);
1594+
}
1595+
});
1596+
15761597
// it('should work when constructor called as function', function() {
15771598
// var p = Person({name: 'John Resig'});
15781599
// p.should.be.an.instanceOf(Person);

0 commit comments

Comments
 (0)