-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmodel.js
75 lines (65 loc) · 2.01 KB
/
model.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
var arrays = require('ringo/utils/arrays');
export('Page', 'PageIndex');
var {Store} = require('ringo-filestore');
var store = exports.store = new Store('/var/lib/ringojs/db');
// PageIndex is a singleton object that maps page names to page ids
var PageIndex = store.defineEntity('PageIndex', {properties: {
map: "object"
}});
var Page = store.defineEntity('Page', {properties: {
name: "string",
revisions: "array"
}});
// create PageIndex singleton
var index = PageIndex.all()[0];
if (!index) {
index = new PageIndex();
index.map = {};
index.save();
} else if (!index.map) {
index.map = {};
}
PageIndex.prototype.updatePage = sync(function(oldName, newName, id) {
if (oldName) {
delete this.map[escapeName(oldName)];
}
if (newName && id != null) {
this.map[escapeName(newName)] = id;
}
this.save();
}, store);
Page.byName = function(name) {
name = escapeName(name);
var pageId = index.map[name];
var page = pageId != null && Page.get(pageId);
if (!page) {
var pages = Page.all().filter(function(page) {
return name == page.name.toLowerCase().replace(/\s/g, '_');
});
page = pages[0];
if (page) {
index.updatePage(null, page.name, page._id);
}
}
return page;
};
Page.prototype.addRevision = function(body, created) {
if (typeof this.revisions === 'undefined') {
this.revisions = [];
}
this.revisions.push({body: body, created: created});
};
Page.prototype.getRevision = function(version) {
var rev = version ? this.revisions[version] : arrays.peek(this.revisions);
return rev ? rev : {body: '', created: new Date()};
};
Page.prototype.updateFrom = function(obj) {
if (this.name != obj.name) {
index.updatePage(this.name, obj.name, this._id);
this.name = obj.name;
}
this.addRevision(obj.body, new Date());
};
function escapeName(name) {
return name ? name.toLowerCase().replace(/\s/g, '_') : null;
}