/
base.js
267 lines (219 loc) · 7.75 KB
/
base.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
var Bookshelf = require('bookshelf'),
when = require('when'),
moment = require('moment'),
_ = require('lodash'),
uuid = require('node-uuid'),
config = require('../config'),
unidecode = require('unidecode'),
sanitize = require('validator').sanitize,
schema = require('../data/schema'),
validation = require('../data/validation'),
ghostBookshelf;
// Initializes a new Bookshelf instance, for reference elsewhere in Ghost.
ghostBookshelf = Bookshelf.ghost = Bookshelf.initialize(config().database);
ghostBookshelf.client = config().database.client;
// The Base Model which other Ghost objects will inherit from,
// including some convenience functions as static properties on the model.
ghostBookshelf.Model = ghostBookshelf.Model.extend({
hasTimestamps: true,
// get permitted attributs from schema.js
permittedAttributes: function () {
return _.keys(schema.tables[this.tableName]);
},
defaults: function () {
return {
uuid: uuid.v4()
};
},
initialize: function () {
var self = this;
this.on('creating', this.creating, this);
this.on('saving', function (model, attributes, options) {
return when(self.saving(model, attributes, options)).then(function () {
return self.validate(model, attributes, options);
});
});
},
validate: function () {
validation.validateSchema(this.tableName, this.toJSON());
},
creating: function () {
if (!this.get('created_by')) {
this.set('created_by', 1);
}
},
saving: function () {
// Remove any properties which don't belong on the model
this.attributes = this.pick(this.permittedAttributes());
// sessions do not have 'updated_by' column
if (this.tableName !== 'sessions') {
this.set('updated_by', 1);
}
},
// Base prototype properties will go here
// Fix problems with dates
fixDates: function (attrs) {
_.each(attrs, function (value, key) {
if (key.substr(-3) === '_at' && value !== null) {
attrs[key] = moment(attrs[key]).toDate();
}
});
return attrs;
},
// Convert bools to ints to be consistent
// across db providers
fixBools: function (attrs) {
_.each(attrs, function (value, key) {
if (typeof value === "boolean") {
attrs[key] = value ? 1 : 0;
}
});
return attrs;
},
format: function (attrs) {
return this.fixBools(this.fixDates(attrs));
},
toJSON: function (options) {
var attrs = this.fixBools(this.fixDates(_.extend({}, this.attributes))),
relations = this.relations;
if (options && options.shallow) {
return attrs;
}
_.each(relations, function (relation, key) {
if (key.substring(0, 7) !== '_pivot_') {
attrs[key] = relation.toJSON ? relation.toJSON() : relation;
}
});
return attrs;
},
sanitize: function (attr) {
return sanitize(this.get(attr)).xss();
}
}, {
/**
* Naive find all
* @param options (optional)
*/
findAll: function (options) {
options = options || {};
return ghostBookshelf.Collection.forge([], {model: this}).fetch(options);
},
browse: function () {
return this.findAll.apply(this, arguments);
},
/**
* Naive find one where args match
* @param args
* @param options (optional)
*/
findOne: function (args, options) {
options = options || {};
return this.forge(args).fetch(options);
},
read: function () {
return this.findOne.apply(this, arguments);
},
/**
* Naive edit
* @param editedObj
* @param options (optional)
*/
edit: function (editedObj, options) {
options = options || {};
return this.forge({id: editedObj.id}).fetch(options).then(function (foundObj) {
return foundObj.save(editedObj, options);
});
},
update: function () {
return this.edit.apply(this, arguments);
},
/**
* Naive create
* @param newObj
* @param options (optional)
*/
add: function (newObj, options) {
options = options || {};
var instance = this.forge(newObj);
// 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
if (options.importing) {
instance.hasTimestamps = false;
}
return instance.save(null, options);
},
create: function () {
return this.add.apply(this, arguments);
},
/**
* Naive destroy
* @param _identifier
* @param options (optional)
*/
destroy: function (_identifier, options) {
options = options || {};
return this.forge({id: _identifier}).destroy(options);
},
'delete': function () {
return this.destroy.apply(this, arguments);
},
// #### generateSlug
// Create a string act as the permalink for an object.
generateSlug: function (Model, base, readOptions) {
var slug,
slugTryCount = 1,
baseName = Model.prototype.tableName.replace(/s$/, ''),
// Look for a post with a matching slug, append an incrementing number if so
checkIfSlugExists;
checkIfSlugExists = function (slugToFind) {
var args = {slug: slugToFind};
//status is needed for posts
if (readOptions && readOptions.status) {
args.status = readOptions.status;
}
return Model.findOne(args, readOptions).then(function (found) {
var trimSpace;
if (!found) {
return when.resolve(slugToFind);
}
slugTryCount += 1;
// 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);
}
slugToFind += slugTryCount;
return checkIfSlugExists(slugToFind);
});
};
slug = base.trim();
// Remove non ascii characters
slug = unidecode(slug);
// Remove URL reserved chars: `:/?#[]@!$&'()*+,;=` as well as `\%<>|^~£"`
slug = slug.replace(/[:\/\?#\[\]@!$&'()*+,;=\\%<>\|\^~£"]/g, '')
// Replace dots and spaces with a dash
.replace(/(\s|\.)/g, '-')
// Convert 2 or more dashes into a single dash
.replace(/-+/g, '-')
// Make the whole thing lowercase
.toLowerCase();
// Remove trailing hyphen
slug = slug.charAt(slug.length - 1) === '-' ? slug.substr(0, slug.length - 1) : slug;
// Check the filtered slug doesn't match any of the reserved keywords
slug = /^(ghost|ghost\-admin|admin|wp\-admin|wp\-login|dashboard|logout|login|signin|signup|signout|register|archive|archives|category|categories|tag|tags|page|pages|post|posts|user|users|rss|feed)$/g
.test(slug) ? slug + '-' + baseName : slug;
//if slug is empty after trimming use "post"
if (!slug) {
slug = baseName;
}
// Test for duplicate slugs.
return checkIfSlugExists(slug);
}
});
module.exports = ghostBookshelf;