erp5storage.js 6.97 KB
Newer Older
Tristan Cavelier's avatar
Tristan Cavelier committed
1
/*
Tristan Cavelier's avatar
Tristan Cavelier committed
2 3 4 5
 * Copyright 2013, Nexedi SA
 * Released under the LGPL license.
 * http://www.gnu.org/licenses/lgpl.html
 */
Romain Courteaud's avatar
Romain Courteaud committed
6
// JIO ERP5 Storage Description :
Tristan Cavelier's avatar
Tristan Cavelier committed
7
// {
Tristan Cavelier's avatar
Tristan Cavelier committed
8
//   type: "erp5"
Tristan Cavelier's avatar
Tristan Cavelier committed
9 10
//   url: {string}
// }
11

12
/*jslint indent: 2, nomen: true, unparam: true */
Tristan Cavelier's avatar
Tristan Cavelier committed
13
/*global jIO, console, UriTemplate, FormData, RSVP, URI,
14
  ProgressEvent, define */
15

16 17 18 19 20
(function (dependencies, module) {
  "use strict";
  if (typeof define === 'function' && define.amd) {
    return define(dependencies, module);
  }
Tristan Cavelier's avatar
Tristan Cavelier committed
21
  module(RSVP, jIO, URI);
22 23 24 25
}([
  'rsvp',
  'jio',
  'uri'
Tristan Cavelier's avatar
Tristan Cavelier committed
26
], function (RSVP, jIO, URI) {
Tristan Cavelier's avatar
Tristan Cavelier committed
27
  "use strict";
Tristan Cavelier's avatar
Tristan Cavelier committed
28

29
  function ERP5Storage(spec) {
Romain Courteaud's avatar
Romain Courteaud committed
30 31 32 33 34 35
    if (typeof spec.url !== 'string' && !spec.url) {
      throw new TypeError("ERP5 'url' must be a string " +
                          "which contains more than one character.");
    }
    this._url = spec.url;
  }
36

Romain Courteaud's avatar
Romain Courteaud committed
37 38 39 40 41 42
  ERP5Storage.prototype._getSiteDocument = function () {
    return jIO.util.ajax({
      "type": "GET",
      "url": this._url,
      "xhrFields": {
        withCredentials: true
43
      }
Romain Courteaud's avatar
Romain Courteaud committed
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
    }).then(function (response) {
      return JSON.parse(response.target.responseText);
    });
  };

  ERP5Storage.prototype._get = function (param, options) {
    return this._getSiteDocument()
      .then(function (site_hal) {
        return jIO.util.ajax({
          "type": "GET",
          "url": UriTemplate.parse(site_hal._links.traverse.href)
                            .expand({
              relative_url: param._id,
              view: options._view
            }),
          "xhrFields": {
            withCredentials: true
          }
        });
      })
      .then(function (response) {
        var result = JSON.parse(response.target.responseText);
        result._id = param._id;
        return result;
      });
  };

  ERP5Storage.prototype.get = function (command, param, options) {
    this._get(param, options)
      .then(function (response) {
        command.success({"data": response});
      })
76 77 78 79 80 81 82 83 84
      .fail(function (event) {
        console.error(event);
        if (event instanceof ProgressEvent) {
          command.error(
            event.target.status,
            event.target.statusText,
            "Cannot find document"
          );
        }
Romain Courteaud's avatar
Romain Courteaud committed
85
        // XXX How to propagate the error
86
        command.error(event);
Romain Courteaud's avatar
Romain Courteaud committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
      });
  };

  ERP5Storage.prototype.post = function (command, metadata, options) {
    return this._getSiteDocument()
      .then(function (site_hal) {
        var post_action = site_hal._actions.add,
          data = new FormData(),
          key;

        for (key in metadata) {
          if (metadata.hasOwnProperty(key)) {
            // XXX Not a form dialog in this case but distant script
            data.append(key, metadata[key]);
          }
102
        }
Romain Courteaud's avatar
Romain Courteaud committed
103 104 105 106 107 108 109 110 111 112
        return jIO.util.ajax({
          "type": post_action.method,
          "url": post_action.href,
          "data": data,
          "xhrFields": {
            withCredentials: true
          }
        });
      }).then(function (doc) {
        // XXX Really depend on server response...
113 114
        var uri = new URI(doc.target.getResponseHeader("X-Location"));
        command.success({"id": uri.segment(2)});
115
      }).fail(function (event) {
116 117 118 119 120 121 122 123 124
        console.error(event);
        if (event instanceof ProgressEvent) {
          return command.error(
            event.target.status,
            event.target.statusText,
            "Unable to post doc"
          );
        }
        command.error(event);
Romain Courteaud's avatar
Romain Courteaud committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
      });
  };

  ERP5Storage.prototype.put = function (command, metadata, options) {
    return this._get(metadata, options)
      .then(function (result) {
        var put_action = result._embedded._view._actions.put,
          renderer_form = result._embedded._view,
          data = new FormData(),
          key;
        data.append(renderer_form.form_id.key,
                    renderer_form.form_id['default']);
        for (key in metadata) {
          if (metadata.hasOwnProperty(key)) {
            if (key !== "_id") {
              // Hardcoded my_ ERP5 behaviour
              if (renderer_form.hasOwnProperty("my_" + key)) {
                data.append(renderer_form["my_" + key].key, metadata[key]);
              } else {
                throw new Error("Can not save property " + key);
              }
146 147
            }
          }
148
        }
Romain Courteaud's avatar
Romain Courteaud committed
149 150 151 152 153 154
        return jIO.util.ajax({
          "type": put_action.method,
          "url": put_action.href,
          "data": data,
          "xhrFields": {
            withCredentials: true
155
          }
Romain Courteaud's avatar
Romain Courteaud committed
156 157 158 159 160
        });
      })
      .then(function (result) {
        command.success(result);
      })
161 162 163 164 165 166 167 168 169 170
      .fail(function (event) {
        console.error(event);
        if (event instanceof ProgressEvent) {
          return command.error(
            event.target.status,
            event.target.statusText,
            "Unable to call put"
          );
        }
        command.error(event);
171 172
      });

Romain Courteaud's avatar
Romain Courteaud committed
173 174 175
  };

  ERP5Storage.prototype.allDocs = function (command, param, options) {
176 177
    if (typeof options.query !== "string") {
      options.query = (options.query ?
Tristan Cavelier's avatar
Tristan Cavelier committed
178
                       jIO.Query.objectToSearchText(options.query) :
179 180
                       undefined);
    }
Romain Courteaud's avatar
Romain Courteaud committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    return this._getSiteDocument()
      .then(function (site_hal) {
        return jIO.util.ajax({
          "type": "GET",
          "url": UriTemplate.parse(site_hal._links.raw_search.href)
                            .expand({
              query: options.query,
              // XXX Force erp5 to return embedded document
              select_list: options.select_list || ["title", "reference"],
              limit: options.limit
            }),
          "xhrFields": {
            withCredentials: true
          }
        });
      })
      .then(function (response) {
        return JSON.parse(response.target.responseText);
      })
      .then(function (catalog_json) {
        var data = catalog_json._embedded.contents,
          count = data.length,
          i,
204
          uri,
Romain Courteaud's avatar
Romain Courteaud committed
205 206 207 208 209
          item,
          result = [],
          promise_list = [result];
        for (i = 0; i < count; i += 1) {
          item = data[i];
210
          uri = new URI(item._links.self.href);
Romain Courteaud's avatar
Romain Courteaud committed
211
          result.push({
212 213
            id: uri.segment(2),
            key: uri.segment(2),
Romain Courteaud's avatar
Romain Courteaud committed
214 215 216 217 218 219 220 221
            doc: {},
            value: item
          });
//           if (options.include_docs) {
//             promise_list.push(RSVP.Queue().push(function () {
//               return this._get({_id: item.name}, {_view: "View"});
//             }).push
//           }
222
        }
Romain Courteaud's avatar
Romain Courteaud committed
223 224 225 226 227 228 229
        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}});
      })
230 231 232 233 234 235 236 237 238 239
      .fail(function (event) {
        console.error(event);
        if (event instanceof ProgressEvent) {
          return command.error(
            event.target.status,
            event.target.statusText,
            "Cannot get list of document"
          );
        }
        command.error(event);
240
      });
Tristan Cavelier's avatar
Tristan Cavelier committed
241

Romain Courteaud's avatar
Romain Courteaud committed
242
  };
Tristan Cavelier's avatar
Tristan Cavelier committed
243

244
  jIO.addStorage("erp5", ERP5Storage);
Tristan Cavelier's avatar
Tristan Cavelier committed
245

246
}));