-
Notifications
You must be signed in to change notification settings - Fork 6
/
model.js
267 lines (231 loc) · 9.12 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
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 showdown = new Showdown.converter();
this.CKAN = this.CKAN || {};
// Global object that stores all CKAN models.
CKAN.Model = function ($, _, Backbone, undefined) {
var Model = {};
// Simple validator helper returns a `validate()` function that checks
// the provided model keys and returns an error object if these do not
// exist on the model or the attributes object provided.\
//
// validate: validator('title', 'description', url)
//
function validator() {
var required = arguments;
return function (attrs) {
var errors;
if (attrs) {
_.each(required, function (key) {
if (!attrs[key] && !this.get(key)) {
if (!errors) {
errors = {};
}
errors[key] = 'The "' + key + '" is required';
}
}, this);
}
return errors;
};
}
// A Base model that all CKAN models inherit from. Methods that should be
// shared across all models should be defined here.
Model.Base = Backbone.Model.extend({
// Extend the default Backbone.Model constructor simply to provide a named
// function. This improves debugging in consoles such as the Webkit inspector.
constructor: function Base(attributes, options) {
Backbone.Model.prototype.constructor.apply(this, arguments);
},
// Rather than letting the models connect to the server themselves we
// leave this to the implementor to decide how models are saved. This allows
// the API details such as API key and enpoints to change without having
// to update the models. When `.save()` or `.destroy()` is called the
// `"sync"` event will be published with the arguments provided to `.sync()`.
//
// var package = new Package({name: 'My Package Name'});
// package.bind('sync', Backbone.sync);
//
// This method returns itself for chaining.
sync: function () {
return this.trigger.apply(this, ['sync'].concat(_.toArray(arguments)));
},
// Overrides the standard `toJSON()` method to serialise any nested
// Backbone models and collections (or any other object that has a `toJSON()`
// method).
toJSON: function () {
var obj = Backbone.Model.prototype.toJSON.apply(this, arguments);
_.each(obj, function (value, key) {
if (value && typeof value === 'object' && value.toJSON) {
obj[key] = value.toJSON();
}
});
return obj;
}
});
// Model objects
Model.Dataset = Model.Base.extend({
constructor: function Dataset() {
// Define an key/model mapping for child relationships. These will be
// managed as a Backbone collection when setting/getting the key.
this.children = {
resources: Model.Resource,
relationships: Model.Relationship
};
Model.Base.prototype.constructor.apply(this, arguments);
},
// Override the `set()` method on `Backbone.Model` to handle resources as
// relationships. This will now manually update the `"resouces"` collection
// (using `_updateResources()`) with any `Resource` models provided rather
// than replacing the key.
set: function (attributes, options) {
var resources, validated;
// If not yet defined set the child collections. This will be done when
// set is called for the first time in the constructor.
this._createRelationships();
if (attributes && attributes.resources) {
if (!(attributes.resources instanceof Backbone.Collection)) {
resources = attributes.resources;
delete attributes.resources;
}
}
validated = Model.Base.prototype.set.call(this, attributes, options);
// Ensure validation passed before updating resource relationships.
if (validated && resources) {
this._updateResources(resources);
}
return validated;
},
// Checks to see if our model instance has Backbone collections defined for
// child keys. If they do not exist it creates them.
_createRelationships: function () {
_.each(this.children, function (Model, key) {
if (!this.get(key)) {
this.attributes[key] = new Backbone.Collection();
this.attributes[key].model = Model;
}
}, this);
return this;
},
// Manages the one to many relationship between resources and the dataset.
// Accepts an array of Resources (ideally model instances but will convert
// object literals into resources for you). New models will be added to the
// collection and existing ones updated. Any pre-existing models not found
// in the new array will be removed.
_updateResources: function (resources) {
var collection = this.get('resources'),
ids = {};
// Add/Update models.
_.each(resources, function (resource) {
var existing = collection.get(resource.id),
isLiteral = !(resource instanceof Model.Resource);
// Provide the dataset key if not already there.
if (isLiteral) {
// Only update if not an object literal.
resource.dataset = this;
delete resource.package_id;
}
if (!existing) {
collection.add(resource);
}
else if (existing && isLiteral) {
existing.set(resource);
}
ids[resource.id] = 1;
}, this);
// Remove missing models.
collection.remove(collection.select(function (resource) {
return !ids[resource.id];
}));
},
// NOTE: Returns localised URL.
toTemplateJSON: function () {
var out = this.toJSON();
out.ckan_url = '/package/' + this.get('name');
var title = this.get('title');
out.displaytitle = title ? title : 'No title ...';
var notes = this.get('notes');
out.notesHtml = showdown.makeHtml(notes ? notes : '');
out.snippet = this.makeSnippet(out.notesHtml);
return out;
},
makeSnippet: function (notesHtml) {
var out = $(notesHtml).text();
if (out.length > 190) {
out = out.slice(0, 190) + ' ...';
}
return out;
}
});
Model.Resource = Model.Base.extend({
constructor: function Resource() {
Model.Base.prototype.constructor.apply(this, arguments);
},
// Override the `save()` method to update the Resource with attributes then
// call the parent dataset and save that. Any `options` provided will be
// passed on to the dataset `save()` method.
save: function (attrs, options) {
var validated = this.set(attrs);
if (validated) {
return this.get('dataset').save({}, options);
}
return validated;
},
// Override the `fetch()` method to call `fetch()` on the parent dataset.
fetch: function (options) {
return this.get('dataset').fetch(options);
},
// Override the `fetch()` method to trigger the `"destroy"` event which
// will remove it from any collections then save the parent dataset.
destroy: function (options) {
return this.trigger('destroy', this).get('dataset').save({}, options);
},
// Override the `toJSON()` method to set the `"package_id"` key required
// by the server.
toJSON: function () {
// Call Backbone.Model rather than Base to break the circular reference.
var obj = Backbone.Model.prototype.toJSON.apply(this, arguments);
obj.package_id = obj.dataset.id;
delete obj.dataset;
return obj;
},
// Validates the provided attributes. Returns an object literal of
// attribute/error pairs if invalid, `undefined` otherwise.
validate: validator('url', 'dataset')
});
// Helper function that returns a stub method that warns the devloper that
// this method has not yet been implemented.
function apiPlaceholder(method) {
var console = window.console;
return function () {
if (console && console.warn) {
console.warn('The method "' + method + '" has not yet been implemented');
}
return this;
};
}
Model.Relationship = Model.Base.extend({
constructor: function Relationship() {
Model.Base.prototype.constructor.apply(this, arguments);
},
// Add placeholder method that simply returns itself to all methods that
// interact with the server. This will also log a warning message to the
// developer into the console.
save: apiPlaceholder('save'),
fetch: apiPlaceholder('fetch'),
destroy: apiPlaceholder('destroy'),
// Validates the provided attributes. Returns an object literal of
// attribute/error pairs if invalid, `undefined` otherwise.
validate: validator('object', 'subject', 'type')
});
// Collection for managing results from the CKAN search API. An additional
// `options.total` parameter can be provided on initialisation to
// indicate how many models there are on the server in total. This can
// then be accessed via the `total` property.
Model.SearchCollection = Backbone.Collection.extend({
constructor: function SearchCollection(models, options) {
if (options && options.total) {
this.total = options.total;
}
Backbone.Collection.prototype.constructor.apply(this, arguments);
}
});
return Model;
}(this.jQuery, this._, this.Backbone);