diff --git a/.gitignore b/.gitignore index 3f7cb55..ff77965 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ *.sublime-* .DS_Store node_modules +.idea \ No newline at end of file diff --git a/README.md b/README.md index 3faa8b2..90a902f 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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) + }); + }) }); ``` diff --git a/lib/plugin.js b/lib/plugin.js index 97d98cd..322068b 100644 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -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"))); + }); + }; + } + }; } diff --git a/package.json b/package.json index 16b39f9..e3419bf 100644 --- a/package.json +++ b/package.json @@ -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",