ionic-coreo
Version:
Ionic2 module for integration with Coreo
94 lines • 3.48 kB
JavaScript
;
var lodash_1 = require('lodash');
var CoreoRecord = (function () {
function CoreoRecord(options) {
this.data = {};
this.records = [];
this.files = [];
Object.assign(this, options || {});
}
CoreoRecord.prototype.setData = function (key, value) {
this.data[key] = value;
};
CoreoRecord.prototype.addFile = function (path, url, type) {
if (type === void 0) { type = 'image/jpeg'; }
this.files.push({
url: url,
path: path,
type: type
});
};
// TODO does not handle if children have files
CoreoRecord.prototype.toFormData = function () {
var _this = this;
var filesPromise = this.files.length === 0 ? Promise.resolve([]) : Promise.all(this.files.map(function (f) { return _this.loadFile(f); }));
return filesPromise.then(function (files) {
var data = lodash_1.omit(_this, ['files']);
for (var i = 0; i < _this.files.length; i++) {
if (typeof files[i] !== 'undefined') {
data.data[_this.files[i].path] = files[i];
}
}
var fd = objectToFormData(data);
return fd;
}, function (err) {
console.log('ERRORS!', err);
});
};
CoreoRecord.prototype.createChildRecord = function (options) {
var child = new CoreoRecord(Object.assign({}, options || {}, { surveyId: this.surveyId }));
this.records.push(child);
return child;
};
/**
* Load a file from the filesystem into a blob
*/
CoreoRecord.prototype.loadFile = function (file) {
console.log('LOADING FILE');
var type = file.type;
var url = file.url;
return new Promise(function (resolve, reject) {
if (!window.hasOwnProperty('resolveLocalFileSystemURL')) {
console.warn('Unable to load file in browser');
return resolve();
}
window.resolveLocalFileSystemURL(url, function (entry) {
console.log('GOT FILE', file);
entry.file(function (f) {
console.log('Got f', f);
var reader = new FileReader();
reader.onloadend = function () {
console.log('ALL DONE');
var blob = new Blob([this.result], { type: type });
resolve(blob);
};
reader.readAsArrayBuffer(f);
}, function (e) { return reject(e); });
}, function (e) { return reject(e); });
});
};
return CoreoRecord;
}());
exports.CoreoRecord = CoreoRecord;
function objectToFormData(obj, form, nspace) {
var fd = form || new FormData();
var formKey;
for (var property in obj) {
if (obj.hasOwnProperty(property) && typeof obj[property] !== 'function') {
if (nspace) {
formKey = nspace + '[' + property + ']';
}
else {
formKey = property;
}
if (typeof obj[property] === 'object' && !(obj[property] instanceof File || obj[property] instanceof Blob)) {
objectToFormData(obj[property], fd, formKey);
}
else {
fd.append(formKey, obj[property]);
}
}
}
return fd;
}
//# sourceMappingURL=record.js.map