forked from jaredly/hexo-admin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate.js
More file actions
70 lines (61 loc) · 1.93 KB
/
update.js
File metadata and controls
70 lines (61 loc) · 1.93 KB
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
var fs = require('fs'),
path = require('path'),
moment = require('moment'),
util = hexo.util,
file = util.file2,
yfm = util.yfm,
escape = util.escape;
/**
* Updates a post.
*
* @method update
* @param {str} model the type of model being updated
* @param {Object} post a post model
* @param {Object} update attributes to update
* @param {Function} callback
*/
module.exports = function (model, id, update, callback) {
var post = hexo.model(model).get(id)
if (!post) {
return callback('Post not found');
}
var config = hexo.config,
slug = post.slug = escape.filename(post.slug || post.title, config.filename_case),
layout = post.layout = (post.layout || config.default_layout).toLowerCase(),
date = post.date = post.date ? moment(post.date) : moment();
var split = yfm.split(post.raw),
frontMatter = split.data
compiled = yfm([frontMatter, '---', split.content].join('\n'));
var preservedKeys = ['title', 'date', 'tags', 'categories', '_content'];
var prev_full = post.full_source;
if (update.source && update.source !== post.source) {
update.full_source = hexo.source_dir + update.source
}
preservedKeys.forEach(function (attr) {
if (attr in update) {
compiled[attr] = update[attr]
}
});
compiled.date = moment(compiled.date).toDate()
delete update._content
var raw = yfm.stringify(compiled);
update.raw = raw
update.updated = moment()
for (var name in update) {
post[name] = update[name];
}
console.log(prev_full, post.source)
post.save(function () {
console.log(post.full_source, post.source)
file.writeFile(post.full_source, raw, function(err){
if (err) return callback(err);
if (post.full_source !== prev_full) {
fs.unlinkSync(prev_full)
}
hexo.source.process([post.source], function () {
console.log(post.full_source, post.source)
callback(null, hexo.model(model).get(id));
});
});
});
}