From 31fc84cefb97ba42b9cee2de2a9a81a061421b69 Mon Sep 17 00:00:00 2001 From: Hannah Wolfe Date: Mon, 5 May 2014 16:18:38 +0100 Subject: [PATCH] Consistency in model method naming - The API has the BREAD naming for methods - The model now has findAll, findOne, findPage (where needed), edit, add and destroy, meaning it is similar but with a bit more flexibility - browse, read, update, create, and delete, which were effectively just aliases, have all been removed. - added jsDoc for the model methods --- core/server/api/settings.js | 8 +- core/server/api/users.js | 6 +- core/server/models/base.js | 106 +++++++------- core/server/models/index.js | 4 +- core/server/models/post.js | 130 +++++++++--------- core/server/models/settings.js | 4 +- core/server/models/user.js | 2 +- core/server/permissions/effective.js | 4 +- core/server/permissions/index.js | 6 +- core/test/integration/api/api_db_spec.js | 6 +- .../model/model_app_fields_spec.js | 12 +- .../model/model_app_settings_spec.js | 12 +- .../test/integration/model/model_apps_spec.js | 18 +-- .../model/model_permissions_spec.js | 28 ++-- .../integration/model/model_posts_spec.js | 36 ++--- .../integration/model/model_roles_spec.js | 37 +++-- .../integration/model/model_settings_spec.js | 24 ++-- .../test/integration/model/model_tags_spec.js | 28 ++-- .../integration/model/model_users_spec.js | 26 ++-- core/test/unit/permissions_spec.js | 22 +-- 20 files changed, 262 insertions(+), 257 deletions(-) diff --git a/core/server/api/settings.js b/core/server/api/settings.js index 6d61d5940e..3178782ff5 100644 --- a/core/server/api/settings.js +++ b/core/server/api/settings.js @@ -77,7 +77,7 @@ readSettingsResult = function (settingsModels) { if (settings.activeApps) { res = filterPaths(apps, JSON.parse(settings.activeApps.value)); - + settings.availableApps = { key: 'availableApps', value: res, @@ -172,7 +172,7 @@ settings = { if (!setting) { return when.reject({type: 'NotFound', message: 'Unable to find setting: ' + options.key}); } - + result[options.key] = setting; return when(settingsResult(result)); @@ -203,7 +203,7 @@ settings = { return settingsResult(readResult, type); }); }).otherwise(function (error) { - return dataProvider.Settings.read(key.key).then(function (result) { + return dataProvider.Settings.findOne(key.key).then(function (result) { if (!result) { return when.reject({type: 'NotFound', message: 'Unable to find setting: ' + key + '.'}); } @@ -212,7 +212,7 @@ settings = { }); } - return dataProvider.Settings.read(key).then(function (setting) { + return dataProvider.Settings.findOne(key).then(function (setting) { if (!setting) { return when.reject({type: 'NotFound', message: 'Unable to find setting: ' + key + '.'}); } diff --git a/core/server/api/users.js b/core/server/api/users.js index 9dc63d0ad8..522ddfbeb5 100644 --- a/core/server/api/users.js +++ b/core/server/api/users.js @@ -22,7 +22,7 @@ users = { browse: function browse(options) { // **returns:** a promise for a collection of users in a json object return canThis(this.user).browse.user().then(function () { - return dataProvider.User.browse(options).then(function (result) { + return dataProvider.User.findAll(options).then(function (result) { var omitted = {}, i; @@ -49,7 +49,7 @@ users = { args = {id: this.user}; } - return dataProvider.User.read(args).then(function (result) { + return dataProvider.User.findOne(args).then(function (result) { if (result) { var omitted = _.omit(result.toJSON(), filteredAttributes); return { users: [omitted] }; @@ -150,7 +150,7 @@ users = { }, doesUserExist: function doesUserExist() { - return dataProvider.User.browse().then(function (users) { + return dataProvider.User.findAll().then(function (users) { if (users.length === 0) { return false; } diff --git a/core/server/models/base.js b/core/server/models/base.js index cec3222e4c..eb1a1c3afb 100644 --- a/core/server/models/base.js +++ b/core/server/models/base.js @@ -1,3 +1,10 @@ +// # Base Model +// This is the model from which all other Ghost models extend. The model is based on Bookshelf.Model, and provides +// several basic behaviours such as UUIDs, as well as a set of Data methods for accessing information from the database. +// +// The models are internal to Ghost, only the API and some internal functions such as migration and import/export +// accesses the models directly. All other parts of Ghost, including the blog frontend, admin UI, and apps are only +// allowed to access data via the API. var Bookshelf = require('bookshelf'), when = require('when'), moment = require('moment'), @@ -11,17 +18,19 @@ var Bookshelf = require('bookshelf'), ghostBookshelf; -// Initializes a new Bookshelf instance, for reference elsewhere in Ghost. +// ### ghostBookshelf +// Initializes a new Bookshelf instance called ghostBookshelf, for reference elsewhere in Ghost. ghostBookshelf = Bookshelf.ghost = Bookshelf.initialize(config().database); ghostBookshelf.client = config().database.client; +// ### ghostBookshelf.Model // The Base Model which other Ghost objects will inherit from, // including some convenience functions as static properties on the model. ghostBookshelf.Model = ghostBookshelf.Model.extend({ hasTimestamps: true, - // get permitted attributs from schema.js + // Get permitted attributes from server/data/schema.js, which is where the DB schema is defined permittedAttributes: function () { return _.keys(schema.tables[this.tableName]); }, @@ -145,9 +154,13 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ }, { + // ## Model Data Functions + /** - * Naive find all + * ### Find All + * Naive find all fetches all the data for a particular model * @param {Object} options (optional) + * @return {Promise(ghostBookshelf.Collection)} Collection of all Models */ findAll: function (options) { options = options || {}; @@ -161,50 +174,44 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ }); }, - browse: function () { - return this.findAll.apply(this, arguments); - }, - /** - * Naive find one where args match - * @param {Object} args + * ### Find One + * Naive find one where data determines what to match on + * @param {Object} data * @param {Object} options (optional) + * @return {Promise(ghostBookshelf.Model)} Single Model */ - findOne: function (args, options) { + findOne: function (data, options) { options = options || {}; - return this.forge(args, {include: options.include}).fetch(options); - }, - - read: function () { - return this.findOne.apply(this, arguments); + return this.forge(data, {include: options.include}).fetch(options); }, /** + * ### Edit * Naive edit - * @param {Object} editedObj + * @param {Object} data * @param {Object} options (optional) + * @return {Promise(ghostBookshelf.Model)} Edited Model */ - edit: function (editedObj, options) { + edit: function (data, options) { options = options || {}; - return this.forge({id: editedObj.id}).fetch(options).then(function (foundObj) { - if (foundObj) { - return foundObj.save(editedObj, options); + return this.forge({id: data.id}).fetch(options).then(function (object) { + if (object) { + return object.save(data, options); } }); }, - update: function () { - return this.edit.apply(this, arguments); - }, - /** - * Naive create - * @param {Object} newObj + * ### Add + * Naive add + * @param {Object} data * @param {Object} options (optional) + * @return {Promise(ghostBookshelf.Model)} Newly Added Model */ - add: function (newObj, options) { + add: function (data, options) { options = options || {}; - var instance = this.forge(newObj); + var instance = this.forge(data); // We allow you to disable timestamps // when importing posts so that // the new posts `updated_at` value @@ -216,27 +223,27 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ return instance.save(null, options); }, - create: function () { - return this.add.apply(this, arguments); + /** + * ### Destroy + * Naive destroy + * @param {Object} data + * @param {Object} options (optional) + * @return {Promise(ghostBookshelf.Model)} Empty Model + */ + destroy: function (data, options) { + options = options || {}; + return this.forge({id: data}).destroy(options); }, /** - * Naive destroy - * @param {Object} _identifier - * @param {Object} options (optional) - */ - destroy: function (_identifier, options) { - options = options || {}; - return this.forge({id: _identifier}).destroy(options); - }, - - 'delete': function () { - return this.destroy.apply(this, arguments); - }, - - // #### generateSlug - // Create a string act as the permalink for an object. - generateSlug: function (Model, base, readOptions) { + * ### Generate Slug + * Create a string to act as the permalink for an object. + * @param {ghostBookshelf.Model} Model Model type to generate a slug for + * @param {String} base The string for which to generate a slug, usually a title or name + * @param {Object} options Options to pass to findOne + * @return {Promise(String)} Resolves to a unique slug string + */ + generateSlug: function (Model, base, options) { var slug, slugTryCount = 1, baseName = Model.prototype.tableName.replace(/s$/, ''), @@ -246,10 +253,10 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ checkIfSlugExists = function (slugToFind) { var args = {slug: slugToFind}; //status is needed for posts - if (readOptions && readOptions.status) { - args.status = readOptions.status; + if (options && options.status) { + args.status = options.status; } - return Model.findOne(args, readOptions).then(function (found) { + return Model.findOne(args, options).then(function (found) { var trimSpace; if (!found) { @@ -304,4 +311,5 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ }); +// Export ghostBookshelf for use elsewhere module.exports = ghostBookshelf; diff --git a/core/server/models/index.js b/core/server/models/index.js index 72e75c0d92..64ef0f7dd2 100644 --- a/core/server/models/index.js +++ b/core/server/models/index.js @@ -23,12 +23,12 @@ module.exports = { deleteAllContent: function () { var self = this; - return self.Post.browse().then(function (posts) { + return self.Post.findAll().then(function (posts) { return when.all(_.map(posts.toJSON(), function (post) { return self.Post.destroy(post.id); })); }).then(function () { - return self.Tag.browse().then(function (tags) { + return self.Tag.findAll().then(function (tags) { return when.all(_.map(tags.toJSON(), function (tag) { return self.Tag.destroy(tag.id); })); diff --git a/core/server/models/post.js b/core/server/models/post.js index 83dd460d52..1c81f94bb9 100644 --- a/core/server/models/post.js +++ b/core/server/models/post.js @@ -1,3 +1,4 @@ +// # Post Model var _ = require('lodash'), uuid = require('node-uuid'), when = require('when'), @@ -225,12 +226,13 @@ Post = ghostBookshelf.Model.extend({ attrs.author = attrs.author || attrs.author_id; delete attrs.author_id; - + return attrs; } }, { + // #### findAll // Extends base model findAll to eager-fetch author and user relationships. findAll: function (options) { @@ -239,24 +241,6 @@ Post = ghostBookshelf.Model.extend({ return ghostBookshelf.Model.findAll.call(this, options); }, - // #### findOne - // Extends base model findOne to eager-fetch author and user relationships. - findOne: function (args, options) { - options = options || {}; - - args = _.extend({ - status: 'published' - }, args || {}); - - if (args.status === 'all') { - delete args.status; - } - - // Add related objects - options.withRelated = _.union([ 'tags', 'fields' ], options.include); - - return ghostBookshelf.Model.findOne.call(this, args, options); - }, // #### findPage // Find results by page - returns an object containing the @@ -276,51 +260,51 @@ Post = ghostBookshelf.Model.extend({ // } /* - * @params {Object} opts + * @params {Object} options */ - findPage: function (opts) { + findPage: function (options) { + options = options || {}; + var postCollection = Posts.forge(), - tagInstance = opts.tag !== undefined ? Tag.forge({slug: opts.tag}) : false, + tagInstance = options.tag !== undefined ? Tag.forge({slug: options.tag}) : false, permittedOptions = ['page', 'limit', 'status', 'staticPages', 'include']; - // sanitize opts so we are not automatically passing through any and all - // query strings to Bookshelf / Knex. Although the API requires auth, we - // should prevent this until such time as we can design the API properly and safely. - opts = _.pick(opts, permittedOptions); + // sanitize options so we are not automatically passing through any and all query strings to Bookshelf / Knex. + options = _.pick(options, permittedOptions); // Set default settings for options - opts = _.extend({ + options = _.extend({ page: 1, // pagination page limit: 15, staticPages: false, // include static pages status: 'published', where: {} - }, opts); + }, options); - if (opts.staticPages !== 'all') { + if (options.staticPages !== 'all') { // convert string true/false to boolean - if (!_.isBoolean(opts.staticPages)) { - opts.staticPages = opts.staticPages === 'true' || opts.staticPages === '1' ? true : false; + if (!_.isBoolean(options.staticPages)) { + options.staticPages = options.staticPages === 'true' || options.staticPages === '1' ? true : false; } - opts.where.page = opts.staticPages; + options.where.page = options.staticPages; } // Unless `all` is passed as an option, filter on // the status provided. - if (opts.status !== 'all') { + if (options.status !== 'all') { // make sure that status is valid - opts.status = _.indexOf(['published', 'draft'], opts.status) !== -1 ? opts.status : 'published'; - opts.where.status = opts.status; + options.status = _.indexOf(['published', 'draft'], options.status) !== -1 ? options.status : 'published'; + options.where.status = options.status; } // If there are where conditionals specified, add those // to the query. - if (opts.where) { - postCollection.query('where', opts.where); + if (options.where) { + postCollection.query('where', options.where); } // Add related objects - opts.withRelated = _.union([ 'tags', 'fields' ], opts.include); + options.withRelated = _.union([ 'tags', 'fields' ], options.include); // If a query param for a tag is attached // we need to fetch the tag model to find its id @@ -347,12 +331,12 @@ Post = ghostBookshelf.Model.extend({ .query('where', 'posts_tags.tag_id', '=', tagInstance.id); } return postCollection - .query('limit', opts.limit) - .query('offset', opts.limit * (opts.page - 1)) + .query('limit', options.limit) + .query('offset', options.limit * (options.page - 1)) .query('orderBy', 'status', 'ASC') .query('orderBy', 'published_at', 'DESC') .query('orderBy', 'updated_at', 'DESC') - .fetch(_.omit(opts, 'page', 'limit')); + .fetch(_.omit(options, 'page', 'limit')); }) // Fetch pagination information @@ -365,8 +349,8 @@ Post = ghostBookshelf.Model.extend({ // the limits are for the pagination values. qb = ghostBookshelf.knex(tableName); - if (opts.where) { - qb.where(opts.where); + if (options.where) { + qb.where(options.where); } if (tagInstance) { @@ -380,21 +364,21 @@ Post = ghostBookshelf.Model.extend({ // Format response of data .then(function (resp) { var totalPosts = parseInt(resp[0].aggregate, 10), - calcPages = Math.ceil(totalPosts / opts.limit), + calcPages = Math.ceil(totalPosts / options.limit), pagination = {}, meta = {}, data = {}; - pagination['page'] = parseInt(opts.page, 10); - pagination['limit'] = opts.limit; + pagination['page'] = parseInt(options.page, 10); + pagination['limit'] = options.limit; pagination['pages'] = calcPages === 0 ? 1 : calcPages; pagination['total'] = totalPosts; pagination['next'] = null; pagination['prev'] = null; - if (opts.include) { + if (options.include) { _.each(postCollection.models, function (item) { - item.include = opts.include; + item.include = options.include; }); } @@ -425,26 +409,25 @@ Post = ghostBookshelf.Model.extend({ .catch(errors.logAndThrowError); }, - permissable: function (postModelOrId, context) { - var self = this, - userId = context.user, - postModel = postModelOrId; + // #### findOne + // Extends base model read to eager-fetch author and user relationships. + findOne: function (args, options) { + options = options || {}; - // If we passed in an id instead of a model, get the model - // then check the permissions - if (_.isNumber(postModelOrId) || _.isString(postModelOrId)) { - return this.read({id: postModelOrId, status: 'all'}).then(function (foundPostModel) { - return self.permissable(foundPostModel, context); - }, errors.logAndThrowError); + args = _.extend({ + status: 'published' + }, args || {}); + + if (args.status === 'all') { + delete args.status; } - // If this is the author of the post, allow it. - if (postModel && userId === postModel.get('author_id')) { - return when.resolve(); - } + // Add related objects + options.withRelated = _.union([ 'tags', 'fields' ], options.include); - return when.reject(); + return ghostBookshelf.Model.findOne.call(this, args, options); }, + add: function (newPostData, options) { var self = this; options = options || {}; @@ -480,6 +463,27 @@ Post = ghostBookshelf.Model.extend({ return post.destroy(options); }); + }, + + permissable: function (postModelOrId, context) { + var self = this, + userId = context.user, + postModel = postModelOrId; + + // If we passed in an id instead of a model, get the model + // then check the permissions + if (_.isNumber(postModelOrId) || _.isString(postModelOrId)) { + return this.findOne({id: postModelOrId, status: 'all'}).then(function (foundPostModel) { + return self.permissable(foundPostModel, context); + }, errors.logAndThrowError); + } + + // If this is the author of the post, allow it. + if (postModel && userId === postModel.get('author_id')) { + return when.resolve(); + } + + return when.reject(); } }); diff --git a/core/server/models/settings.js b/core/server/models/settings.js index 54829adaff..0278d0dde0 100644 --- a/core/server/models/settings.js +++ b/core/server/models/settings.js @@ -58,12 +58,12 @@ Settings = ghostBookshelf.Model.extend({ } }, { - read: function (_key) { + findOne: function (_key) { // Allow for just passing the key instead of attributes if (!_.isObject(_key)) { _key = { key: _key }; } - return when(ghostBookshelf.Model.read.call(this, _key)); + return when(ghostBookshelf.Model.findOne.call(this, _key)); }, edit: function (_data, options) { diff --git a/core/server/models/user.js b/core/server/models/user.js index 1499c68f5f..aac1ec7470 100644 --- a/core/server/models/user.js +++ b/core/server/models/user.js @@ -147,7 +147,7 @@ User = ghostBookshelf.Model.extend({ // If we passed in an id instead of a model, get the model // then check the permissions if (_.isNumber(userModelOrId) || _.isString(userModelOrId)) { - return this.read({id: userModelOrId}).then(function (foundUserModel) { + return this.findOne({id: userModelOrId}).then(function (foundUserModel) { return self.permissable(foundUserModel, context); }, errors.logAndThrowError); } diff --git a/core/server/permissions/effective.js b/core/server/permissions/effective.js index 9d4f30a280..dba9d06b94 100644 --- a/core/server/permissions/effective.js +++ b/core/server/permissions/effective.js @@ -6,7 +6,7 @@ var _ = require('lodash'), var effective = { user: function (id) { - return User.read({id: id}, { withRelated: ['permissions', 'roles.permissions'] }) + return User.findOne({id: id}, { withRelated: ['permissions', 'roles.permissions'] }) .then(function (foundUser) { var seenPerms = {}, rolePerms = _.map(foundUser.related('roles').models, function (role) { @@ -35,7 +35,7 @@ var effective = { }, app: function (appName) { - return App.read({name: appName}, { withRelated: ['permissions'] }) + return App.findOne({name: appName}, { withRelated: ['permissions'] }) .then(function (foundApp) { if (!foundApp) { return []; diff --git a/core/server/permissions/index.js b/core/server/permissions/index.js index 096e1e25f9..c6796f683e 100644 --- a/core/server/permissions/index.js +++ b/core/server/permissions/index.js @@ -30,7 +30,7 @@ function parseContext(context) { user: null, app: null }; - + if (context && (context === 'internal' || context.internal)) { parsed.internal = true; } @@ -158,7 +158,7 @@ CanThisResult.prototype.beginCheck = function (context) { // Resolve null if no context.user to prevent db call userPermissionLoad = when.resolve(null); } - + // Kick off loading of effective app permissions if necessary if (context.app) { @@ -204,7 +204,7 @@ canThis = function (context) { init = refresh = function () { // Load all the permissions - return PermissionsProvider.browse().then(function (perms) { + return PermissionsProvider.findAll().then(function (perms) { var seenActions = {}; exported.actionsMap = {}; diff --git a/core/test/integration/api/api_db_spec.js b/core/test/integration/api/api_db_spec.js index c446edb4b2..30f345550a 100644 --- a/core/test/integration/api/api_db_spec.js +++ b/core/test/integration/api/api_db_spec.js @@ -38,9 +38,9 @@ describe('DB API', function () { it('delete all content', function (done) { permissions.init().then(function () { return dbAPI.deleteAllContent.call({user: 1}); - }).then(function (result){ + }).then(function (result) { should.exist(result.message); - result.message.should.equal('Successfully deleted all content from your blog.') + result.message.should.equal('Successfully deleted all content from your blog.'); }).then(function () { TagsAPI.browse().then(function (results) { should.exist(results); @@ -54,7 +54,7 @@ describe('DB API', function () { done(); }); }).catch(function (error) { - done(new Error(JSON.stringify(error))); + done('error', error); }); }); diff --git a/core/test/integration/model/model_app_fields_spec.js b/core/test/integration/model/model_app_fields_spec.js index 0b031320b1..5d3f276b9e 100644 --- a/core/test/integration/model/model_app_fields_spec.js +++ b/core/test/integration/model/model_app_fields_spec.js @@ -39,8 +39,8 @@ describe('App Fields Model', function () { }).catch(done); }); - it('can browse', function (done) { - AppFieldsModel.browse().then(function (results) { + it('can findAll', function (done) { + AppFieldsModel.findAll().then(function (results) { should.exist(results); @@ -50,8 +50,8 @@ describe('App Fields Model', function () { }).catch(done); }); - it('can read', function (done) { - AppFieldsModel.read({id: 1}).then(function (foundAppField) { + it('can findOne', function (done) { + AppFieldsModel.findOne({id: 1}).then(function (foundAppField) { should.exist(foundAppField); done(); @@ -59,12 +59,12 @@ describe('App Fields Model', function () { }); it('can edit', function (done) { - AppFieldsModel.read({id: 1}).then(function (foundAppField) { + AppFieldsModel.findOne({id: 1}).then(function (foundAppField) { should.exist(foundAppField); return foundAppField.set({value: "350"}).save(); }).then(function () { - return AppFieldsModel.read({id: 1}); + return AppFieldsModel.findOne({id: 1}); }).then(function (updatedAppField) { should.exist(updatedAppField); diff --git a/core/test/integration/model/model_app_settings_spec.js b/core/test/integration/model/model_app_settings_spec.js index d91da53d18..140983bb2f 100644 --- a/core/test/integration/model/model_app_settings_spec.js +++ b/core/test/integration/model/model_app_settings_spec.js @@ -39,8 +39,8 @@ describe('App Setting Model', function () { }).catch(done); }); - it('can browse', function (done) { - AppSettingModel.browse().then(function (results) { + it('can findAll', function (done) { + AppSettingModel.findAll().then(function (results) { should.exist(results); @@ -50,8 +50,8 @@ describe('App Setting Model', function () { }).catch(done); }); - it('can read', function (done) { - AppSettingModel.read({id: 1}).then(function (foundAppSetting) { + it('can findOne', function (done) { + AppSettingModel.findOne({id: 1}).then(function (foundAppSetting) { should.exist(foundAppSetting); done(); @@ -59,12 +59,12 @@ describe('App Setting Model', function () { }); it('can edit', function (done) { - AppSettingModel.read({id: 1}).then(function (foundAppSetting) { + AppSettingModel.findOne({id: 1}).then(function (foundAppSetting) { should.exist(foundAppSetting); return foundAppSetting.set({value: "350"}).save(); }).then(function () { - return AppSettingModel.read({id: 1}); + return AppSettingModel.findOne({id: 1}); }).then(function (updatedAppSetting) { should.exist(updatedAppSetting); diff --git a/core/test/integration/model/model_apps_spec.js b/core/test/integration/model/model_apps_spec.js index 2a45190589..38a990d416 100644 --- a/core/test/integration/model/model_apps_spec.js +++ b/core/test/integration/model/model_apps_spec.js @@ -39,8 +39,8 @@ describe('App Model', function () { }).catch(done); }); - it('can browse', function (done) { - AppModel.browse().then(function (results) { + it('can findAll', function (done) { + AppModel.findAll().then(function (results) { should.exist(results); @@ -50,8 +50,8 @@ describe('App Model', function () { }).catch(done); }); - it('can read', function (done) { - AppModel.read({id: 1}).then(function (foundApp) { + it('can findOne', function (done) { + AppModel.findOne({id: 1}).then(function (foundApp) { should.exist(foundApp); done(); @@ -59,12 +59,12 @@ describe('App Model', function () { }); it('can edit', function (done) { - AppModel.read({id: 1}).then(function (foundApp) { + AppModel.findOne({id: 1}).then(function (foundApp) { should.exist(foundApp); return foundApp.set({name: "New App"}).save(); }).then(function () { - return AppModel.read({id: 1}); + return AppModel.findOne({id: 1}); }).then(function (updatedApp) { should.exist(updatedApp); @@ -87,12 +87,12 @@ describe('App Model', function () { }); it("can delete", function (done) { - AppModel.read({id: 1}).then(function (foundApp) { + AppModel.findOne({id: 1}).then(function (foundApp) { should.exist(foundApp); - return AppModel['delete'](1); + return AppModel.destroy(1); }).then(function () { - return AppModel.browse(); + return AppModel.findAll(); }).then(function (foundApp) { var hasRemovedId = foundApp.any(function (foundApp) { return foundApp.id === 1; diff --git a/core/test/integration/model/model_permissions_spec.js b/core/test/integration/model/model_permissions_spec.js index 2845b193da..f601b476e4 100644 --- a/core/test/integration/model/model_permissions_spec.js +++ b/core/test/integration/model/model_permissions_spec.js @@ -6,7 +6,7 @@ var testUtils = require('../../utils'), // Stuff we are testing Models = require('../../../server/models'); -describe("Permission Model", function () { +describe('Permission Model', function () { var PermissionModel = Models.Permission; @@ -30,8 +30,8 @@ describe("Permission Model", function () { }).catch(done); }); - it("can browse permissions", function (done) { - PermissionModel.browse().then(function (foundPermissions) { + it('can findAll', function (done) { + PermissionModel.findAll().then(function (foundPermissions) { should.exist(foundPermissions); foundPermissions.models.length.should.be.above(0); @@ -40,21 +40,21 @@ describe("Permission Model", function () { }).then(null, done); }); - it("can read permissions", function (done) { - PermissionModel.read({id: 1}).then(function (foundPermission) { + it('can findOne', function (done) { + PermissionModel.findOne({id: 1}).then(function (foundPermission) { should.exist(foundPermission); done(); }).catch(done); }); - it("can edit permissions", function (done) { - PermissionModel.read({id: 1}).then(function (foundPermission) { + it('can edit', function (done) { + PermissionModel.findOne({id: 1}).then(function (foundPermission) { should.exist(foundPermission); return foundPermission.set({name: "updated"}).save(); }).then(function () { - return PermissionModel.read({id: 1}); + return PermissionModel.findOne({id: 1}); }).then(function (updatedPermission) { should.exist(updatedPermission); @@ -64,9 +64,9 @@ describe("Permission Model", function () { }).catch(done); }); - it("can add permissions", function (done) { + it('can add', function (done) { var newPerm = { - name: "testperm1", + name: 'testperm1', object_type: 'test', action_type: 'test' }; @@ -80,13 +80,13 @@ describe("Permission Model", function () { }).catch(done); }); - it("can delete permissions", function (done) { - PermissionModel.read({id: 1}).then(function (foundPermission) { + it('can delete', function (done) { + PermissionModel.findOne({id: 1}).then(function (foundPermission) { should.exist(foundPermission); - return PermissionModel['delete'](1); + return PermissionModel.destroy(1); }).then(function () { - return PermissionModel.browse(); + return PermissionModel.findAll(); }).then(function (foundPermissions) { var hasRemovedId = foundPermissions.any(function (permission) { return permission.id === 1; diff --git a/core/test/integration/model/model_posts_spec.js b/core/test/integration/model/model_posts_spec.js index 6c0f72f298..78d44e5310 100644 --- a/core/test/integration/model/model_posts_spec.js +++ b/core/test/integration/model/model_posts_spec.js @@ -35,8 +35,8 @@ describe('Post Model', function () { }).catch(done); }); - it('can browse', function (done) { - PostModel.browse().then(function (results) { + it('can findAll', function (done) { + PostModel.findAll().then(function (results) { should.exist(results); results.length.should.be.above(1); @@ -48,18 +48,19 @@ describe('Post Model', function () { }).catch(done); }); - it('can read', function (done) { + it('can findOne', function (done) { var firstPost; - PostModel.browse().then(function (results) { + PostModel.findPage().then(function (results) { should.exist(results); - results.length.should.be.above(0); - firstPost = results.models[0]; + should.exist(results.posts); + results.posts.length.should.be.above(0); + firstPost = results.posts[0]; - return PostModel.read({slug: firstPost.attributes.slug}); + return PostModel.findOne({slug: firstPost.slug}); }).then(function (found) { should.exist(found); - found.attributes.title.should.equal(firstPost.attributes.title); + found.attributes.title.should.equal(firstPost.title); done(); }).catch(done); @@ -103,7 +104,7 @@ describe('Post Model', function () { it('can edit', function (done) { var firstPost; - PostModel.browse().then(function (results) { + PostModel.findAll().then(function (results) { should.exist(results); results.length.should.be.above(0); firstPost = results.models[0]; @@ -314,7 +315,7 @@ describe('Post Model', function () { // Should not have a conflicted slug from the first updatedSecondPost.get('slug').should.not.equal(firstPost.slug); - return PostModel.read({ + return PostModel.findOne({ id: updatedSecondPost.id, status: 'all' }); @@ -331,28 +332,21 @@ describe('Post Model', function () { it('can delete', function (done) { var firstPostId; - PostModel.browse().then(function (results) { + PostModel.findAll().then(function (results) { should.exist(results); results.length.should.be.above(0); firstPostId = results.models[0].id; return PostModel.destroy(firstPostId); }).then(function () { - return PostModel.browse(); + return PostModel.findOne({id: firstPostId}); }).then(function (newResults) { - var ids, hasDeletedId; - - ids = _.pluck(newResults.models, 'id'); - hasDeletedId = _.any(ids, function (id) { - return id === firstPostId; - }); - hasDeletedId.should.equal(false); - + should.equal(newResults, null); done(); }).catch(done); }); - it('can fetch a paginated set, with various options', function (done) { + it('can findPage, with various options', function (done) { testUtils.insertMorePosts().then(function () { return testUtils.insertMorePostsTags(); diff --git a/core/test/integration/model/model_roles_spec.js b/core/test/integration/model/model_roles_spec.js index c83e9d57c2..e26191fd89 100644 --- a/core/test/integration/model/model_roles_spec.js +++ b/core/test/integration/model/model_roles_spec.js @@ -1,12 +1,11 @@ /*globals describe, it, before, beforeEach, afterEach */ var testUtils = require('../../utils'), should = require('should'), - errors = require('../../../server/errorHandling'), // Stuff we are testing Models = require('../../../server/models'); -describe("Role Model", function () { +describe('Role Model', function () { var RoleModel = Models.Role; @@ -30,8 +29,8 @@ describe("Role Model", function () { }).catch(done); }); - it("can browse roles", function (done) { - RoleModel.browse().then(function (foundRoles) { + it('can findAll', function (done) { + RoleModel.findAll().then(function (foundRoles) { should.exist(foundRoles); foundRoles.models.length.should.be.above(0); @@ -40,34 +39,34 @@ describe("Role Model", function () { }).catch(done); }); - it("can read roles", function (done) { - RoleModel.read({id: 1}).then(function (foundRole) { + it('can findOne', function (done) { + RoleModel.findOne({id: 1}).then(function (foundRole) { should.exist(foundRole); done(); }).catch(done); }); - it("can edit roles", function (done) { - RoleModel.read({id: 1}).then(function (foundRole) { + it('can edit', function (done) { + RoleModel.findOne({id: 1}).then(function (foundRole) { should.exist(foundRole); - return foundRole.set({name: "updated"}).save(); + return foundRole.set({name: 'updated'}).save(); }).then(function () { - return RoleModel.read({id: 1}); + return RoleModel.findOne({id: 1}); }).then(function (updatedRole) { should.exist(updatedRole); - updatedRole.get("name").should.equal("updated"); + updatedRole.get('name').should.equal('updated'); done(); }).catch(done); }); - it("can add roles", function (done) { + it('can add', function (done) { var newRole = { - name: "test1", - description: "test1 description" + name: 'test1', + description: 'test1 description' }; RoleModel.add(newRole, {user: 1}).then(function (createdRole) { @@ -80,13 +79,13 @@ describe("Role Model", function () { }).catch(done); }); - it("can delete roles", function (done) { - RoleModel.read({id: 1}).then(function (foundRole) { + it('can delete', function (done) { + RoleModel.findOne({id: 1}).then(function (foundRole) { should.exist(foundRole); - return RoleModel['delete'](1); - }).then(function () { - return RoleModel.browse(); + return RoleModel.destroy(1); + }).then(function (destResp) { + return RoleModel.findAll(); }).then(function (foundRoles) { var hasRemovedId = foundRoles.any(function (role) { return role.id === 1; diff --git a/core/test/integration/model/model_settings_spec.js b/core/test/integration/model/model_settings_spec.js index a7e9c0071b..eac7361963 100644 --- a/core/test/integration/model/model_settings_spec.js +++ b/core/test/integration/model/model_settings_spec.js @@ -37,8 +37,8 @@ describe('Settings Model', function () { describe('API', function () { - it('can browse', function (done) { - SettingsModel.browse().then(function (results) { + it('can findAll', function (done) { + SettingsModel.findAll().then(function (results) { should.exist(results); @@ -48,10 +48,10 @@ describe('Settings Model', function () { }).catch(done); }); - it('can read', function (done) { + it('can findOne', function (done) { var firstSetting; - SettingsModel.browse().then(function (results) { + SettingsModel.findAll().then(function (results) { should.exist(results); @@ -59,7 +59,7 @@ describe('Settings Model', function () { firstSetting = results.models[0]; - return SettingsModel.read(firstSetting.attributes.key); + return SettingsModel.findOne(firstSetting.attributes.key); }).then(function (found) { @@ -74,7 +74,7 @@ describe('Settings Model', function () { it('can edit single', function (done) { - SettingsModel.browse().then(function (results) { + SettingsModel.findAll().then(function (results) { should.exist(results); @@ -103,7 +103,7 @@ describe('Settings Model', function () { model2, editedModel; - SettingsModel.browse().then(function (results) { + SettingsModel.findAll().then(function (results) { should.exist(results); @@ -156,7 +156,7 @@ describe('Settings Model', function () { it('can delete', function (done) { var settingId; - SettingsModel.browse().then(function (results) { + SettingsModel.findAll().then(function (results) { should.exist(results); @@ -170,13 +170,13 @@ describe('Settings Model', function () { }).then(function () { - return SettingsModel.browse(); + return SettingsModel.findAll(); }).then(function (newResults) { var ids, hasDeletedId; - ids = _.pluck(newResults.models, "id"); + ids = _.pluck(newResults.models, 'id'); hasDeletedId = _.any(ids, function (id) { return id === settingId; @@ -207,7 +207,7 @@ describe('Settings Model', function () { }).then(function (allSettings) { allSettings.length.should.be.above(0); - return SettingsModel.read('description'); + return SettingsModel.findOne('description'); }).then(function (descriptionSetting) { // Testing against the actual value in default-settings.json feels icky, // but it's easier to fix the test if that ever changes than to mock out that behaviour @@ -220,7 +220,7 @@ describe('Settings Model', function () { SettingsModel.add({key: 'description', value: 'Adam\'s Blog'}, {user: 1}).then(function () { return SettingsModel.populateDefaults(); }).then(function () { - return SettingsModel.read('description'); + return SettingsModel.findOne('description'); }).then(function (descriptionSetting) { descriptionSetting.get('value').should.equal('Adam\'s Blog'); done(); diff --git a/core/test/integration/model/model_tags_spec.js b/core/test/integration/model/model_tags_spec.js index 9b23dca0b7..9e62751ab1 100644 --- a/core/test/integration/model/model_tags_spec.js +++ b/core/test/integration/model/model_tags_spec.js @@ -49,7 +49,7 @@ describe('Tag Model', function () { createdPostID = createdPost.id; return createdPost.tags().attach(createdTag); }).then(function () { - return PostModel.read({id: createdPostID, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']}); }).then(function (postWithTag) { postWithTag.related('tags').length.should.equal(1); done(); @@ -77,11 +77,11 @@ describe('Tag Model', function () { createdTagID = createdTag.id; return createdPost.tags().attach(createdTag); }).then(function () { - return PostModel.read({id: createdPostID, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']}); }).then(function (postWithTag) { return postWithTag.tags().detach(createdTagID); }).then(function () { - return PostModel.read({id: createdPostID, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: createdPostID, status: 'all'}, { withRelated: ['tags']}); }).then(function (postWithoutTag) { postWithoutTag.related('tags').length.should.equal(0); done(); @@ -114,7 +114,7 @@ describe('Tag Model', function () { return postModel; }); }).then(function (postModel) { - return PostModel.read({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); }); } @@ -149,7 +149,7 @@ describe('Tag Model', function () { tagData.splice(1, 1); return postModel.set('tags', tagData).save(); }).then(function (postModel) { - return PostModel.read({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); }).then(function (reloadedPost) { var tagNames = reloadedPost.related('tags').models.map(function (t) { return t.attributes.name; }); tagNames.sort().should.eql(['tag1', 'tag3']); @@ -173,13 +173,13 @@ describe('Tag Model', function () { tagData.push({id: 3, name: 'tag3'}); return postModel.set('tags', tagData).save(); }).then(function () { - return PostModel.read({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); }).then(function (reloadedPost) { var tagModels = reloadedPost.related('tags').models, tagNames = tagModels.map(function (t) { return t.attributes.name; }), tagIds = _.pluck(tagModels, 'id'); tagNames.sort().should.eql(['tag1', 'tag2', 'tag3']); - + // make sure it hasn't just added a new tag with the same name // Don't expect a certain order in results - check for number of items! Math.max.apply(Math, tagIds).should.eql(4); @@ -199,7 +199,7 @@ describe('Tag Model', function () { tagData.push({id: null, name: 'tag3'}); return postModel.set('tags', tagData).save(null, {user: 1}); }).then(function (postModel) { - return PostModel.read({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); }).then(function (reloadedPost) { var tagNames = reloadedPost.related('tags').models.map(function (t) { return t.attributes.name; }); tagNames.sort().should.eql(['tag1', 'tag2', 'tag3']); @@ -220,7 +220,7 @@ describe('Tag Model', function () { tagData.push({id: null, name: 'tag3'}); return postModel.set('tags', tagData).save(null, {user: 1}); }).then(function (postModel) { - return PostModel.read({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); }).then(function (reloadedPost) { var tagNames = reloadedPost.related('tags').models.map(function (t) { return t.attributes.name; }); tagNames.sort().should.eql(['tag1', 'tag2', 'tag3']); @@ -248,14 +248,14 @@ describe('Tag Model', function () { return postModel.set('tags', tagData).save(null, {user: 1}); }).then(function () { - return PostModel.read({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); }).then(function (reloadedPost) { var tagModels = reloadedPost.related('tags').models, tagNames = tagModels.map(function (t) { return t.attributes.name; }), tagIds = _.pluck(tagModels, 'id'); tagNames.sort().should.eql(['tag1', 'tag2', 'tag3']); - + // make sure it hasn't just added a new tag with the same name // Don't expect a certain order in results - check for number of items! Math.max.apply(Math, tagIds).should.eql(4); @@ -284,7 +284,7 @@ describe('Tag Model', function () { return postModel.set('tags', tagData).save(null, {user: 1}); }).then(function () { - return PostModel.read({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: postModel.id, status: 'all'}, { withRelated: ['tags']}); }).then(function (reloadedPost) { var tagModels = reloadedPost.related('tags').models, tagNames = tagModels.map(function (t) { return t.get('name'); }), @@ -294,7 +294,7 @@ describe('Tag Model', function () { // make sure it hasn't just added a new tag with the same name // Don't expect a certain order in results - check for number of items! - Math.max.apply(Math, tagIds).should.eql(5); + Math.max.apply(Math, tagIds).should.eql(5); done(); }).catch(done); @@ -304,7 +304,7 @@ describe('Tag Model', function () { var newPost = _.extend(testUtils.DataGenerator.forModel.posts[0], {tags: [{name: 'test_tag_1'}]}) PostModel.add(newPost, {user: 1}).then(function (createdPost) { - return PostModel.read({id: createdPost.id, status: 'all'}, { withRelated: ['tags']}); + return PostModel.findOne({id: createdPost.id, status: 'all'}, { withRelated: ['tags']}); }).then(function (postWithTag) { postWithTag.related('tags').length.should.equal(1); done(); diff --git a/core/test/integration/model/model_users_spec.js b/core/test/integration/model/model_users_spec.js index d88185b52d..f1f4601bec 100644 --- a/core/test/integration/model/model_users_spec.js +++ b/core/test/integration/model/model_users_spec.js @@ -159,9 +159,9 @@ describe('User Model', function run() { }).catch(done); }); - it('can browse', function (done) { + it('can findAll', function (done) { - UserModel.browse().then(function (results) { + UserModel.findAll().then(function (results) { should.exist(results); results.length.should.be.above(0); @@ -171,10 +171,10 @@ describe('User Model', function run() { }).catch(done); }); - it('can read', function (done) { + it('can findOne', function (done) { var firstUser; - UserModel.browse().then(function (results) { + UserModel.findAll().then(function (results) { should.exist(results); @@ -182,7 +182,7 @@ describe('User Model', function run() { firstUser = results.models[0]; - return UserModel.read({email: firstUser.attributes.email}); + return UserModel.findOne({email: firstUser.attributes.email}); }).then(function (found) { @@ -199,7 +199,7 @@ describe('User Model', function run() { it('can edit', function (done) { var firstUser; - UserModel.browse().then(function (results) { + UserModel.findAll().then(function (results) { should.exist(results); @@ -223,7 +223,7 @@ describe('User Model', function run() { it('can delete', function (done) { var firstUserId; - UserModel.browse().then(function (results) { + UserModel.findAll().then(function (results) { should.exist(results); @@ -235,7 +235,7 @@ describe('User Model', function run() { }).then(function () { - return UserModel.browse(); + return UserModel.findAll(); }).then(function (newResults) { var ids, hasDeletedId; @@ -261,7 +261,7 @@ describe('User Model', function run() { var expires = Date.now() + 60000, dbHash = uuid.v4(); - UserModel.browse().then(function (results) { + UserModel.findAll().then(function (results) { return UserModel.generateResetToken(results.models[0].attributes.email, expires, dbHash); @@ -279,7 +279,7 @@ describe('User Model', function run() { var expires = Date.now() + 60000, dbHash = uuid.v4(); - UserModel.browse().then(function (results) { + UserModel.findAll().then(function (results) { return UserModel.generateResetToken(results.models[0].attributes.email, expires, dbHash); @@ -300,7 +300,7 @@ describe('User Model', function run() { expires = Date.now() + 60000, dbHash = uuid.v4(); - UserModel.browse().then(function (results) { + UserModel.findAll().then(function (results) { var firstUser = results.models[0], origPassword = firstUser.attributes.password; @@ -330,7 +330,7 @@ describe('User Model', function run() { expires = Date.now() - 60000, dbHash = uuid.v4(); - UserModel.browse().then(function (results) { + UserModel.findAll().then(function (results) { // Store email for later email = results.models[0].attributes.email; @@ -356,7 +356,7 @@ describe('User Model', function run() { var expires = Date.now() - 60000, dbHash = uuid.v4(); - UserModel.browse().then(function (results) { + UserModel.findAll().then(function (results) { return UserModel.generateResetToken(results.models[0].attributes.email, expires, dbHash); diff --git a/core/test/unit/permissions_spec.js b/core/test/unit/permissions_spec.js index c5a7d1977e..2ee860482b 100644 --- a/core/test/unit/permissions_spec.js +++ b/core/test/unit/permissions_spec.js @@ -115,7 +115,7 @@ describe('Permissions', function () { it('can add user to role', function (done) { var existingUserRoles; - UserProvider.read({id: 1}, { withRelated: ['roles'] }).then(function (foundUser) { + UserProvider.findOne({id: 1}, { withRelated: ['roles'] }).then(function (foundUser) { var testRole = new Models.Role({ name: 'testrole1', description: 'testrole1 description' @@ -131,7 +131,7 @@ describe('Permissions', function () { return foundUser.roles().attach(testRole); }); }).then(function () { - return UserProvider.read({id: 1}, { withRelated: ['roles'] }); + return UserProvider.findOne({id: 1}, { withRelated: ['roles'] }); }).then(function (updatedUser) { should.exist(updatedUser); @@ -142,7 +142,7 @@ describe('Permissions', function () { }); it('can add user permissions', function (done) { - Models.User.read({id: 1}, { withRelated: ['permissions']}).then(function (testUser) { + UserProvider.findOne({id: 1}, { withRelated: ['permissions']}).then(function (testUser) { var testPermission = new Models.Permission({ name: "test edit posts", action_type: 'edit', @@ -155,7 +155,7 @@ describe('Permissions', function () { return testUser.permissions().attach(testPermission); }); }).then(function () { - return Models.User.read({id: 1}, { withRelated: ['permissions']}); + return UserProvider.findOne({id: 1}, { withRelated: ['permissions']}); }).then(function (updatedUser) { should.exist(updatedUser); @@ -189,7 +189,7 @@ describe('Permissions', function () { }); }) .then(function () { - return Models.Role.read({id: testRole.id}, { withRelated: ['permissions']}); + return Models.Role.findOne({id: testRole.id}, { withRelated: ['permissions']}); }) .then(function (updatedRole) { should.exist(updatedRole); @@ -208,7 +208,7 @@ describe('Permissions', function () { createTestPermissions() .then(permissions.init) .then(function () { - return Models.User.read({id: 1}); + return UserProvider.findOne({id: 1}); }) .then(function (foundUser) { var canThisResult = permissions.canThis(foundUser); @@ -231,7 +231,7 @@ describe('Permissions', function () { createTestPermissions() .then(permissions.init) .then(function () { - return Models.User.read({id: 1}); + return UserProvider.findOne({id: 1}); }) .then(function (foundUser) { var newPerm = new Models.Permission({ @@ -245,7 +245,7 @@ describe('Permissions', function () { }); }) .then(function () { - return Models.User.read({id: 1}, { withRelated: ['permissions']}); + return UserProvider.findOne({id: 1}, { withRelated: ['permissions']}); }) .then(function (updatedUser) { @@ -270,7 +270,7 @@ describe('Permissions', function () { testUtils.insertAuthorUser() .then(function () { - return UserProvider.browse(); + return UserProvider.findAll(); }) .then(function (foundUser) { testUser = foundUser.models[1]; @@ -299,7 +299,7 @@ describe('Permissions', function () { testUtils.insertAuthorUser() .then(function () { - return UserProvider.browse(); + return UserProvider.findAll(); }) .then(function (foundUser) { testUser = foundUser.models[1]; @@ -345,7 +345,7 @@ describe('Permissions', function () { PostProvider.edit({id: 1, 'author_id': 2}) .then(function (updatedPost) { // Add user permissions - return Models.User.read({id: 1}) + return UserProvider.findOne({id: 1}) .then(function (foundUser) { var newPerm = new Models.Permission({ name: "app test edit post",