Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added Model.primary(name) to set the key #50

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ components:
clean:
rm -fr build components template.js

test:
test: build
@node test/server

.PHONY: clean test
14 changes: 14 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,20 @@ var Post = model('Post')
.attr('updated_at', { type: 'date' })
```

### .primary(name)

Set the primary attribute key's `name`.

```js
var model = require('model');

var Post = model('Post')
.attr('slug')
.attr('title')
.attr('body')
.primary('slug');
```

### .validate(fn)

TODO: validation callback docs
Expand Down
20 changes: 16 additions & 4 deletions lib/static.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ exports.url = function(path){
*
* User.headers({
* 'X-CSRF-Token': 'some token',
* 'X-API-Token': 'api token
* 'X-API-Token': 'api token
* });
*
* @param {String|Object} header(s)
Expand Down Expand Up @@ -88,9 +88,8 @@ exports.attr = function(name, options){
this.attrs[name] = options || {};

// implied pk
if ('_id' == name || 'id' == name) {
this.attrs[name].primaryKey = true;
this.primaryKey = name;
if (!this.primaryKey && ('_id' == name || 'id' == name)) {
this.primary(name);
}

// getter / setter method
Expand All @@ -109,6 +108,19 @@ exports.attr = function(name, options){
return this;
};

/**
* Set the primary attribute `name` for the model.
*
* @param {String} name
* @return {Function} self
* @api public
*/

exports.primary = function(name){
this.primaryKey = name;
return this;
};

/**
* Remove all and invoke `fn(err)`.
*
Expand Down
7 changes: 7 additions & 0 deletions test/statics.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ describe('Model.url(string)', function(){
})
})

describe('Model.primary(name)', function(){
it('should set the model primary key', function(){
User.primary('id');
assert('id' == User.primaryKey);
})
})

describe('Model.attrs', function(){
it('should hold the defined attrs', function(){
assert('string' == User.attrs.name.type);
Expand Down