Commit 4a1655ef authored by Romain Courteaud's avatar Romain Courteaud

Update erp5storage.

Follow draft API provided by
http://git.erp5.org/gitweb/slapos.core.git/tree/HEAD:/master/bt5/slapos_jio

Drop compatibility with previous API.
parent 830a9671
...@@ -3,442 +3,232 @@ ...@@ -3,442 +3,232 @@
* Released under the LGPL license. * Released under the LGPL license.
* http://www.gnu.org/licenses/lgpl.html * http://www.gnu.org/licenses/lgpl.html
*/ */
// JIO Erp5 Storage Description : // JIO ERP5 Storage Description :
// { // {
// type: "erp5" // type: "erp5"
// url: {string} // url: {string}
// mode: {string} (optional)
// - "generic" (default)
// - "erp5_only"
//
// with
//
// auth_type: {string} (optional)
// - "none" (default)
// - "basic" (not implemented)
// - "digest" (not implemented)
// username: {string}
// password: {string} (optional)
// - no password (default)
//
// or
//
// encoded_login: {string} (not implemented)
//
// or
//
// secured_login: {string} (not implemented)
// } // }
/*jslint indent: 2, maxlen: 80, nomen: true */ /*jslint nomen: true, unparam: true */
/*global define, jIO, jQuery, complex_queries */ /*global jIO, complex_queries, console, UriTemplate, FormData, RSVP */
(function (dependencies, module) { (function (jIO, complex_queries) {
"use strict";
if (typeof define === 'function' && define.amd) {
return define(dependencies, module);
}
module(jIO, jQuery, complex_queries);
}(['jio', 'jquery', 'complex_queries'], function (jIO, $, complex_queries) {
"use strict"; "use strict";
function ERP5Storage(spec) { function ERP5Storage(spec) {
var priv = {}, that = this, erp5 = {}; if (typeof spec.url !== 'string' && !spec.url) {
throw new TypeError("ERP5 'url' must be a string " +
// ATTRIBUTES // "which contains more than one character.");
priv.url = null;
priv.mode = "generic";
priv.auth_type = "none";
priv.encoded_login = null;
// CONSTRUCTOR //
/**
* Init the erp5 storage connector thanks to the description
* @method __init__
* @param {object} description The description object
*/
priv.__init__ = function (description) {
priv.url = description.url || "";
priv.url = priv.removeSlashIfLast(priv.url);
if (description.mode === "erp5_only") {
priv.mode = "erp5_only";
}
if (description.encoded_login) {
priv.encoded_login = description.encoded_login;
} else {
if (description.username) {
priv.encoded_login =
"__ac_name=" + priv.convertToUrlParameter(description.username) +
"&" + (typeof description.password === "string" ?
"__ac_password=" +
priv.convertToUrlParameter(description.password) + "&" : "");
} else {
priv.encoded_login = "";
} }
this._url = spec.url;
} }
};
// TOOLS // ERP5Storage.prototype._getSiteDocument = function () {
/** return jIO.util.ajax({
* Replace substrings to another strings "type": "GET",
* @method recursiveReplace "url": this._url,
* @param {string} string The string to do replacement "xhrFields": {
* @param {array} list_of_replacement An array of couple withCredentials: true
* ["substring to select", "selected substring replaced by this string"].
* @return {string} The replaced string
*/
priv.recursiveReplace = function (string, list_of_replacement) {
var i, split_string = string.split(list_of_replacement[0][0]);
if (list_of_replacement[1]) {
for (i = 0; i < split_string.length; i += 1) {
split_string[i] = priv.recursiveReplace(
split_string[i],
list_of_replacement.slice(1)
);
}
} }
return split_string.join(list_of_replacement[0][1]); }).then(function (response) {
}; return JSON.parse(response.target.responseText);
});
/**
* Changes & to %26
* @method convertToUrlParameter
* @param {string} parameter The parameter to convert
* @return {string} The converted parameter
*/
priv.convertToUrlParameter = function (parameter) {
return priv.recursiveReplace(parameter, [[" ", "%20"], ["&", "%26"]]);
}; };
/** ERP5Storage.prototype._get = function (param, options) {
* Removes the last character if it is a "/". "/a/b/c/" become "/a/b/c" return this._getSiteDocument()
* @method removeSlashIfLast .then(function (site_hal) {
* @param {string} string The string to modify return jIO.util.ajax({
* @return {string} The modified string "type": "GET",
*/ "url": UriTemplate.parse(site_hal._links.traverse.href)
priv.removeSlashIfLast = function (string) { .expand({
if (string[string.length - 1] === "/") { relative_url: param._id,
return string.slice(0, -1); view: options._view
}),
"xhrFields": {
withCredentials: true
} }
return string; });
}; })
.then(function (response) {
/** var result = JSON.parse(response.target.responseText);
* Modify an ajax object to add default values result._id = param._id;
* @method makeAjaxObject return result;
* @param {object} json The JSON object });
* @param {object} option The option object
* @param {string} method The erp5 request method
* @param {object} ajax_object The ajax object to override
* @return {object} A new ajax object with default values
*/
priv.makeAjaxObject = function (json, option, method, ajax_object) {
ajax_object.type = "POST";
ajax_object.dataType = "json";
ajax_object.data = [
{"name": "doc", "value": JSON.stringify(json)},
{"name": "option", "value": JSON.stringify(option)},
{"name": "mode", "value": priv.mode}
];
ajax_object.url = priv.url + "/JIO_" + method +
"?" + priv.encoded_login + "_=" + Date.now();
ajax_object.async = ajax_object.async === false ? false : true;
ajax_object.crossdomain =
ajax_object.crossdomain === false ? false : true;
ajax_object.headers = ajax_object.headers || {};
return ajax_object;
}; };
/** ERP5Storage.prototype.get = function (command, param, options) {
* Runs all ajax requests for erp5Storage this._get(param, options)
* @method ajax .then(function (response) {
* @param {object} json The JSON object command.success({"data": response});
* @param {object} option The option object })
* @param {string} method The erp5 request method .fail(function (error) {
* @param {object} ajax_object The request parameters (optional) console.error(error);
*/ // XXX How to propagate the error
priv.ajax = function (json, option, method, ajax_object) { command.error(
return $.ajax( "not_found",
priv.makeAjaxObject(json, option, method, ajax_object || {}) "missing",
"Cannot find document"
); );
//.always(then || function () {}); });
}; };
/** ERP5Storage.prototype.post = function (command, metadata, options) {
* Creates error objects for this storage return this._getSiteDocument()
* @method createError .then(function (site_hal) {
* @param {string} url url to clean up var post_action = site_hal._actions.add,
* @return {object} error The error object data = new FormData(),
*/ key;
priv.createError = function (status, message, reason) {
return {
"status": status,
"message": message,
"reason": reason
};
};
/** for (key in metadata) {
* Converts ajax error object to a JIO error object if (metadata.hasOwnProperty(key)) {
* @method ajaxErrorToJioError // XXX Not a form dialog in this case but distant script
* @param {object} ajax_error_object The ajax error object data.append(key, metadata[key]);
* @param {string} message The error message
* @param {string} reason The error reason
* @return {object} The JIO error object
*/
priv.ajaxErrorToJioError = function (ajax_error_object, message, reason) {
var jio_error_object = {};
jio_error_object.status = ajax_error_object.status;
jio_error_object.statusText = ajax_error_object.statusText;
jio_error_object.error =
ajax_error_object.statusText.toLowerCase().split(" ").join("_");
jio_error_object.message = message;
jio_error_object.reason = reason;
return jio_error_object;
};
/**
* Function that create an object containing jQuery like callbacks
* @method makeJQLikeCallback
* @return {object} jQuery like callback methods
*/
priv.makeJQLikeCallback = function () {
var result = null, emptyFun = function () {
return;
}, jql = {
"respond": function () {
result = arguments;
},
"to_return": {
"always": function (func) {
if (result) {
func.apply(func, result);
jql.to_return.always = emptyFun;
} else {
jql.respond = func;
} }
return jql.to_return;
} }
return jIO.util.ajax({
"type": post_action.method,
"url": post_action.href,
"data": data,
"xhrFields": {
withCredentials: true
} }
}; });
return jql; }).then(function (doc) {
}; // XXX Really depend on server response...
var new_document_url = doc.target.getResponseHeader("Location");
/** return jIO.util.ajax({
* Use option object and converts a query to a compatible ERP5 Query. "type": "GET",
* "url": new_document_url,
* @param {Object} option The command options "xhrFields": {
*/ withCredentials: true
priv.convertToErp5Query = function (option) {
option.query = complex_queries.QueryFactory.create(option.query || "");
if (option.wildcard_character === undefined ||
(option.wildcard_character !== null &&
typeof option.wildcard_character !== 'string')) {
option.wildcard_character = '%';
} else {
option.wildcard_character = option.wildcard_character || '';
} }
option.query.onParseSimpleQuery = function (object) { });
if (option.wildcard_character.length === 1 && }).then(function (response) {
object.parsed.operator === '=') { var doc_hal = JSON.parse(response.target.responseText);
object.parsed.operator = 'like'; if (doc_hal !== null) {
if (option.wildcard_character === '%') { command.success({"id": doc_hal._relative_url});
object.parsed.value =
object.parsed.value.replace(/_/g, '\\_');
} else if (option.wildcard_character === '_') {
object.parsed.value =
object.parsed.value.replace(/%/g, '\\%').replace(/_/g, '%');
} else { } else {
object.parsed.value = command.error(
object.parsed.value.replace( "not_found",
/([%_])/g, "missing",
'\\$1' "Cannot find document"
).replace(
new RegExp(complex_queries.stringEscapeRegexpCharacters(
option.wildcard_character
), 'g'),
'%'
); );
} }
} }, function (error) {
}; console.error(error);
option.query = option.query.parse(); command.error(
500,
"Too bad...",
"Unable to post doc"
);
});
}; };
// ERP5 REQUESTS // ERP5Storage.prototype.put = function (command, metadata, options) {
/** return this._get(metadata, options)
* Sends a request to ERP5 .then(function (result) {
* @method erp5.genericRequest var put_action = result._embedded._view._actions.put,
* @param {object} doc The document object renderer_form = result._embedded._view,
* @param {object} option The option object data = new FormData(),
* @param {string} method The ERP5 request method key;
*/ data.append(renderer_form.form_id.key,
erp5.genericRequest = function (method, json, option) { renderer_form.form_id['default']);
var jql = priv.makeJQLikeCallback(), error = null; for (key in metadata) {
priv.ajax(json, option, method).always(function (one, state) { if (metadata.hasOwnProperty(key)) {
if (state === "parsererror") { if (key !== "_id") {
return jql.respond(priv.createError( // Hardcoded my_ ERP5 behaviour
24, if (renderer_form.hasOwnProperty("my_" + key)) {
"Cannot parse data", data.append(renderer_form["my_" + key].key, metadata[key]);
"Corrupted data" } else {
), undefined); throw new Error("Can not save property " + key);
} }
if (state !== "success") {
error = priv.ajaxErrorToJioError(
one,
"An error occured on " + method,
"Unknown"
);
if (one.status === 404) {
error.reason = "Not Found";
} }
return jql.respond(error, undefined);
} }
if (one.err !== null) {
return jql.respond(one.err, undefined);
} }
if (one.response !== null) { return jIO.util.ajax({
return jql.respond(undefined, one.response); "type": put_action.method,
"url": put_action.href,
"data": data,
"xhrFields": {
withCredentials: true
} }
return jql.respond(priv.createError(
24,
"Cannot parse data",
"Corrupted data"
), undefined);
}); });
return jql.to_return; })
.then(function (result) {
command.success(result);
})
.fail(function (error) {
console.error(error);
command.error(
"error",
"did not work as expected",
"Unable to call put"
);
});
}; };
// JIO COMMANDS // ERP5Storage.prototype.allDocs = function (command, param, options) {
/** return this._getSiteDocument()
* The ERP5 storage generic command .then(function (site_hal) {
* @method genericCommand return jIO.util.ajax({
* @param {object} command The JIO command object "type": "GET",
* @param {string} method The ERP5 request method "url": UriTemplate.parse(site_hal._links.raw_search.href)
*/ .expand({
priv.genericCommand = function (method, command, param, option) { query: options.query,
if (complex_queries !== undefined && // XXX Force erp5 to return embedded document
method === 'allDocs' && select_list: options.select_list || ["title", "reference"],
option.query) { limit: options.limit
priv.convertToErp5Query(option); }),
} "xhrFields": {
erp5.genericRequest( withCredentials: true
method,
param,
option
).always(function (err, response) {
if (err) {
return command.error(err);
} }
if (['get', 'getAttachment', 'allDocs'].indexOf(method) === -1) { });
return command.success(response); })
.then(function (response) {
return JSON.parse(response.target.responseText);
})
.then(function (catalog_json) {
var data = catalog_json._embedded.contents,
count = data.length,
i,
item,
result = [],
promise_list = [result];
for (i = 0; i < count; i += 1) {
item = data[i];
item._id = item._relative_url;
result.push({
id: item._relative_url,
key: item._relative_url,
doc: {},
value: item
});
// if (options.include_docs) {
// promise_list.push(RSVP.Queue().push(function () {
// return this._get({_id: item.name}, {_view: "View"});
// }).push
// }
} }
return command.success({"data": response}); return RSVP.all(promise_list);
})
.then(function (promise_list) {
var result = promise_list[0],
count = result.length;
command.success({"data": {"rows": result, "total_rows": count}});
})
.fail(function (error) {
console.error(error);
command.error(
"error",
"did not work as expected",
"Unable to call allDocs"
);
}); });
};
/**
* Creates a new document
* @method post
* @param {object} command The JIO command
*/
that.post = function (command, metadata, options) {
priv.genericCommand("post", command, metadata, options);
};
/**
* Creates or updates a document
* @method put
* @param {object} command The JIO command
*/
that.put = function (command, metadata, options) {
priv.genericCommand("put", command, metadata, options);
};
/**
* Add an attachment to a document
* @method putAttachment
* @param {object} command The JIO command
*/
that.putAttachment = function (command, param, options) {
priv.genericCommand("putAttachment", command, param, options);
};
/**
* Get a document
* @method get
* @param {object} command The JIO command
*/
that.get = function (command, param, options) {
priv.genericCommand("get", command, param, options);
};
/**
* Get an attachment
* @method getAttachment
* @param {object} command The JIO command
*/
that.getAttachment = function (command, param, options) {
priv.genericCommand("getAttachment", command, param, options);
};
/**
* Remove a document
* @method remove
* @param {object} command The JIO command
*/
that.remove = function (command, param, options) {
priv.genericCommand("remove", command, param, options);
};
/**
* Remove an attachment
* @method removeAttachment
* @param {object} command The JIO command
*/
that.removeAttachment = function (command, param, options) {
priv.genericCommand("removeAttachment", command, param, options);
};
/**
* Gets a document list from a distant erp5 storage
* Options:
* - {boolean} include_docs Also retrieve the actual document content.
* @method allDocs
* @param {object} command The JIO command
*/
that.allDocs = function (command, param, options) {
priv.genericCommand("allDocs", command, param, options);
};
/**
* Checks a document state
* @method check
* @param {object} command The JIO command
*/
that.check = function (command, param, options) {
priv.genericCommand("check", command, param, options);
};
/**
* Restore a document state to a coherent state
* @method repair
* @param {object} command The JIO command
*/
that.repair = function (command, param, options) {
priv.genericCommand("repair", command, param, options);
}; };
priv.__init__(spec);
if (typeof priv.url !== "string" || priv.url === "") {
throw new TypeError("The erp5 server URL is not provided");
}
if (priv.encoded_login === null) {
throw new TypeError("Impossible to create the authorization");
}
}
jIO.addStorage("erp5", ERP5Storage); jIO.addStorage("erp5", ERP5Storage);
})); }(jIO, complex_queries));
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment