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
2014-05-05 19:18:38 +04:00
|
|
|
// # 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.
|
2014-09-07 00:16:14 +04:00
|
|
|
var _ = require('lodash'),
|
|
|
|
bookshelf = require('bookshelf'),
|
2016-05-19 14:49:22 +03:00
|
|
|
moment = require('moment'),
|
|
|
|
Promise = require('bluebird'),
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
ObjectId = require('bson-objectid'),
|
2015-06-14 18:58:49 +03:00
|
|
|
config = require('../../config'),
|
2016-02-12 14:56:27 +03:00
|
|
|
db = require('../../data/db'),
|
2015-06-14 18:58:49 +03:00
|
|
|
errors = require('../../errors'),
|
|
|
|
filters = require('../../filters'),
|
|
|
|
schema = require('../../data/schema'),
|
|
|
|
utils = require('../../utils'),
|
|
|
|
validation = require('../../data/validation'),
|
2015-11-11 21:24:24 +03:00
|
|
|
plugins = require('../plugins'),
|
2015-11-12 15:29:45 +03:00
|
|
|
i18n = require('../../i18n'),
|
2016-05-19 14:49:22 +03:00
|
|
|
|
2015-11-20 15:04:49 +03:00
|
|
|
ghostBookshelf,
|
|
|
|
proto;
|
2013-06-25 15:43:15 +04:00
|
|
|
|
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
2014-05-05 19:18:38 +04:00
|
|
|
// ### ghostBookshelf
|
|
|
|
// Initializes a new Bookshelf instance called ghostBookshelf, for reference elsewhere in Ghost.
|
2016-02-12 14:56:27 +03:00
|
|
|
ghostBookshelf = bookshelf(db.knex);
|
2014-08-14 01:58:12 +04:00
|
|
|
|
2015-06-17 16:55:39 +03:00
|
|
|
// Load the Bookshelf registry plugin, which helps us avoid circular dependencies
|
2014-07-13 15:17:18 +04:00
|
|
|
ghostBookshelf.plugin('registry');
|
2013-06-25 15:43:15 +04:00
|
|
|
|
2015-11-11 21:12:18 +03:00
|
|
|
// Load the Ghost access rules plugin, which handles passing permissions/context through the model layer
|
|
|
|
ghostBookshelf.plugin(plugins.accessRules);
|
|
|
|
|
2015-11-11 20:52:44 +03:00
|
|
|
// Load the Ghost filter plugin, which handles applying a 'filter' to findPage requests
|
|
|
|
ghostBookshelf.plugin(plugins.filter);
|
|
|
|
|
2015-11-03 14:38:29 +03:00
|
|
|
// Load the Ghost include count plugin, which allows for the inclusion of cross-table counts
|
2015-11-11 21:24:24 +03:00
|
|
|
ghostBookshelf.plugin(plugins.includeCount);
|
2015-11-03 14:38:29 +03:00
|
|
|
|
2015-06-17 16:55:39 +03:00
|
|
|
// Load the Ghost pagination plugin, which gives us the `fetchPage` method on Models
|
2015-11-11 21:24:24 +03:00
|
|
|
ghostBookshelf.plugin(plugins.pagination);
|
2015-06-17 16:55:39 +03:00
|
|
|
|
2015-11-20 15:04:49 +03:00
|
|
|
// Cache an instance of the base model prototype
|
|
|
|
proto = ghostBookshelf.Model.prototype;
|
|
|
|
|
2015-06-17 16:55:39 +03:00
|
|
|
// ## ghostBookshelf.Model
|
2013-06-25 15:43:15 +04:00
|
|
|
// The Base Model which other Ghost objects will inherit from,
|
|
|
|
// including some convenience functions as static properties on the model.
|
2013-09-23 02:20:08 +04:00
|
|
|
ghostBookshelf.Model = ghostBookshelf.Model.extend({
|
2015-06-17 16:55:39 +03:00
|
|
|
// Bookshelf `hasTimestamps` - handles created_at and updated_at properties
|
2013-09-14 23:01:46 +04:00
|
|
|
hasTimestamps: true,
|
|
|
|
|
2015-06-17 16:55:39 +03:00
|
|
|
// Ghost option handling - get permitted attributes from server/data/schema.js, where the DB schema is defined
|
2015-06-14 18:58:49 +03:00
|
|
|
permittedAttributes: function permittedAttributes() {
|
2014-02-19 17:57:26 +04:00
|
|
|
return _.keys(schema.tables[this.tableName]);
|
|
|
|
},
|
|
|
|
|
2015-06-17 16:55:39 +03:00
|
|
|
// Bookshelf `defaults` - default values setup on every model creation
|
2015-06-14 18:58:49 +03:00
|
|
|
defaults: function defaults() {
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
return {};
|
2013-09-14 23:01:46 +04:00
|
|
|
},
|
|
|
|
|
2016-07-18 23:21:47 +03:00
|
|
|
// When loading an instance, subclasses can specify default to fetch
|
|
|
|
defaultColumnsToFetch: function defaultColumnsToFetch() {
|
|
|
|
return [];
|
|
|
|
},
|
|
|
|
|
2015-06-17 16:55:39 +03:00
|
|
|
// Bookshelf `initialize` - declare a constructor-like method for model creation
|
2015-06-14 18:58:49 +03:00
|
|
|
initialize: function initialize() {
|
2014-04-27 20:58:34 +04:00
|
|
|
var self = this,
|
|
|
|
options = arguments[1] || {};
|
|
|
|
|
|
|
|
// make options include available for toJSON()
|
|
|
|
if (options.include) {
|
|
|
|
this.include = _.clone(options.include);
|
|
|
|
}
|
|
|
|
|
2016-10-14 15:37:01 +03:00
|
|
|
['fetching', 'fetched', 'creating', 'created', 'updating', 'updated', 'destroying', 'destroyed', 'saved']
|
|
|
|
.forEach(function (eventName) {
|
|
|
|
var functionName = 'on' + eventName[0].toUpperCase() + eventName.slice(1);
|
|
|
|
|
|
|
|
if (!self[functionName]) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
self.on(eventName, function eventTriggered() {
|
|
|
|
return this[functionName].apply(this, arguments);
|
|
|
|
});
|
2014-02-19 17:57:26 +04:00
|
|
|
});
|
2016-10-14 15:37:01 +03:00
|
|
|
|
|
|
|
this.on('saving', function onSaving() {
|
|
|
|
var self = this,
|
|
|
|
args = arguments;
|
|
|
|
|
|
|
|
return Promise.resolve(self.onSaving.apply(self, args))
|
|
|
|
.then(function validated() {
|
|
|
|
return Promise.resolve(self.onValidate.apply(self, args));
|
|
|
|
});
|
2014-02-19 17:57:26 +04:00
|
|
|
});
|
|
|
|
},
|
|
|
|
|
2016-10-14 15:37:01 +03:00
|
|
|
onValidate: function onValidate() {
|
2014-05-05 17:51:21 +04:00
|
|
|
return validation.validateSchema(this.tableName, this.toJSON());
|
2013-09-14 23:01:46 +04:00
|
|
|
},
|
|
|
|
|
2016-10-14 15:37:01 +03:00
|
|
|
onCreating: function onCreating(newObj, attr, options) {
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
// id = 0 is still a valid value for external usage
|
|
|
|
if (_.isUndefined(newObj.id) || _.isNull(newObj.id)) {
|
|
|
|
newObj.setId();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (schema.tables[this.tableName].hasOwnProperty('created_by') && !this.get('created_by')) {
|
2014-07-15 15:03:12 +04:00
|
|
|
this.set('created_by', this.contextUser(options));
|
2013-09-14 23:01:46 +04:00
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2016-10-14 15:37:01 +03:00
|
|
|
onSaving: function onSaving(newObj, attr, options) {
|
2014-04-03 17:03:09 +04:00
|
|
|
// Remove any properties which don't belong on the model
|
2014-02-19 17:57:26 +04:00
|
|
|
this.attributes = this.pick(this.permittedAttributes());
|
2014-04-22 05:04:30 +04:00
|
|
|
// Store the previous attributes so we can tell what was updated later
|
|
|
|
this._updatedAttributes = newObj.previousAttributes();
|
|
|
|
|
2014-07-15 15:03:12 +04:00
|
|
|
this.set('updated_by', this.contextUser(options));
|
2013-09-14 23:01:46 +04:00
|
|
|
},
|
|
|
|
|
2016-06-03 11:06:18 +03:00
|
|
|
/**
|
|
|
|
* before we insert dates into the database, we have to normalize
|
|
|
|
* date format is now in each db the same
|
|
|
|
*/
|
|
|
|
fixDatesWhenSave: function fixDates(attrs) {
|
2014-07-05 18:57:56 +04:00
|
|
|
var self = this;
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
_.each(attrs, function each(value, key) {
|
2014-07-24 12:17:10 +04:00
|
|
|
if (value !== null
|
|
|
|
&& schema.tables[self.tableName].hasOwnProperty(key)
|
|
|
|
&& schema.tables[self.tableName][key].type === 'dateTime') {
|
2016-06-03 11:06:18 +03:00
|
|
|
attrs[key] = moment(value).format('YYYY-MM-DD HH:mm:ss');
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return attrs;
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* all supported databases (pg, sqlite, mysql) return different values
|
|
|
|
*
|
|
|
|
* sqlite:
|
|
|
|
* - knex returns a UTC String
|
|
|
|
* pg:
|
|
|
|
* - has an active UTC session through knex and returns UTC Date
|
|
|
|
* mysql:
|
|
|
|
* - knex wraps the UTC value into a local JS Date
|
|
|
|
*/
|
|
|
|
fixDatesWhenFetch: function fixDates(attrs) {
|
|
|
|
var self = this;
|
|
|
|
|
|
|
|
_.each(attrs, function each(value, key) {
|
|
|
|
if (value !== null
|
|
|
|
&& schema.tables[self.tableName].hasOwnProperty(key)
|
|
|
|
&& schema.tables[self.tableName][key].type === 'dateTime') {
|
2014-07-05 18:57:56 +04:00
|
|
|
attrs[key] = moment(value).toDate();
|
2013-07-08 15:39:11 +04:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return attrs;
|
|
|
|
},
|
|
|
|
|
2014-04-25 11:55:53 +04:00
|
|
|
// Convert integers to real booleans
|
2015-06-14 18:58:49 +03:00
|
|
|
fixBools: function fixBools(attrs) {
|
2014-04-25 11:55:53 +04:00
|
|
|
var self = this;
|
2015-06-14 18:58:49 +03:00
|
|
|
_.each(attrs, function each(value, key) {
|
2014-07-24 12:17:10 +04:00
|
|
|
if (schema.tables[self.tableName].hasOwnProperty(key)
|
|
|
|
&& schema.tables[self.tableName][key].type === 'bool') {
|
2014-04-25 11:55:53 +04:00
|
|
|
attrs[key] = value ? true : false;
|
2014-01-05 02:16:29 +04:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return attrs;
|
|
|
|
},
|
|
|
|
|
2014-07-15 15:03:12 +04:00
|
|
|
// Get the user from the options object
|
2015-06-14 18:58:49 +03:00
|
|
|
contextUser: function contextUser(options) {
|
2016-11-09 18:01:07 +03:00
|
|
|
options = options || {};
|
|
|
|
options.context = options.context || {};
|
|
|
|
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
if (options.context.user || ghostBookshelf.Model.isExternalUser(options.context.user)) {
|
2014-07-15 15:03:12 +04:00
|
|
|
return options.context.user;
|
2016-11-09 18:01:07 +03:00
|
|
|
} else if (options.context.internal) {
|
|
|
|
return ghostBookshelf.Model.internalUser;
|
|
|
|
} else if (this.get('id')) {
|
|
|
|
return this.get('id');
|
|
|
|
} else if (options.context.external) {
|
|
|
|
return ghostBookshelf.Model.externalUser;
|
2014-07-15 15:03:12 +04:00
|
|
|
} else {
|
2016-10-06 15:27:35 +03:00
|
|
|
throw new errors.NotFoundError({
|
|
|
|
message: i18n.t('errors.models.base.index.missingContext'),
|
|
|
|
level: 'critical'
|
|
|
|
});
|
2014-07-15 15:03:12 +04:00
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2014-04-25 11:55:53 +04:00
|
|
|
// format date before writing to DB, bools work
|
2015-06-14 18:58:49 +03:00
|
|
|
format: function format(attrs) {
|
2016-06-03 11:06:18 +03:00
|
|
|
return this.fixDatesWhenSave(attrs);
|
2014-04-25 11:55:53 +04:00
|
|
|
},
|
|
|
|
|
|
|
|
// format data and bool when fetching from DB
|
2015-06-14 18:58:49 +03:00
|
|
|
parse: function parse(attrs) {
|
2016-06-03 11:06:18 +03:00
|
|
|
return this.fixBools(this.fixDatesWhenFetch(attrs));
|
2013-07-08 15:39:11 +04:00
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
toJSON: function toJSON(options) {
|
2014-04-25 11:55:53 +04:00
|
|
|
var attrs = _.extend({}, this.attributes),
|
2014-04-27 20:58:34 +04:00
|
|
|
self = this;
|
2014-07-08 20:00:59 +04:00
|
|
|
options = options || {};
|
2015-04-22 22:20:27 +03:00
|
|
|
options = _.pick(options, ['shallow', 'baseKey', 'include', 'context']);
|
2013-07-08 15:39:11 +04:00
|
|
|
|
|
|
|
if (options && options.shallow) {
|
|
|
|
return attrs;
|
|
|
|
}
|
|
|
|
|
2014-07-08 20:00:59 +04:00
|
|
|
if (options && options.include) {
|
|
|
|
this.include = _.union(this.include, options.include);
|
|
|
|
}
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
_.each(this.relations, function each(relation, key) {
|
2013-09-24 14:46:30 +04:00
|
|
|
if (key.substring(0, 7) !== '_pivot_') {
|
2014-04-27 20:58:34 +04:00
|
|
|
// if include is set, expand to full object
|
2015-04-22 22:20:27 +03:00
|
|
|
var fullKey = _.isEmpty(options.baseKey) ? key : options.baseKey + '.' + key;
|
2016-06-11 21:23:27 +03:00
|
|
|
if (_.includes(self.include, fullKey)) {
|
2015-04-22 22:20:27 +03:00
|
|
|
attrs[key] = relation.toJSON(_.extend({}, options, {baseKey: fullKey, include: self.include}));
|
2014-04-27 20:58:34 +04:00
|
|
|
}
|
2013-08-21 16:55:58 +04:00
|
|
|
}
|
2013-07-08 15:39:11 +04:00
|
|
|
});
|
|
|
|
|
2015-11-20 15:04:49 +03:00
|
|
|
// @TODO upgrade bookshelf & knex and use serialize & toJSON to do this in a neater way (see #6103)
|
|
|
|
return proto.finalize.call(this, attrs);
|
2013-09-14 23:01:46 +04:00
|
|
|
},
|
|
|
|
|
2014-04-22 05:04:30 +04:00
|
|
|
// Get attributes that have been updated (values before a .save() call)
|
2015-06-14 18:58:49 +03:00
|
|
|
updatedAttributes: function updatedAttributes() {
|
2014-04-22 05:04:30 +04:00
|
|
|
return this._updatedAttributes || {};
|
|
|
|
},
|
|
|
|
|
|
|
|
// Get a specific updated attribute value
|
2015-06-14 18:58:49 +03:00
|
|
|
updated: function updated(attr) {
|
2014-04-22 05:04:30 +04:00
|
|
|
return this.updatedAttributes()[attr];
|
2016-05-19 14:49:22 +03:00
|
|
|
},
|
|
|
|
|
|
|
|
hasDateChanged: function (attr) {
|
|
|
|
return moment(this.get(attr)).diff(moment(this.updated(attr))) !== 0;
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* we auto generate a GUID for each resource
|
|
|
|
* no auto increment
|
|
|
|
*/
|
|
|
|
setId: function setId() {
|
|
|
|
this.set('id', ObjectId.generate());
|
2013-07-08 15:39:11 +04:00
|
|
|
}
|
2013-06-25 15:43:15 +04:00
|
|
|
}, {
|
Refactor API arguments
closes #2610, refs #2697
- cleanup API index.js, and add docs
- all API methods take consistent arguments: object & options
- browse, read, destroy take options, edit and add take object and options
- the context is passed as part of options, meaning no more .call
everywhere
- destroy expects an object, rather than an id all the way down to the model layer
- route params such as :id, :slug, and :key are passed as an option & used
to perform reads, updates and deletes where possible - settings / themes
may need work here still
- HTTP posts api can find a post by slug
- Add API utils for checkData
2014-05-08 16:41:19 +04:00
|
|
|
// ## Data Utility Functions
|
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
2014-05-05 19:18:38 +04:00
|
|
|
|
2016-11-09 18:01:07 +03:00
|
|
|
/**
|
|
|
|
* please use these static definitions when comparing id's
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
* we keep type number, because we have too many check's where we rely on
|
|
|
|
* context.user ? true : false (if context.user is 0 as number, this condition is false)
|
2016-11-09 18:01:07 +03:00
|
|
|
*/
|
|
|
|
internalUser: 1,
|
|
|
|
ownerUser: 1,
|
|
|
|
externalUser: 0,
|
|
|
|
|
|
|
|
isOwnerUser: function isOwnerUser(id) {
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
return id === ghostBookshelf.Model.ownerUser || id === ghostBookshelf.Model.ownerUser.toString();
|
2016-11-09 18:01:07 +03:00
|
|
|
},
|
|
|
|
|
|
|
|
isInternalUser: function isInternalUser(id) {
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
return id === ghostBookshelf.Model.internalUser || id === ghostBookshelf.Model.internalUser.toString();
|
2016-11-09 18:01:07 +03:00
|
|
|
},
|
|
|
|
|
|
|
|
isExternalUser: function isExternalUser(id) {
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
return id === ghostBookshelf.Model.externalUser || id === ghostBookshelf.Model.externalUser.toString();
|
2016-11-09 18:01:07 +03:00
|
|
|
},
|
|
|
|
|
2014-05-06 05:45:08 +04:00
|
|
|
/**
|
|
|
|
* Returns an array of keys permitted in every method's `options` hash.
|
|
|
|
* Can be overridden and added to by a model's `permittedOptions` method.
|
2016-06-03 11:06:18 +03:00
|
|
|
*
|
|
|
|
* importing: is used when import a JSON file or when migrating the database
|
|
|
|
*
|
2015-10-10 19:07:10 +03:00
|
|
|
* @return {Object} Keys allowed in the `options` hash of every model's method.
|
2014-05-06 05:45:08 +04:00
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
permittedOptions: function permittedOptions() {
|
2014-05-06 05:45:08 +04:00
|
|
|
// terms to whitelist for all methods.
|
2016-06-03 11:06:18 +03:00
|
|
|
return ['context', 'include', 'transacting', 'importing'];
|
2014-05-06 05:45:08 +04:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Filters potentially unsafe model attributes, so you can pass them to Bookshelf / Knex.
|
|
|
|
* @param {Object} data Has keys representing the model's attributes/fields in the database.
|
|
|
|
* @return {Object} The filtered results of the passed in data, containing only what's allowed in the schema.
|
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
filterData: function filterData(data) {
|
2014-05-06 05:45:08 +04:00
|
|
|
var permittedAttributes = this.prototype.permittedAttributes(),
|
|
|
|
filteredData = _.pick(data, permittedAttributes);
|
|
|
|
|
|
|
|
return filteredData;
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Filters potentially unsafe `options` in a model method's arguments, so you can pass them to Bookshelf / Knex.
|
|
|
|
* @param {Object} options Represents options to filter in order to be passed to the Bookshelf query.
|
|
|
|
* @param {String} methodName The name of the method to check valid options for.
|
|
|
|
* @return {Object} The filtered results of `options`.
|
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
filterOptions: function filterOptions(options, methodName) {
|
2014-05-06 05:45:08 +04:00
|
|
|
var permittedOptions = this.permittedOptions(methodName),
|
|
|
|
filteredOptions = _.pick(options, permittedOptions);
|
|
|
|
|
|
|
|
return filteredOptions;
|
|
|
|
},
|
|
|
|
|
2015-05-01 00:14:19 +03:00
|
|
|
// ## Model Data Functions
|
Refactor API arguments
closes #2610, refs #2697
- cleanup API index.js, and add docs
- all API methods take consistent arguments: object & options
- browse, read, destroy take options, edit and add take object and options
- the context is passed as part of options, meaning no more .call
everywhere
- destroy expects an object, rather than an id all the way down to the model layer
- route params such as :id, :slug, and :key are passed as an option & used
to perform reads, updates and deletes where possible - settings / themes
may need work here still
- HTTP posts api can find a post by slug
- Add API utils for checkData
2014-05-08 16:41:19 +04:00
|
|
|
|
2013-06-25 15:43:15 +04:00
|
|
|
/**
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* ### Find All
|
2016-04-14 18:54:49 +03:00
|
|
|
* Fetches all the data for a particular model
|
2014-04-21 22:04:20 +04:00
|
|
|
* @param {Object} options (optional)
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* @return {Promise(ghostBookshelf.Collection)} Collection of all Models
|
2013-06-25 15:43:15 +04:00
|
|
|
*/
|
2015-06-17 16:55:39 +03:00
|
|
|
findAll: function findAll(options) {
|
2014-05-06 05:45:08 +04:00
|
|
|
options = this.filterOptions(options, 'findAll');
|
2015-10-10 19:07:10 +03:00
|
|
|
options.withRelated = _.union(options.withRelated, options.include);
|
2016-04-14 18:54:49 +03:00
|
|
|
|
|
|
|
var itemCollection = this.forge(null, {context: options.context});
|
|
|
|
|
|
|
|
// transforms fictive keywords like 'all' (status:all) into correct allowed values
|
|
|
|
if (this.processOptions) {
|
|
|
|
this.processOptions(options);
|
|
|
|
}
|
|
|
|
|
|
|
|
itemCollection.applyDefaultAndCustomFilters(options);
|
|
|
|
|
|
|
|
return itemCollection.fetchAll(options).then(function then(result) {
|
2014-04-27 20:58:34 +04:00
|
|
|
if (options.include) {
|
2015-06-14 18:58:49 +03:00
|
|
|
_.each(result.models, function each(item) {
|
2014-04-27 20:58:34 +04:00
|
|
|
item.include = options.include;
|
|
|
|
});
|
|
|
|
}
|
2016-10-12 18:18:57 +03:00
|
|
|
|
2014-04-27 20:58:34 +04:00
|
|
|
return result;
|
|
|
|
});
|
2013-06-25 15:43:15 +04:00
|
|
|
},
|
|
|
|
|
2015-06-17 16:55:39 +03:00
|
|
|
/**
|
|
|
|
* ### Find Page
|
|
|
|
* Find results by page - returns an object containing the
|
|
|
|
* information about the request (page, limit), along with the
|
|
|
|
* info needed for pagination (pages, total).
|
|
|
|
*
|
|
|
|
* **response:**
|
|
|
|
*
|
|
|
|
* {
|
|
|
|
* posts: [
|
|
|
|
* {...}, ...
|
|
|
|
* ],
|
|
|
|
* page: __,
|
|
|
|
* limit: __,
|
|
|
|
* pages: __,
|
|
|
|
* total: __
|
|
|
|
* }
|
|
|
|
*
|
|
|
|
* @param {Object} options
|
|
|
|
*/
|
|
|
|
findPage: function findPage(options) {
|
|
|
|
options = options || {};
|
|
|
|
|
2016-07-18 23:21:47 +03:00
|
|
|
var self = this,
|
|
|
|
itemCollection = this.forge(null, {context: options.context}),
|
|
|
|
tableName = _.result(this.prototype, 'tableName'),
|
|
|
|
requestedColumns = options.columns;
|
2015-06-17 16:55:39 +03:00
|
|
|
|
2015-11-12 17:21:04 +03:00
|
|
|
// Set this to true or pass ?debug=true as an API option to get output
|
2016-10-11 15:53:52 +03:00
|
|
|
itemCollection.debug = options.debug && config.get('env') !== 'production';
|
2015-11-12 17:21:04 +03:00
|
|
|
|
2015-06-17 16:55:39 +03:00
|
|
|
// Filter options so that only permitted ones remain
|
|
|
|
options = this.filterOptions(options, 'findPage');
|
|
|
|
|
2015-11-11 22:31:52 +03:00
|
|
|
// This applies default properties like 'staticPages' and 'status'
|
|
|
|
// And then converts them to 'where' options... this behaviour is effectively deprecated in favour
|
|
|
|
// of using filter - it's only be being kept here so that we can transition cleanly.
|
2015-11-11 20:52:44 +03:00
|
|
|
this.processOptions(options);
|
2015-07-28 03:27:54 +03:00
|
|
|
|
2015-11-11 20:52:44 +03:00
|
|
|
// Add Filter behaviour
|
2016-04-14 18:54:49 +03:00
|
|
|
itemCollection.applyDefaultAndCustomFilters(options);
|
2015-06-17 16:55:39 +03:00
|
|
|
|
2015-10-24 23:39:47 +03:00
|
|
|
// Handle related objects
|
|
|
|
// TODO: this should just be done for all methods @ the API level
|
|
|
|
options.withRelated = _.union(options.withRelated, options.include);
|
2015-06-17 16:55:39 +03:00
|
|
|
|
2015-11-11 22:31:52 +03:00
|
|
|
// Ensure only valid fields/columns are added to query
|
2016-07-18 23:21:47 +03:00
|
|
|
// and append default columns to fetch
|
2015-11-11 22:31:52 +03:00
|
|
|
if (options.columns) {
|
|
|
|
options.columns = _.intersection(options.columns, this.prototype.permittedAttributes());
|
2016-07-18 23:21:47 +03:00
|
|
|
options.columns = _.union(options.columns, this.prototype.defaultColumnsToFetch());
|
2015-11-11 22:31:52 +03:00
|
|
|
}
|
|
|
|
|
2015-10-22 15:49:15 +03:00
|
|
|
if (options.order) {
|
2015-11-21 00:20:00 +03:00
|
|
|
options.order = self.parseOrderOption(options.order, options.include);
|
2016-07-15 13:04:10 +03:00
|
|
|
} else if (self.orderDefaultRaw) {
|
|
|
|
options.orderRaw = self.orderDefaultRaw();
|
2015-10-22 15:49:15 +03:00
|
|
|
} else {
|
|
|
|
options.order = self.orderDefaultOptions();
|
|
|
|
}
|
2016-07-15 13:04:10 +03:00
|
|
|
|
2015-10-24 23:39:47 +03:00
|
|
|
return itemCollection.fetchPage(options).then(function formatResponse(response) {
|
2016-07-18 23:21:47 +03:00
|
|
|
var data = {},
|
|
|
|
models = [];
|
|
|
|
|
|
|
|
options.columns = requestedColumns;
|
|
|
|
models = response.collection.toJSON(options);
|
2016-03-29 20:36:04 +03:00
|
|
|
|
|
|
|
// re-add any computed properties that were stripped out before the call to fetchPage
|
2016-07-18 23:21:47 +03:00
|
|
|
// pick only requested before returning JSON
|
|
|
|
data[tableName] = _.map(models, function transform(model) {
|
|
|
|
return options.columns ? _.pick(model, options.columns) : model;
|
|
|
|
});
|
2015-10-24 23:39:47 +03:00
|
|
|
data.meta = {pagination: response.pagination};
|
|
|
|
return data;
|
2015-11-03 14:38:29 +03:00
|
|
|
});
|
2015-06-17 16:55:39 +03:00
|
|
|
},
|
|
|
|
|
2013-06-25 15:43:15 +04:00
|
|
|
/**
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* ### Find One
|
|
|
|
* Naive find one where data determines what to match on
|
|
|
|
* @param {Object} data
|
2014-04-21 22:04:20 +04:00
|
|
|
* @param {Object} options (optional)
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* @return {Promise(ghostBookshelf.Model)} Single Model
|
2013-06-25 15:43:15 +04:00
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
findOne: function findOne(data, options) {
|
2014-05-06 05:45:08 +04:00
|
|
|
data = this.filterData(data);
|
|
|
|
options = this.filterOptions(options, 'findOne');
|
2016-09-21 17:48:14 +03:00
|
|
|
|
Refactor API arguments
closes #2610, refs #2697
- cleanup API index.js, and add docs
- all API methods take consistent arguments: object & options
- browse, read, destroy take options, edit and add take object and options
- the context is passed as part of options, meaning no more .call
everywhere
- destroy expects an object, rather than an id all the way down to the model layer
- route params such as :id, :slug, and :key are passed as an option & used
to perform reads, updates and deletes where possible - settings / themes
may need work here still
- HTTP posts api can find a post by slug
- Add API utils for checkData
2014-05-08 16:41:19 +04:00
|
|
|
// We pass include to forge so that toJSON has access
|
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
2014-05-05 19:18:38 +04:00
|
|
|
return this.forge(data, {include: options.include}).fetch(options);
|
2013-06-25 15:43:15 +04:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* ### Edit
|
2013-06-25 15:43:15 +04:00
|
|
|
* Naive edit
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* @param {Object} data
|
2014-04-21 22:04:20 +04:00
|
|
|
* @param {Object} options (optional)
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* @return {Promise(ghostBookshelf.Model)} Edited Model
|
2013-06-25 15:43:15 +04:00
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
edit: function edit(data, options) {
|
2016-06-03 11:06:18 +03:00
|
|
|
var id = options.id,
|
|
|
|
model = this.forge({id: id});
|
|
|
|
|
2014-05-06 05:45:08 +04:00
|
|
|
data = this.filterData(data);
|
|
|
|
options = this.filterOptions(options, 'edit');
|
Refactor API arguments
closes #2610, refs #2697
- cleanup API index.js, and add docs
- all API methods take consistent arguments: object & options
- browse, read, destroy take options, edit and add take object and options
- the context is passed as part of options, meaning no more .call
everywhere
- destroy expects an object, rather than an id all the way down to the model layer
- route params such as :id, :slug, and :key are passed as an option & used
to perform reads, updates and deletes where possible - settings / themes
may need work here still
- HTTP posts api can find a post by slug
- Add API utils for checkData
2014-05-08 16:41:19 +04:00
|
|
|
|
2016-06-03 11:06:18 +03:00
|
|
|
// We allow you to disable timestamps when run migration, so that the posts `updated_at` value is the same
|
|
|
|
if (options.importing) {
|
|
|
|
model.hasTimestamps = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return model.fetch(options).then(function then(object) {
|
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
2014-05-05 19:18:38 +04:00
|
|
|
if (object) {
|
|
|
|
return object.save(data, options);
|
2014-04-16 14:09:03 +04:00
|
|
|
}
|
2013-06-25 15:43:15 +04:00
|
|
|
});
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* ### Add
|
|
|
|
* Naive add
|
|
|
|
* @param {Object} data
|
2014-04-21 22:04:20 +04:00
|
|
|
* @param {Object} options (optional)
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* @return {Promise(ghostBookshelf.Model)} Newly Added Model
|
2013-06-25 15:43:15 +04:00
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
add: function add(data, options) {
|
2014-05-06 05:45:08 +04:00
|
|
|
data = this.filterData(data);
|
|
|
|
options = this.filterOptions(options, 'add');
|
2014-09-19 20:17:58 +04:00
|
|
|
var model = this.forge(data);
|
2016-06-03 11:06:18 +03:00
|
|
|
|
Refactor API arguments
closes #2610, refs #2697
- cleanup API index.js, and add docs
- all API methods take consistent arguments: object & options
- browse, read, destroy take options, edit and add take object and options
- the context is passed as part of options, meaning no more .call
everywhere
- destroy expects an object, rather than an id all the way down to the model layer
- route params such as :id, :slug, and :key are passed as an option & used
to perform reads, updates and deletes where possible - settings / themes
may need work here still
- HTTP posts api can find a post by slug
- Add API utils for checkData
2014-05-08 16:41:19 +04:00
|
|
|
// We allow you to disable timestamps when importing posts so that the new posts `updated_at` value is the same
|
|
|
|
// as the import json blob. More details refer to https://github.com/TryGhost/Ghost/issues/1696
|
2013-12-26 07:48:16 +04:00
|
|
|
if (options.importing) {
|
2014-09-19 20:17:58 +04:00
|
|
|
model.hasTimestamps = false;
|
2013-12-26 07:48:16 +04:00
|
|
|
}
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
|
|
|
|
// Bookshelf determines whether an operation is an update or an insert based on the id
|
|
|
|
// Ghost auto-generates Object id's, so we need to tell Bookshelf here that we are inserting data
|
|
|
|
options.method = 'insert';
|
2014-09-19 20:17:58 +04:00
|
|
|
return model.save(null, options);
|
2013-06-25 15:43:15 +04:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* ### Destroy
|
2013-06-25 15:43:15 +04:00
|
|
|
* Naive destroy
|
2014-04-21 22:04:20 +04:00
|
|
|
* @param {Object} options (optional)
|
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
2014-05-05 19:18:38 +04:00
|
|
|
* @return {Promise(ghostBookshelf.Model)} Empty Model
|
2013-06-25 15:43:15 +04:00
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
destroy: function destroy(options) {
|
Refactor API arguments
closes #2610, refs #2697
- cleanup API index.js, and add docs
- all API methods take consistent arguments: object & options
- browse, read, destroy take options, edit and add take object and options
- the context is passed as part of options, meaning no more .call
everywhere
- destroy expects an object, rather than an id all the way down to the model layer
- route params such as :id, :slug, and :key are passed as an option & used
to perform reads, updates and deletes where possible - settings / themes
may need work here still
- HTTP posts api can find a post by slug
- Add API utils for checkData
2014-05-08 16:41:19 +04:00
|
|
|
var id = options.id;
|
2014-05-06 05:45:08 +04:00
|
|
|
options = this.filterOptions(options, 'destroy');
|
2015-03-24 23:23:23 +03:00
|
|
|
|
|
|
|
// Fetch the object before destroying it, so that the changed data is available to events
|
2015-06-14 18:58:49 +03:00
|
|
|
return this.forge({id: id}).fetch(options).then(function then(obj) {
|
2015-03-24 23:23:23 +03:00
|
|
|
return obj.destroy(options);
|
|
|
|
});
|
2013-06-25 15:43:15 +04:00
|
|
|
},
|
|
|
|
|
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
2014-05-05 19:18:38 +04:00
|
|
|
/**
|
|
|
|
* ### 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
|
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
generateSlug: function generateSlug(Model, base, options) {
|
2013-12-20 17:36:00 +04:00
|
|
|
var slug,
|
|
|
|
slugTryCount = 1,
|
2014-03-23 22:52:25 +04:00
|
|
|
baseName = Model.prototype.tableName.replace(/s$/, ''),
|
2014-06-04 09:47:16 +04:00
|
|
|
// Look for a matching slug, append an incrementing number if so
|
2014-09-30 02:45:58 +04:00
|
|
|
checkIfSlugExists, longSlug;
|
2013-12-20 17:36:00 +04:00
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
checkIfSlugExists = function checkIfSlugExists(slugToFind) {
|
2014-03-23 22:52:25 +04:00
|
|
|
var args = {slug: slugToFind};
|
2016-10-14 20:24:38 +03:00
|
|
|
|
2014-09-10 08:06:24 +04:00
|
|
|
// status is needed for posts
|
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
2014-05-05 19:18:38 +04:00
|
|
|
if (options && options.status) {
|
|
|
|
args.status = options.status;
|
2014-03-23 22:52:25 +04:00
|
|
|
}
|
2016-10-14 20:24:38 +03:00
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
return Model.findOne(args, options).then(function then(found) {
|
2014-03-23 22:52:25 +04:00
|
|
|
var trimSpace;
|
2013-12-20 17:36:00 +04:00
|
|
|
|
2014-03-23 22:52:25 +04:00
|
|
|
if (!found) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return slugToFind;
|
2014-03-23 22:52:25 +04:00
|
|
|
}
|
2013-12-20 17:36:00 +04:00
|
|
|
|
2014-03-23 22:52:25 +04:00
|
|
|
slugTryCount += 1;
|
2013-12-20 17:36:00 +04:00
|
|
|
|
2014-09-30 02:45:58 +04:00
|
|
|
// If we shortened, go back to the full version and try again
|
|
|
|
if (slugTryCount === 2 && longSlug) {
|
|
|
|
slugToFind = longSlug;
|
|
|
|
longSlug = null;
|
|
|
|
slugTryCount = 1;
|
|
|
|
return checkIfSlugExists(slugToFind);
|
|
|
|
}
|
|
|
|
|
2014-03-23 22:52:25 +04:00
|
|
|
// If this is the first time through, add the hyphen
|
|
|
|
if (slugTryCount === 2) {
|
|
|
|
slugToFind += '-';
|
|
|
|
} else {
|
|
|
|
// Otherwise, trim the number off the end
|
|
|
|
trimSpace = -(String(slugTryCount - 1).length);
|
|
|
|
slugToFind = slugToFind.slice(0, trimSpace);
|
|
|
|
}
|
2013-12-20 17:36:00 +04:00
|
|
|
|
2014-03-23 22:52:25 +04:00
|
|
|
slugToFind += slugTryCount;
|
|
|
|
|
|
|
|
return checkIfSlugExists(slugToFind);
|
|
|
|
});
|
|
|
|
};
|
2013-12-20 17:36:00 +04:00
|
|
|
|
2015-09-23 13:54:56 +03:00
|
|
|
slug = utils.safeString(base, options);
|
2013-12-20 17:36:00 +04:00
|
|
|
|
2014-09-30 02:45:58 +04:00
|
|
|
// If it's a user, let's try to cut it down (unless this is a human request)
|
|
|
|
if (baseName === 'user' && options && options.shortSlug && slugTryCount === 1 && slug !== 'ghost-owner') {
|
|
|
|
longSlug = slug;
|
|
|
|
slug = (slug.indexOf('-') > -1) ? slug.substr(0, slug.indexOf('-')) : slug;
|
|
|
|
}
|
|
|
|
|
2016-06-11 18:12:04 +03:00
|
|
|
if (!_.has(options, 'importing') || !options.importing) {
|
|
|
|
// This checks if the first character of a tag name is a #. If it is, this
|
|
|
|
// is an internal tag, and as such we should add 'hash' to the beginning of the slug
|
2016-10-10 11:51:03 +03:00
|
|
|
if (baseName === 'tag' && /^#/.test(base)) {
|
2016-06-11 18:12:04 +03:00
|
|
|
slug = 'hash-' + slug;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-12-20 17:36:00 +04:00
|
|
|
// Check the filtered slug doesn't match any of the reserved keywords
|
2016-09-13 18:41:14 +03:00
|
|
|
return filters.doFilter('slug.reservedSlugs', config.get('slugs').reserved).then(function then(slugList) {
|
2014-09-07 00:16:14 +04:00
|
|
|
// Some keywords cannot be changed
|
2016-09-12 14:53:04 +03:00
|
|
|
slugList = _.union(slugList, utils.url.getProtectedSlugs());
|
2014-09-07 00:16:14 +04:00
|
|
|
|
2016-06-11 21:23:27 +03:00
|
|
|
return _.includes(slugList, slug) ? slug + '-' + baseName : slug;
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(slug) {
|
2014-09-07 00:16:14 +04:00
|
|
|
// if slug is empty after trimming use the model name
|
|
|
|
if (!slug) {
|
|
|
|
slug = baseName;
|
|
|
|
}
|
|
|
|
// Test for duplicate slugs.
|
|
|
|
return checkIfSlugExists(slug);
|
|
|
|
});
|
2015-10-22 15:49:15 +03:00
|
|
|
},
|
|
|
|
|
2015-11-21 00:20:00 +03:00
|
|
|
parseOrderOption: function (order, include) {
|
2015-10-22 15:49:15 +03:00
|
|
|
var permittedAttributes, result, rules;
|
|
|
|
|
|
|
|
permittedAttributes = this.prototype.permittedAttributes();
|
2015-11-21 00:20:00 +03:00
|
|
|
if (include && include.indexOf('count.posts') > -1) {
|
|
|
|
permittedAttributes.push('count.posts');
|
|
|
|
}
|
2015-10-22 15:49:15 +03:00
|
|
|
result = {};
|
|
|
|
rules = order.split(',');
|
|
|
|
|
|
|
|
_.each(rules, function (rule) {
|
|
|
|
var match, field, direction;
|
|
|
|
|
|
|
|
match = /^([a-z0-9_\.]+)\s+(asc|desc)$/i.exec(rule.trim());
|
|
|
|
|
|
|
|
// invalid order syntax
|
|
|
|
if (!match) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
field = match[1].toLowerCase();
|
|
|
|
direction = match[2].toUpperCase();
|
|
|
|
|
|
|
|
if (permittedAttributes.indexOf(field) === -1) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
result[field] = direction;
|
|
|
|
});
|
|
|
|
|
|
|
|
return result;
|
2013-06-25 15:43:15 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
});
|
|
|
|
|
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
2014-05-05 19:18:38 +04:00
|
|
|
// Export ghostBookshelf for use elsewhere
|
2013-09-23 02:20:08 +04:00
|
|
|
module.exports = ghostBookshelf;
|