-
Notifications
You must be signed in to change notification settings - Fork 2k
/
client.js
309 lines (278 loc) · 9.51 KB
/
client.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
(function (ckan, jQuery) {
function Client(options) {
this.endpoint = options && options.endpoint || '';
jQuery.proxyAll(this, /parse/);
}
jQuery.extend(Client.prototype, {
/* Creates an API url from the path provided. If a fully qualified url
* is provided then this function just returns the input.
*
* path - A path to add the API domain to.
*
* Examples
*
* client.url('/datasets'); // http://api.example.com/datasets
*
* Returns an url string.
*/
url: function (path) {
if (!(/^https?:\/\//i).test(path)) {
path = this.endpoint + '/' + encodeURI(path).replace(/^\//, '');
}
return path;
},
/* Fetches the current locale translation from the API.
*
* locale - The current page locale.
*
* Examples
*
* var locale = jQuery('html').attr('lang');
* client.getLocaleData(locale, function (data) {
* // Load into the localizer.
* });
*
* Returns a jQuery xhr promise.
*/
getLocaleData: function (locale, success, error) {
var url = this.url('/api/i18n/' + (locale || ''));
return jQuery.getJSON(url).then(success, error);
},
/* Retrieves a list of auto-completions from one of the various endpoints
* and normalises the results into an array of tags.
*
* url - An API endpoint for the auto complete.
* options - An object of options for the function (optional).
* formatter: A function that takes the response and parses it.
* success - A function to be called on success (optional).
* error - A function to be called on error (optional).
*
* Examples
*
* client.getCompletions(tagEndpoint).done(function (tags) {
* // tags == array of formatted tags.
* });
*
* Returns a jqXHR promise object.
*/
getCompletions: function (url, options, success, error) {
if (typeof options === 'function') {
error = success;
success = options;
options = {};
}
var formatter = options && options.format || this.parseCompletions;
var request = jQuery.ajax({url: this.url(url)});
return request.pipe(formatter).promise(request).then(success, error);
},
/* Takes a JSON response from an auto complete endpoint and normalises
* the data into an array of strings. This also will remove duplicates
* from the results (this is case insensitive).
*
* data - The parsed JSON response from the server.
* options - An object of options for the method.
* objects: If true returns an object of results.
*
* Examples
*
* jQuery.getJSON(tagCompletionUrl, function (data) {
* var parsed = client.parseCompletions(data);
* });
*
* Returns the parsed object.
*/
parseCompletions: function (data, options) {
if (typeof data === 'string') {
// Package completions are returned as a crazy string. So we handle
// them separately.
return this.parsePackageCompletions(data, options);
}
var map = {};
var raw = data.ResultSet && data.ResultSet.Result || {};
var items = jQuery.map(raw, function (item) {
item = typeof item === 'string' ? item : item.Name || item.Format || '';
item = jQuery.trim(item);
var lowercased = item.toLowerCase();
var returnObject = options && options.objects === true;
if (lowercased && !map[lowercased]) {
map[lowercased] = 1;
return returnObject ? {id: item, text: item} : item;
}
return null;
});
// Remove duplicates.
items = jQuery.grep(items, function (item) { return item !== null; });
return items;
},
/* Returns each item as an object with an "id" and "text" property as this
* format is used by a number of auto complete plugins.
*
* data - The parsed JSON response from the server.
*
* Example
*
* var opts = {format: client.parseCompletionsForPlugin};
* client.getCompletions(tagEndpoint, opts).done(function (tags) {
* // tags == {results: [{...}, {...}, {...}}
* // tags[0] == {id: "string", text: "string"}
* });
*
* Returns an object of item objects.
*/
parseCompletionsForPlugin: function (data) {
return {
results: this.parseCompletions(data, {objects: true})
};
},
/* Parses the string returned by the package autocomplete endpoint which
* is a newline separated list of packages. Each package consists of
* a name and an id separated by a pipe (|) character.
*
* string - The string returned by the API.
*
* Returns an array of parsed packages.
*/
parsePackageCompletions: function (string, options) {
var packages = jQuery.trim(string).split('\n');
var parsed = [];
return jQuery.map(packages, function (pkg) {
var parts = pkg.split('|');
var id = jQuery.trim(parts.pop() || '');
var text = jQuery.trim(parts.join('|') || '');
return options && options.objects === true ? {id: id, text: text} : id;
});
},
/* Requests config options for a file upload.
*
* See: http://docs.ckan.org/en/latest/filestore.html
*
* key - A unique id/filename for the resource.
* success - A callback to be called on successful response.
* error - A callback to be called when the request fails.
*
* Examples
*
* client.getStorageAuth('myfile.jpg', function (data) {
* data.fields;
* });
*
* client.getStorageAuth('myfile.jpg')
* .done(function (data) {
* data.fields;
* })
* .error(function () {
* showError('Something Went Wrong');
* });
*
* Returns a jqXHR promise.
*/
getStorageAuth: function (key, success, error) {
if (!key) {
throw new Error('Client#getStorageAuth() must be called with a key');
}
return jQuery.ajax({
url: this.url('/api/storage/auth/form/' + key),
success: success,
error: error
});
},
/* Requests metadata for a file upload.
*
* See: http://docs.ckan.org/en/latest/filestore.html
*
* key - A unique id/filename for the resource.
* success - A callback to be called on successful response.
* error - A callback to be called when the request fails.
*
* Examples
*
* client.getStorageMetadata('myfile.jpg', function (data) {
* data._format;
* });
*
* Returns a jqXHR promise.
*/
getStorageMetadata: function (key, success, error) {
if (!key) {
throw new Error('Client#getStorageMetadata() must be called with a key');
}
return jQuery.ajax({
url: this.url('/api/storage/metadata/' + key),
success: success,
error: error
});
},
/* Converts the data returned from the storage metadata into keys that
* can be used with a dataset.
*
* key - The key for the stored file.
* meta - The metadata object.
*
* Examples
*
* client.getStorageMetadata('myfile.jpg', function (data) {
* var dataset = client.convertStorageMetadataToResource(data);
* });
*
* Returns an object of dataset keys.
*/
convertStorageMetadataToResource: function (meta) {
// TODO: Check this is supported by IE7. U believe that the IE
// Date constructor chokes on hyphens and timezones.
var modified = new Date(this.normalizeTimestamp(meta._last_modified));
var created = new Date(this.normalizeTimestamp(meta._creation_date));
var createdISO = jQuery.date.toCKANString(created);
var modifiedISO = jQuery.date.toCKANString(modified);
var filename = meta['filename-original'] || meta.key;
var format = meta._format || filename.split('.').pop();
var url = meta._location;
// If this is a local upload then the returned url will not have a domain
// and we should add one.
if (url.indexOf('://') === -1) {
url = ckan.url(url);
}
return {
url: url,
key: meta.key, /* Not strictly Resource data but may be useful */
name: filename,
size: meta._content_length,
created: createdISO,
last_modified: modifiedISO,
format: format,
mimetype: meta._format || null,
resource_type: 'file.upload', // Is this standard?
owner: meta['uploaded-by'],
hash: meta._checksum,
cache_url: meta._location,
cache_url_updated: modifiedISO
};
},
/* Adds a timezone to the provided timestamp if one is not present. This
* fixes an inconsistency between Webkit and Firefox where Firefox parses
* the date in the current users timezone but Webkit uses UTC.
*
* string - A timestamp string.
*
* Examples
*
* client.normalizeTimestamp("2012-07-17T14:35:35");
* // => "2012-07-17T14:35:35Z"
*
* client.normalizeTimestamp("2012-07-17T14:35:35+0100");
* // => "2012-07-17T14:35:35+0100"
*
* Returns a new timestamp with timezone.
*/
normalizeTimestamp: function (string) {
var tz = /[+\-]\d{4}|Z/;
if (!tz.test(string)) {
string += 'Z';
}
return string;
}
});
ckan.sandbox.setup(function (instance) {
instance.client = new Client({endpoint: ckan.API_ROOT});
});
ckan.Client = Client;
})(this.ckan, this.jQuery);