Skip to content
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
*.sublime-*
.DS_Store
node_modules
.idea
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ Any driver supported by ORM is supported by this plugin.
## Usage

```js
Model.pages(cb) // total pages
Model.page(page) // get page
Model.pages([conditions, ]cb) // total pages
Model.page([conditions, ]page) // get page
```

## Example
Expand Down Expand Up @@ -48,6 +48,14 @@ orm.connect("mysql://username:password@host/database", function (err, db) {
// should get you page 3, which means people from index 20 to 29 (ordered by name)
});
});

Person.pages({age: orm.gt(3)}, function(err, pages) {
console.log("Total pages: %d", pages);

Person.page({age: orm.gt(3)}, 3).order("name").run(function (err, people) {
// should get you page 3, which means people who's age is greater than 3 from index 20 to 29 (ordered by name)
});
})
});
```

48 changes: 31 additions & 17 deletions lib/plugin.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
module.exports = Plugin;

function Plugin(db) {
return {
define: function (Model) {
Model.settings.set("pagination.perpage", 20);
return {
define: function (Model) {
Model.settings.set("pagination.perpage", 20);

Model.page = function (n) {
var perpage = Model.settings.get("pagination.perpage");
Model.page = function (conditions, n) {
if (arguments.length == 1) {
n = conditions;
conditions = {};
}
else {
conditions = conditions || {};
}
var perpage = Model.settings.get("pagination.perpage");

return this.all().offset( (n - 1) * perpage ).limit(perpage);
};
return this.find(conditions).offset((n - 1) * perpage).limit(perpage);
};

Model.pages = function (cb) {
Model.count(function (err, count) {
if (err) {
return cb(err);
}
Model.pages = function (conditions, cb) {
if (arguments.length == 1) {
cb = conditions;
conditions = {};
}
else {
conditions = conditions || {};
}
Model.count(conditions, function (err, count) {
if (err) {
return cb(err);
}

return cb(null, Math.ceil(count / Model.settings.get("pagination.perpage")));
});
};
}
};
return cb(null, Math.ceil(count / Model.settings.get("pagination.perpage")));
});
};
}
};
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"orm",
"pagination"
],
"version" : "0.0.1",
"version" : "0.0.2",
"license" : "MIT",
"repository" : "http://github.com/dresende/node-orm-paging.git",
"main" : "./lib/plugin",
Expand Down