You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@couchdb.apache.org by GitBox <gi...@apache.org> on 2019/01/09 21:43:21 UTC
[GitHub] Antonio-Maranhao closed pull request #1165: Remove dependency with
Backbone.Model
Antonio-Maranhao closed pull request #1165: Remove dependency with Backbone.Model
URL: https://github.com/apache/couchdb-fauxton/pull/1165
This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:
As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):
diff --git a/app/addons/components/actions.js b/app/addons/components/actions.js
index bc1783b0c..50f6a03ce 100644
--- a/app/addons/components/actions.js
+++ b/app/addons/components/actions.js
@@ -24,11 +24,7 @@ function showDeleteDatabaseModal (options) {
function deleteDatabase (dbId, onDeleteSuccess) {
const url = FauxtonAPI.urls('databaseBaseURL', 'server', dbId, '');
- deleteRequest(url).then(resp => {
- if (!resp.ok) {
- const msg = resp.reason || '';
- throw new Error(msg);
- }
+ deleteRequest(url).then(FauxtonAPI.throwIfCouchDbErrorResponse).then(() => {
this.showDeleteDatabaseModal({ showModal: true });
FauxtonAPI.addNotification({
diff --git a/app/addons/databases/actions.js b/app/addons/databases/actions.js
index d576c7e1b..fffa193f7 100644
--- a/app/addons/databases/actions.js
+++ b/app/addons/databases/actions.js
@@ -153,7 +153,7 @@ export default {
const db = Stores.databasesStore.obtainNewDatabaseModel(databaseName, partitioned);
FauxtonAPI.addNotification({ msg: 'Creating database.' });
- db.save().done(() => {
+ db.save().then(() => {
FauxtonAPI.addNotification({
msg: 'Database created successfully',
type: 'success',
@@ -161,11 +161,10 @@ export default {
});
const route = FauxtonAPI.urls('allDocs', 'app', app.utils.safeURLName(databaseName));
app.router.navigate(route, { trigger: true });
- }
- ).fail((xhr) => {
- const responseText = JSON.parse(xhr.responseText).reason;
+ }).catch(err => {
+ const reason = err.responseJSON ? err.responseJSON.reason : '';
FauxtonAPI.addNotification({
- msg: 'Create database failed: ' + responseText,
+ msg: 'Create database failed. ' + reason,
type: 'error',
clear: true
});
diff --git a/app/addons/databases/resources.js b/app/addons/databases/resources.js
index cd3af48a7..b8b92ee37 100644
--- a/app/addons/databases/resources.js
+++ b/app/addons/databases/resources.js
@@ -18,37 +18,40 @@ var Databases = FauxtonAPI.addon();
Databases.DocLimit = 100;
-Databases.Model = FauxtonAPI.Model.extend({
+Databases.Model = class extends FauxtonAPI.Model {
- partitioned: false,
+ constructor(attributes, options) {
+ super(attributes, options);
+ this.partitioned = false;
+ }
- setPartitioned: function (partitioned) {
+ setPartitioned(partitioned) {
this.partitioned = partitioned;
- },
+ }
- documentation: function () {
+ documentation() {
return FauxtonAPI.constants.DOC_URLS.ALL_DBS;
- },
+ }
- buildAllDocs: function (params) {
+ buildAllDocs(params) {
this.allDocs = new Documents.AllDocs(null, {
database: this,
params: params
});
return this.allDocs;
- },
+ }
- isNew: function () {
+ isNew() {
// Databases are never new, to make Backbone do a PUT
return false;
- },
+ }
- isSystemDatabase: function () {
+ isSystemDatabase() {
return app.utils.isSystemDatabase(this.id);
- },
+ }
- url: function (context) {
+ url(context) {
if (context === "index") {
return "/database/" + this.safeID() + "/_all_docs";
} else if (context === "web-index") {
@@ -67,12 +70,13 @@ Databases.Model = FauxtonAPI.Model.extend({
}
return Helpers.getServerUrl("/" + this.safeID());
- },
+ }
- safeID: function () {
+ safeID() {
return app.utils.safeURLName(this.id);
- },
- buildChanges: function (params) {
+ }
+
+ buildChanges(params) {
if (!params.limit) {
params.limit = 100;
}
@@ -84,18 +88,20 @@ Databases.Model = FauxtonAPI.Model.extend({
return this.changes;
}
-});
+};
-Databases.Changes = FauxtonAPI.Collection.extend({
+Databases.Changes = class extends FauxtonAPI.Collection {
- initialize: function (options) {
+ initialize(options) {
this.database = options.database;
this.params = options.params;
- },
- documentation: function () {
+ }
+
+ documentation() {
return FauxtonAPI.constants.DOC_URLS.CHANGES;
- },
- url: function (context) {
+ }
+
+ url(context) {
var query = "";
if (this.params) {
query = "?" + app.utils.queryParams(this.params);
@@ -104,12 +110,12 @@ Databases.Changes = FauxtonAPI.Collection.extend({
if (!context) { context = 'server';}
return FauxtonAPI.urls('changes', context, this.database.safeID(), query);
- },
+ }
- parse: function (resp) {
+ parse(resp) {
this.last_seq = resp.last_seq;
return resp.results;
}
-});
+};
export default Databases;
diff --git a/app/addons/documents/doc-editor/actions.js b/app/addons/documents/doc-editor/actions.js
index 7977ab4cd..6e65bb5b1 100644
--- a/app/addons/documents/doc-editor/actions.js
+++ b/app/addons/documents/doc-editor/actions.js
@@ -39,8 +39,8 @@ const initDocEditor = (params) => (dispatch) => {
if (params.onLoaded) {
params.onLoaded();
}
- }, function (xhr) {
- if (xhr.status === 404) {
+ }).catch(err => {
+ if (err.status === 404) {
errorNotification(`The ${doc.id} document does not exist.`);
}
@@ -62,9 +62,10 @@ const saveDoc = (doc, isValidDoc, onSave, navigateToUrl) => {
} else {
FauxtonAPI.navigate('#/' + FauxtonAPI.urls('allDocs', 'app', FauxtonAPI.url.encode(doc.database.id)), {trigger: true});
}
- }).fail(function (xhr) {
+ }).catch(err => {
+ const errMsg = err.responseJSON ? err.responseJSON.reason : '';
FauxtonAPI.addNotification({
- msg: 'Save failed: ' + JSON.parse(xhr.responseText).reason,
+ msg: 'Save failed. ' + errMsg,
type: 'error',
fade: false,
clear: true
@@ -129,7 +130,7 @@ const cloneDoc = (database, doc, newId) => {
msg: 'Document has been duplicated.'
});
- }, (error) => {
+ }).catch((error) => {
const errorMsg = `Could not duplicate document, reason: ${error.responseText}.`;
FauxtonAPI.addNotification({
msg: errorMsg,
diff --git a/app/addons/documents/doc-editor/components/DocEditorScreen.js b/app/addons/documents/doc-editor/components/DocEditorScreen.js
index 8edd15315..9da950fbc 100644
--- a/app/addons/documents/doc-editor/components/DocEditorScreen.js
+++ b/app/addons/documents/doc-editor/components/DocEditorScreen.js
@@ -12,7 +12,6 @@
import PropTypes from 'prop-types';
import React from 'react';
-import ReactDOM from 'react-dom';
import FauxtonAPI from '../../../../core/api';
import FauxtonComponents from '../../../fauxton/components';
import GeneralComponents from '../../../components/react-components';
@@ -96,8 +95,10 @@ export default class DocEditorScreen extends React.Component {
if (this.props.numFilesUploaded !== nextProps.numFilesUploaded ||
this.props.doc && this.props.doc.hasChanged() ||
(this.props.doc && nextProps.doc && this.props.doc.id !== nextProps.doc.id)) {
- this.getEditor().setValue(JSON.stringify(nextProps.doc.attributes, null, ' '));
- this.onSaveComplete();
+ if (this.getEditor()) {
+ this.getEditor().setValue(JSON.stringify(nextProps.doc.attributes, null, ' '));
+ this.onSaveComplete();
+ }
}
}
diff --git a/app/addons/documents/index-editor/actions.js b/app/addons/documents/index-editor/actions.js
index a6cf7e75d..59e8e85f4 100644
--- a/app/addons/documents/index-editor/actions.js
+++ b/app/addons/documents/index-editor/actions.js
@@ -43,9 +43,9 @@ const dispatchClearIndex = () => {
const dispatchFetchDesignDocsBeforeEdit = (options) => {
options.designDocs.fetch({reset: true}).then(() => {
editIndex(options)(FauxtonAPI.reduxDispatch);
- }, xhr => {
+ }).catch(err => {
let errorMsg = 'Error';
- if (xhr.responseJSON && xhr.responseJSON.error === 'not_found') {
+ if (err.responseJSON && err.responseJSON.error === 'not_found') {
const databaseName = options.designDocs.database.safeID();
errorMsg = `The ${databaseName} database does not exist`;
FauxtonAPI.navigate('/', {trigger: true});
@@ -103,9 +103,10 @@ const saveView = (viewInfo, navigateToURL) => (dispatch) => {
SidebarActions.dispatchUpdateDesignDocs(viewInfo.designDocs);
dispatch({ type: ActionTypes.VIEW_SAVED });
FauxtonAPI.navigate(navigateToURL, { trigger: true });
- }, (xhr) => {
+ }).catch(err => {
+ const errMsg = err.responseJSON ? err.responseJSON.reason : '';
FauxtonAPI.addNotification({
- msg: 'Save failed. ' + (xhr.responseJSON ? `Reason: ${xhr.responseJSON.reason}` : ''),
+ msg: 'Save failed. ' + errMsg,
type: 'error',
clear: true
});
@@ -173,11 +174,11 @@ const cloneView = (params) => {
clear: true
});
SidebarActions.dispatchUpdateDesignDocs(params.designDocs);
- }, (xhr) => {
+ }).catch(err => {
params.onComplete();
- const responseText = JSON.parse(xhr.responseText).reason;
+ const errMsg = err.responseJSON ? err.responseJSON.reason : '';
FauxtonAPI.addNotification({
- msg: 'Clone failed: ' + responseText,
+ msg: 'Clone failed. ' + errMsg,
type: 'error',
clear: true
});
@@ -236,10 +237,10 @@ const updateNewDesignDocPartitioned = (isPartitioned) => (dispatch) => {
const safeDeleteIndex = (designDoc, designDocs, indexPropName, indexName, options) => {
const opts = _.extend({
onSuccess: function () { },
- onError: function (xhr) {
- const responseText = JSON.parse(xhr.responseText).reason;
+ onError: function (err) {
+ const reason = err.responseJSON ? err.responseJSON.reason : '';
FauxtonAPI.addNotification({
- msg: 'Delete failed: ' + responseText,
+ msg: 'Delete failed. ' + reason,
type: 'error',
clear: true
});
diff --git a/app/addons/documents/index-editor/reducers.js b/app/addons/documents/index-editor/reducers.js
index 51988f6eb..2ae35e074 100644
--- a/app/addons/documents/index-editor/reducers.js
+++ b/app/addons/documents/index-editor/reducers.js
@@ -10,6 +10,7 @@
// License for the specific language governing permissions and limitations under
// the License.
+import Collection from '../../../core/data/collection';
import ActionTypes from './actiontypes';
import Resources from '../resources';
import Helpers from '../helpers';
@@ -20,7 +21,7 @@ const builtInReducers = ['_sum', '_count', '_stats', '_approx_count_distinct'];
const allReducers = builtInReducers.concat(['CUSTOM', 'NONE']);
const initialState = {
- designDocs: new Backbone.Collection(),
+ designDocs: new Collection(),
isLoading: true,
view: { reduce: '', map: defaultMap },
database: { id: '0' },
diff --git a/app/addons/documents/resources.js b/app/addons/documents/resources.js
index a920b8e6a..902eaf6fb 100644
--- a/app/addons/documents/resources.js
+++ b/app/addons/documents/resources.js
@@ -13,7 +13,6 @@
import app from "../../app";
import Helpers from '../../helpers';
import FauxtonAPI from "../../core/api";
-import { post } from "../../core/ajax";
import Documents from "./shared-resources";
Documents.QueryParams = (function () {
@@ -42,35 +41,48 @@ Documents.QueryParams = (function () {
})();
-Documents.DdocInfo = FauxtonAPI.Model.extend({
- idAttribute: "_id",
- documentation: function () {
+class DdocInfoModel extends FauxtonAPI.Model {
+
+ constructor(attributes, options) {
+ super(attributes, options);
+ this.idAttribute = '_id';
+ if (options) {
+ this.database = options.database;
+ }
+ }
+
+ documentation() {
return FauxtonAPI.constants.DOC_URLS.GENERAL;
- },
- initialize: function (_attrs, options) {
- this.database = options.database;
- },
+ }
- url: function (context) {
+ url(context) {
if (!context) {
context = 'server';
}
return FauxtonAPI.urls('designDocs', context, this.database.safeID(), this.safeID());
- },
+ }
// Need this to work around backbone router thinking _design/foo
// is a separate route. Alternatively, maybe these should be
// treated separately. For instance, we could default into the
// json editor for docs, or into a ddoc specific page.
- safeID: function () {
+ safeID() {
var ddoc = this.id.replace(/^_design\//, "");
return "_design/" + app.utils.safeURLName(ddoc);
}
-});
-Documents.NewDoc = Documents.Doc.extend({
- fetch: function () {
+ parse(data) {
+ if (!data._id) {
+ data._id = '_design/' + data.name;
+ }
+ return data;
+ }
+}
+Documents.DdocInfo = DdocInfoModel;
+
+class NewDocModel extends Documents.Doc {
+ fetch() {
const prefix = this.partitionKey ? (this.partitionKey + ':') : '';
return Helpers.getUUID().then((res) => {
if (res.uuids) {
@@ -85,113 +97,7 @@ Documents.NewDoc = Documents.Doc.extend({
this.set("_id", prefix + 'enter_document_id');
});
}
-});
-
-Documents.BulkDeleteDoc = FauxtonAPI.Model.extend({
- idAttribute: "_id"
-});
-
-Documents.BulkDeleteDocCollection = FauxtonAPI.Collection.extend({
-
- model: Documents.BulkDeleteDoc,
-
- sync: function () {
-
- },
-
- initialize: function (models, options) {
- this.databaseId = options.databaseId;
- },
-
- url: function () {
- return FauxtonAPI.urls('bulk_docs', 'server', this.databaseId, '');
- },
-
- bulkDelete: function () {
- const payload = this.createPayload(this.toJSON());
- return new FauxtonAPI.Promise((resolve, reject) => {
- post(this.url(), payload).then(res => {
- if (res.error) {
- throw new Error(res.reason || res.error);
- }
- this.handleResponse(res, resolve, reject);
- }).catch(() => {
- const ids = _.reduce(this.toArray(), (acc, doc) => {
- acc.push(doc.id);
- return acc;
- }, []);
- this.trigger('error', ids);
- reject(ids);
- });
- });
- },
-
- handleResponse: function (res, resolve, reject) {
- var ids = _.reduce(res, function (ids, doc) {
- if (doc.error) {
- ids.errorIds.push(doc.id);
- }
-
- if (!doc.error) {
- ids.successIds.push(doc.id);
- }
-
- return ids;
- }, { errorIds: [], successIds: [] });
-
- this.removeDocuments(ids.successIds);
-
- if (ids.errorIds.length) {
- this.trigger('error', ids.errorIds);
- }
-
- // This is kind of tricky. If there are no documents deleted then rejects
- // otherwise resolve with list of successful and failed documents
- if (!_.isEmpty(ids.successIds)) {
- resolve(ids);
- } else {
- reject(ids.errorIds);
- }
-
- this.trigger('updated');
- },
-
- removeDocuments: function (ids) {
- _.each(ids, (id) => {
- this.remove(this.get(id));
- });
-
- this.trigger('removed', ids);
- },
-
- createPayload: function (documents) {
- var documentList = documents;
-
- return {
- docs: documentList
- };
- }
-});
-
-Documents.MangoBulkDeleteDocCollection = Documents.BulkDeleteDocCollection.extend({
- url: function () {
- return Helpers.getServerUrl(`/${this.databaseId}/_index/_bulk_delete`);
- },
-
- createPayload: function (documents) {
- var documentList = documents
- .filter(function (doc) {
- return doc._id !== '_all_docs';
- })
- .map(function (doc) {
- return doc._id;
- });
-
- return {
- docids: documentList
- };
- }
-
-});
+}
+Documents.NewDoc = NewDocModel;
export default Documents;
diff --git a/app/addons/documents/shared-resources.js b/app/addons/documents/shared-resources.js
index d0ff69257..d3339c031 100644
--- a/app/addons/documents/shared-resources.js
+++ b/app/addons/documents/shared-resources.js
@@ -13,20 +13,35 @@
import app from "../../app";
import FauxtonAPI from "../../core/api";
import { deleteRequest } from "../../core/ajax";
-import PagingCollection from "../../../assets/js/plugins/cloudant.pagingcollection";
+import PagingCollection from "../../core/data/pagingcollection";
// defined here because this is contains the base resources used throughout the addon and outside,
// so it's the first code that gets run
-var Documents = FauxtonAPI.addon();
+const Documents = FauxtonAPI.addon();
+Documents.Doc = class extends FauxtonAPI.Model {
-Documents.Doc = FauxtonAPI.Model.extend({
- idAttribute: "_id",
- documentation: function () {
+ constructor(attributes, options = {}) {
+ super(attributes, options);
+ this.idAttribute = '_id';
+
+ if (this.collection && this.collection.database) {
+ this.database = this.collection.database;
+ } else if (options.database) {
+ this.database = options.database;
+ }
+
+ if (options.fetchConflicts) {
+ this.fetchConflicts = true;
+ }
+ this.partitionKey = options.partitionKey;
+ }
+
+ documentation() {
return FauxtonAPI.constants.DOC_URLS.GENERAL;
- },
+ }
- url: function (context) {
+ url(context) {
if (context === undefined) {
context = 'server';
}
@@ -39,51 +54,43 @@ Documents.Doc = FauxtonAPI.Model.extend({
const query = this.fetchConflicts ? '?conflicts=true' : '';
return FauxtonAPI.urls('document', context, this.getDatabase().safeID(), id, query);
- },
-
- initialize: function (_attrs, options) {
- if (this.collection && this.collection.database) {
- this.database = this.collection.database;
- } else if (options.database) {
- this.database = options.database;
- }
+ }
- if (options.fetchConflicts) {
- this.fetchConflicts = true;
- }
- this.partitionKey = options.partitionKey;
- },
+ isNew() {
+ // This way it always use PUT when saving a Document
+ return false;
+ }
// HACK: the doc needs to know about the database, but it may be
// set directly or indirectly in all docs
- getDatabase: function () {
+ getDatabase() {
return this.database ? this.database : this.collection.database;
- },
+ }
- validate: function (attrs) {
+ validate(attrs) {
if (this.id && this.id !== attrs._id && this.get('_rev')) {
return "Cannot change a documents id.";
}
- },
+ }
- docType: function () {
+ docType() {
return app.utils.getDocTypeFromId(this.id);
- },
+ }
// @deprecated, see isJSONDocBulkDeletable
- isBulkDeletable: function () {
+ isBulkDeletable() {
return !!this.id && !!this.get('_rev');
- },
+ }
- isDeletable: function () {
+ isDeletable() {
return !!this.id;
- },
+ }
- isFromView: function () {
+ isFromView() {
return !this.id;
- },
+ }
- isMangoDoc: function () {
+ isMangoDoc() {
if (!this.isDdoc()) return false;
if (this.get('language') === 'query') {
return true;
@@ -94,13 +101,13 @@ Documents.Doc = FauxtonAPI.Model.extend({
}
return false;
- },
+ }
- isDdoc: function () {
+ isDdoc() {
return this.docType() === "design doc";
- },
+ }
- setDDocPartitionedOption: function (isPartitioned) {
+ setDDocPartitionedOption(isPartitioned) {
if (!this.isDdoc()) {
return false;
}
@@ -112,9 +119,9 @@ Documents.Doc = FauxtonAPI.Model.extend({
this.set({ options });
return true;
- },
+ }
- setDdocView: function (view, map, reduce) {
+ setDdocView(view, map, reduce) {
if (!this.isDdoc()) {
return false;
}
@@ -138,17 +145,17 @@ Documents.Doc = FauxtonAPI.Model.extend({
this.set({views: views});
return true;
- },
+ }
- removeDdocView: function (viewName) {
+ removeDdocView(viewName) {
if (!this.isDdoc()) return false;
var views = this.get('views');
delete views[viewName];
this.set({views: views});
- },
+ }
- dDocModel: function () {
+ dDocModel() {
if (!this.isDdoc()) return false;
var doc = this.get('doc');
@@ -158,23 +165,28 @@ Documents.Doc = FauxtonAPI.Model.extend({
}
return this;
- },
+ }
- safeID: function () {
+ safeID() {
return app.utils.getSafeIdForDoc(this.id);
- },
+ }
- destroy: function () {
- const url = this.url() + "?rev=" + this.get('_rev');
+ destroy() {
+ let url = this.url();
+ if (url.indexOf('?') === -1) {
+ url = url + "?rev=" + this.get('_rev');
+ } else {
+ url = url + "&rev=" + this.get('_rev');
+ }
return deleteRequest(url).then(res => {
if (res.error) {
throw new Error(res.reason || res.error);
}
return res;
});
- },
+ }
- parse: function (resp) {
+ parse(resp) {
if (resp.rev) {
resp._rev = resp.rev;
delete resp.rev;
@@ -191,52 +203,62 @@ Documents.Doc = FauxtonAPI.Model.extend({
}
return resp;
- },
+ }
- prettyJSON: function () {
+ prettyJSON() {
var data = this.get("doc") ? this.get("doc") : this.attributes;
return JSON.stringify(data, null, " ");
- },
+ }
- copy: function (copyId) {
+ copy(copyId) {
const attrs = Object.assign({}, this.attributes, {_id: copyId});
delete attrs._rev;
const clonedDoc = new this.constructor(attrs, {
database: this.database
});
return clonedDoc.save();
- },
+ }
- isNewDoc: function () {
+ isNewDoc() {
return this.get('_rev') ? false : true;
}
-});
+};
+Documents.AllDocs = class extends PagingCollection {
-Documents.AllDocs = PagingCollection.extend({
- model: Documents.Doc,
- documentation: function () {
- return FauxtonAPI.constants.DOC_URLS.GENERAL;
- },
- initialize: function (_models, options) {
- this.viewMeta = options.viewMeta;
- this.database = options.database;
- this.params = _.clone(options.params);
+ constructor(models, options) {
+ super(models, options);
+ this.model = Documents.Doc;
+ }
+
+ initialize(_models, options) {
+ if (options) {
+ this.viewMeta = options.viewMeta;
+ this.database = options.database;
+ this.params = _.clone(options.params);
- this.on("remove", this.decrementTotalRows, this);
- this.perPageLimit = options.perPageLimit || 20;
+ this.perPageLimit = options.perPageLimit || 20;
- if (!this.params.limit) {
- this.params.limit = this.perPageLimit;
+ if (!this.params.limit) {
+ this.params.limit = this.perPageLimit;
+ }
}
- },
+ }
+
+ documentation() {
+ return FauxtonAPI.constants.DOC_URLS.GENERAL;
+ }
+
+ onRemove() {
+ this.decrementTotalRows();
+ }
- isEditable: function () {
+ isEditable () {
return true;
- },
+ }
- urlRef: function (context, params) {
+ urlRef(context, params) {
var query = "";
if (params) {
@@ -252,13 +274,13 @@ Documents.AllDocs = PagingCollection.extend({
context = 'server';
}
return FauxtonAPI.urls('allDocs', context, this.database.safeID(), query);
- },
+ }
- url: function () {
+ url() {
return this.urlRef.apply(this, arguments);
- },
+ }
- simple: function () {
+ simple() {
var docs = this.map(function (item) {
return {
_id: item.id,
@@ -270,27 +292,27 @@ Documents.AllDocs = PagingCollection.extend({
database: this.database,
params: this.params
});
- },
+ }
- totalRows: function () {
+ totalRows() {
return this.viewMeta.total_rows || "unknown";
- },
+ }
- decrementTotalRows: function () {
+ decrementTotalRows() {
if (this.viewMeta.total_rows) {
this.viewMeta.total_rows = this.viewMeta.total_rows - 1;
this.trigger('totalRows:decrement');
}
- },
+ }
- updateSeq: function () {
+ updateSeq() {
if (!this.viewMeta) {
return false;
}
return this.viewMeta.update_seq || false;
- },
+ }
- parse: function (resp) {
+ parse(resp) {
var rows = resp.rows;
// remove any query errors that may return without doc info
@@ -314,16 +336,16 @@ Documents.AllDocs = PagingCollection.extend({
return res;
});
- return PagingCollection.prototype.parse.call(this, resp);
- },
+ return super.parse(resp);
+ }
- clone: function () {
- return new this.constructor(this.models, {
+ clone() {
+ return new Documents.AllDocs(this.models, {
database: this.database,
params: this.params,
paging: this.paging
});
}
-});
+};
export default Documents;
diff --git a/app/addons/documents/sidebar/actions.js b/app/addons/documents/sidebar/actions.js
index d8ba4cd57..6a3b817c2 100644
--- a/app/addons/documents/sidebar/actions.js
+++ b/app/addons/documents/sidebar/actions.js
@@ -32,9 +32,9 @@ const dispatchNewOptions = (options) => {
type: ActionTypes.SIDEBAR_NEW_OPTIONS,
options: options
});
- }, xhr => {
+ }).catch(err => {
let errorMsg = 'Unable to update the sidebar.';
- if (xhr.responseJSON && xhr.responseJSON.error === 'not_found') {
+ if (err.responseJSON && err.responseJSON.error === 'not_found') {
const databaseName = options.designDocs.database.safeID();
errorMsg = `The ${databaseName} database does not exist.`;
FauxtonAPI.navigate('/', {trigger: true});
diff --git a/app/addons/documents/sidebar/reducers.js b/app/addons/documents/sidebar/reducers.js
index a5491d887..d5f775250 100644
--- a/app/addons/documents/sidebar/reducers.js
+++ b/app/addons/documents/sidebar/reducers.js
@@ -12,11 +12,12 @@
import React from 'react';
import app from '../../../app';
+import Collection from '../../../core/data/collection';
import Helpers from '../helpers';
import ActionTypes from './actiontypes';
const initialState = {
- designDocs: new Backbone.Collection(),
+ designDocs: new Collection(),
designDocList: [],
selected: {
navItem: 'all-docs',
diff --git a/app/addons/fauxton/api.js b/app/addons/fauxton/api.js
new file mode 100644
index 000000000..dd7d5c0be
--- /dev/null
+++ b/app/addons/fauxton/api.js
@@ -0,0 +1,18 @@
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+import Helpers from '../../helpers';
+import { get } from '../../core/ajax';
+
+export function fetchVersionInfo() {
+ return get(Helpers.getServerUrl('/'));
+}
diff --git a/app/addons/fauxton/base.js b/app/addons/fauxton/base.js
index a1bb98e90..1a8456e5c 100644
--- a/app/addons/fauxton/base.js
+++ b/app/addons/fauxton/base.js
@@ -10,27 +10,26 @@
// License for the specific language governing permissions and limitations under
// the License.
-import app from '../../app';
import FauxtonAPI from '../../core/api';
import * as NavigationActions from './navigation/actions';
import navigationReducers from './navigation/reducers';
import notificationsReducer from './notifications/reducers';
+import { fetchVersionInfo } from './api';
import './assets/less/fauxton.less';
const Fauxton = FauxtonAPI.addon();
Fauxton.initialize = () => {
- const versionInfo = new Fauxton.VersionInfo();
- versionInfo.fetch().then(function () {
- NavigationActions.setNavbarVersionInfo(versionInfo.get('version'));
+ fetchVersionInfo().then(res => {
+ if (res.version) {
+ NavigationActions.setNavbarVersionInfo(res.version);
+ }
+ }).catch(() => {
+ // ignore
});
};
-Fauxton.VersionInfo = Backbone.Model.extend({
- url: function () {
- return app.host;
- }
-});
+
FauxtonAPI.addReducers({
navigation: navigationReducers,
diff --git a/app/addons/replication/actions.js b/app/addons/replication/actions.js
index 724a04182..5edb6b009 100644
--- a/app/addons/replication/actions.js
+++ b/app/addons/replication/actions.js
@@ -276,10 +276,10 @@ export const deleteReplicates = (replicates) => dispatch => {
escape: false,
clear: true
});
- }, (xhr) => {
- const errorMessage = JSON.parse(xhr.responseText);
+ }).catch(err => {
+ const errorMessage = err.responseJSON ? err.responseJSON.reason : 'Failed to delete replication.';
FauxtonAPI.addNotification({
- msg: errorMessage.reason,
+ msg: errorMessage,
type: 'error',
clear: true
});
diff --git a/app/addons/verifyinstall/actions.js b/app/addons/verifyinstall/actions.js
index e8a5967b1..6ba779096 100644
--- a/app/addons/verifyinstall/actions.js
+++ b/app/addons/verifyinstall/actions.js
@@ -29,9 +29,9 @@ const testPassed = function (test, dispatch) {
let allTestsPassed = true;
const testFailed = function (test, dispatch) {
- return function (xhr) {
+ return function (err) {
allTestsPassed = false;
- if (!xhr) { return; }
+ if (!err) { return; }
dispatch({
type: ActionTypes.VERIFY_INSTALL_SINGLE_TEST_COMPLETE,
@@ -39,10 +39,10 @@ const testFailed = function (test, dispatch) {
success: false
});
let reason = 'n/a';
- if (xhr.responseText) {
- reason = JSON.parse(xhr.responseText).reason;
- } else if (xhr.message) {
- reason = xhr.message;
+ if (err.responseJSON) {
+ reason = err.responseJSON.reason;
+ } else if (err.message) {
+ reason = err.message;
}
FauxtonAPI.addNotification({
msg: 'Error: ' + reason,
diff --git a/app/addons/verifyinstall/resources.js b/app/addons/verifyinstall/resources.js
index 0c9f6896b..6ed13045d 100644
--- a/app/addons/verifyinstall/resources.js
+++ b/app/addons/verifyinstall/resources.js
@@ -59,8 +59,8 @@ Verifyinstall.testProcess = {
resolve();
}).then(() => {
resolve();
- }, (xhr, error, reason) => {
- reject(new Error(reason));
+ }, (err) => {
+ reject(err);
});
});
return promise;
@@ -79,12 +79,7 @@ Verifyinstall.testProcess = {
resolve = res;
reject = rej;
});
- const getPromise = get(viewDoc.url() + '/_view/testview').then(res => {
- if (res.error) {
- throw new Error(res.reason || res.error);
- }
- return res;
- });
+ const getPromise = get(viewDoc.url() + '/_view/testview').then(FauxtonAPI.throwIfCouchDbErrorResponse);
getPromise.then(function (resp) {
resp = _.isString(resp) ? JSON.parse(resp) : resp;
@@ -127,12 +122,7 @@ Verifyinstall.testProcess = {
return post(
Helpers.getServerUrl('/_replicate'),
body
- ).then(res => {
- if (res.error) {
- throw new Error(res.reason || res.error);
- }
- return res;
- });
+ ).then(FauxtonAPI.throwIfCouchDbErrorResponse);
},
testReplicate: function () {
diff --git a/app/core/base.js b/app/core/base.js
index 2278d84ff..53aa9d359 100644
--- a/app/core/base.js
+++ b/app/core/base.js
@@ -12,6 +12,8 @@
import Backbone from "backbone";
import _ from "lodash";
+import Model from './data/model';
+import Collection from './data/collection';
var FauxtonAPI = {
//add default objects
@@ -112,39 +114,40 @@ FauxtonAPI.addon = function (extra) {
return _.extend(_.clone(FauxtonAPI.addonExtensions), extra);
};
-FauxtonAPI.View = Backbone.View.extend({
- // This should return an array of promises, an empty array, or null
- establish: function () {
- return null;
- },
- loaderClassname: 'loader',
- manage: true,
+function fetchOnce (opt) {
+ const options = _.extend({}, opt);
- forceRender: function () {
- this.hasRendered = false;
+ if (!this._fetchPromise || this._fetchPromiseRejected || options.forceFetch) {
+ this._fetchPromise = this.fetch().catch(function (err) {
+ this._fetchPromiseRejected = true;
+ throw err;
+ });
}
-});
+ return this._fetchPromise;
+}
-var caching = {
- fetchOnce: function (opt) {
- var options = _.extend({}, opt);
+FauxtonAPI.Model = class extends Model {
+ fetchOnce = fetchOnce;
+};
- if (!this._deferred || this._deferred.state() === "rejected" || options.forceFetch) {
- this._deferred = this.fetch();
- }
+FauxtonAPI.Collection = class extends Collection {
+ fetchOnce = fetchOnce;
+};
- return this._deferred;
+/**
+ * Checks if the API response is an error and throws Error with the
+ * appropriate message.
+ *
+ * @param {Object} res response from a CouchDB API call
+ * @returns
+ */
+FauxtonAPI.throwIfCouchDbErrorResponse = function (res) {
+ if (res.error) {
+ throw new Error(res.reason || res.error);
}
+ return res;
};
-FauxtonAPI.Model = Backbone.Model.extend({ });
-
-FauxtonAPI.Collection = Backbone.Collection.extend({ });
-
-_.each([FauxtonAPI.Model, FauxtonAPI.Collection], function (ctor) {
- _.extend(ctor.prototype, caching);
-});
-
var extensions = _.extend({}, Backbone.Events);
// Can look at a remove function later.
FauxtonAPI.registerExtension = function (name, view) {
diff --git a/app/core/data/collection.js b/app/core/data/collection.js
new file mode 100644
index 000000000..c43bf0030
--- /dev/null
+++ b/app/core/data/collection.js
@@ -0,0 +1,108 @@
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+import { sendRequest } from './helpers';
+import Model from './model';
+
+/**
+ * A replacement for Backbone.Collection that only depends on 'fetch' and 'Promise'.
+ * Note it's not intended to be a full replacement for Backbone. It only replicates
+ * the Backbone.Model functions required by Fauxton.
+ *
+ * @export
+ * @class Model
+ */
+export default class Collection {
+
+ models = [];
+
+ constructor(models, options) {
+ if (models) {
+ // shallow copy
+ this.models = models.slice(0);
+ }
+ this.initialize(models, options);
+ }
+
+ initialize() {
+ // default is a no-op
+ }
+
+ url() {
+ return '/';
+ }
+
+ fetch() {
+ const url = this.url();
+ return sendRequest(url).then(res => {
+ const parsedRes = this.parse(res);
+ this.models = parsedRes.map(obj => {
+ let newModel;
+ const options = { collection: this };
+ if (this.model) {
+ newModel = new this.model(obj, options);
+ } else {
+ newModel = new Model(obj, options);
+ }
+ return newModel;
+ });
+ return res;
+ });
+ }
+
+ parse(res) {
+ return res;
+ }
+
+ filter(fn) {
+ return this.models.filter(fn);
+ }
+
+ find(fn) {
+ return this.models.find(fn);
+ }
+
+ map(fn) {
+ return this.models.map(fn);
+ }
+
+ onRemove() {
+ // default is a no-op
+ }
+
+ toJSON() {
+ return this.models.map(obj => obj.toJSON());
+ }
+
+ add(models) {
+ const toAdd = Array.isArray(models) ? models : [models];
+ toAdd.forEach(modelToAdd => {
+ const idx = this.models.findIndex(el => el.id === modelToAdd.id);
+ //Only add if it's not part of the collection yet
+ if (idx === -1) {
+ modelToAdd.collection = this;
+ this.models.push(modelToAdd);
+ }
+ });
+ }
+
+ remove(models) {
+ const toRemove = Array.isArray(models) ? models : [models];
+ toRemove.forEach(modelToRemove => {
+ const idx = this.models.findIndex(el => el.id === modelToRemove.id);
+ if (idx > -1) {
+ this.models.splice(idx, 1);
+ this.onRemove();
+ }
+ });
+ }
+}
diff --git a/app/core/data/helpers.js b/app/core/data/helpers.js
new file mode 100644
index 000000000..022d54f5b
--- /dev/null
+++ b/app/core/data/helpers.js
@@ -0,0 +1,46 @@
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+export const sendRequest = (url, method = "GET", body) => {
+ const options = {
+ method,
+ credentials: "include",
+ headers: {
+ accept: "application/json",
+ "Content-Type": "application/json",
+ "Pragma":"no-cache"
+ },
+ cache: "no-cache",
+ body: body ? JSON.stringify(body) : undefined
+ };
+ return fetch(url, options).then(res => {
+ if (!res.ok) {
+ return res.text().then(errAsText => {
+ const err = new Error(errAsText);
+ // Add these fields for compatibility with XHR response that backbone uses
+ err.status = res.status;
+ err.responseText = errAsText;
+ try {
+ err.responseJSON = JSON.parse(errAsText);
+ } catch (e) {
+ //ignore
+ }
+ throw err;
+ });
+ }
+ return res.json();
+ });
+};
+
+export function isObject(value) {
+ return typeof value === 'object' && value !== null;
+}
diff --git a/app/core/data/model.js b/app/core/data/model.js
new file mode 100644
index 000000000..b447a3ef8
--- /dev/null
+++ b/app/core/data/model.js
@@ -0,0 +1,147 @@
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+import { sendRequest, isObject } from './helpers';
+
+/**
+ * A replacement for Backbone.Model that only depends on 'fetch' and 'Promise'.
+ * Note it's not intended to be a full replacement for Backbone. It only replicates
+ * the Backbone.Model functions required by Fauxton.
+ *
+ * @export
+ * @class Model
+ */
+export default class Model {
+
+ attributes = {};
+ exists = false;
+ isDirty = false;
+
+ /**
+ *Creates an instance of Model.
+ * @param {*} attributes
+ * @param {*} [options={}]
+ * @memberof Model
+ */
+ constructor(attributes, options = {}) {
+ if (attributes) {
+ this.attributes = attributes;
+ }
+ if (options && options.collection) {
+ this.collection = options.collection;
+ }
+ }
+
+ get id() {
+ // It's weird but it's possible that fetch() retrieves
+ // data that doesn't contain the ID attribute. This makes
+ // sure that 'this.id' will return a valid ID if it was ever set.
+
+ if (this.idAttribute) {
+ if (this.attributes[this.idAttribute]) {
+ this.lastKnownId = this.attributes[this.idAttribute];
+ }
+ return this.attributes[this.idAttribute];
+ }
+ if (this.attributes.id) {
+ this.lastKnownId = this.attributes.id;
+ return this.attributes.id;
+ }
+ return this.lastKnownId;
+ }
+
+ isNew() {
+ return !this.exists;
+ }
+
+ save() {
+ const url = this.url();
+ const method = this.isNew() ? 'POST' : 'PUT';
+ return sendRequest(url, method, this.attributes).then(res => {
+ if (res.ok) {
+ if (res.rev) {
+ this.attributes._rev = res.rev;
+ }
+ this.exists = true;
+ this.isDirty = false;
+ }
+ return res;
+ });
+ }
+
+ destroy() {
+ return sendRequest(this.url(), 'DELETE');
+ }
+
+ url() {
+ if (this.id) {
+ return '/' + encodeURIComponent(this.id);
+ }
+ }
+
+ fetch() {
+ const url = this.url();
+ if (url) {
+ return sendRequest(url).then(res => {
+ this.attributes = this.parse(res);
+ this.exists = true;
+ return res;
+ });
+ }
+ return Promise.reject(new Error('Model has an invalid url.'));
+ }
+
+ parse(data) {
+ return data;
+ }
+
+ get(propName) {
+ return this.attributes[propName];
+ }
+
+ set(arg1, arg2) {
+ if (typeof arg1 === 'string' && arg2 !== undefined && arg2 !== null) {
+ this.attributes[arg1] = arg2;
+ this.isDirty = true;
+ } else if (isObject(arg1)) {
+ Object.assign(this.attributes, arg1);
+ this.isDirty = true;
+ }
+ }
+
+ unset(propName) {
+ delete this.attributes[propName];
+ }
+
+ hasChanged() {
+ return this.isDirty;
+ }
+
+ clear() {
+ this.attributes = {};
+ this.exists = false;
+ this.isDirty = false;
+ return this;
+ }
+
+ on() {
+ throw new Error('Method "on" is not supported.');
+ }
+
+ trigger() {
+ throw new Error('Method "trigger" is not supported.');
+ }
+
+ toJSON() {
+ return Object.assign({}, this.attributes);
+ }
+}
diff --git a/assets/js/plugins/cloudant.pagingcollection.js b/app/core/data/pagingcollection.js
similarity index 66%
rename from assets/js/plugins/cloudant.pagingcollection.js
rename to app/core/data/pagingcollection.js
index 0a63ffe0a..0f125a402 100644
--- a/assets/js/plugins/cloudant.pagingcollection.js
+++ b/app/core/data/pagingcollection.js
@@ -11,26 +11,27 @@
// the License.
import _ from 'lodash';
-import $ from 'jquery';
-import Backbone from "backbone";
-import app from '../../../app/app';
-
-//PagingCollection
-//----------------
-
-// A PagingCollection knows how to build appropriate requests to the
-// CouchDB-like server and how to fetch. The Collection will always contain a
-// single page of documents.
-
-export const PagingCollection = Backbone.Collection.extend({
+import app from '../../app';
+import Collection from './collection';
+
+/**
+ * A PagingCollection knows how to build appropriate requests to the
+ * CouchDB-like server and how to fetch. The Collection will always contain a
+ * single page of documents.
+ *
+ * @export
+ * @class PagingCollection
+ * @extends {Collection}
+ */
+export default class PagingCollection extends Collection {
// initialize parameters and page size
- constructor: function() {
- Backbone.Collection.apply(this, arguments);
+ constructor(models, options) {
+ super(models, options);
this.configure.apply(this, arguments);
- },
+ }
- configure: function(collections, options) {
+ configure(collections, options) {
var querystring = _.result(this, "url").split("?")[1] || "";
this.paging = _.defaults((options.paging || {}), {
defaultParams: _.defaults({}, options.params, this._parseQueryString(querystring)),
@@ -43,9 +44,9 @@ export const PagingCollection = Backbone.Collection.extend({
this.paging.params = _.clone(this.paging.defaultParams);
this.updateUrlQuery(this.paging.defaultParams);
- },
+ }
- calculateParams: function(currentParams, skipIncrement, limitIncrement) {
+ calculateParams(currentParams, skipIncrement, limitIncrement) {
var params = _.clone(currentParams);
params.skip = (parseInt(currentParams.skip, 10) || 0) + skipIncrement;
@@ -60,10 +61,10 @@ export const PagingCollection = Backbone.Collection.extend({
params.skip = Math.max(params.skip, 0);
return params;
- },
+ }
- pageSizeReset: function(pageSize, opts) {
- var options = _.defaults((opts || {}), {fetch: true});
+ pageSizeReset(pageSize, opts) {
+ var options = _.defaults((opts || {}), { fetch: true });
this.paging.direction = undefined;
this.paging.pageSize = pageSize;
this.paging.params = this.paging.defaultParams;
@@ -72,71 +73,71 @@ export const PagingCollection = Backbone.Collection.extend({
if (options.fetch) {
return this.fetch();
}
- },
+ }
- _parseQueryString: function(uri) {
- var queryString = decodeURI(uri).split(/&/);
+ _parseQueryString(uri) {
+ const queryString = decodeURI(uri).split(/&/);
return _.reduce(queryString, function (parsedQuery, item) {
- var nameValue = item.split(/=/);
- if (nameValue.length === 2) {
- parsedQuery[nameValue[0]] = nameValue[1];
- }
+ const nameValue = item.split(/=/);
+ if (nameValue.length === 2) {
+ parsedQuery[nameValue[0]] = nameValue[1];
+ }
- return parsedQuery;
+ return parsedQuery;
}, {});
- },
+ }
- _iterate: function(offset, opts) {
- var options = _.defaults((opts || {}), {fetch: true});
+ _iterate(offset, opts) {
+ const options = _.defaults((opts || {}), { fetch: true });
this.paging.params = this.calculateParams(this.paging.params, offset, this.paging.pageSize);
// Fetch the next page of documents
this.updateUrlQuery(this.paging.params);
if (options.fetch) {
- return this.fetch({reset: true});
+ return this.fetch({ reset: true });
}
- },
+ }
// `next` is called with the number of items for the next page.
// It returns the fetch promise.
- next: function(options) {
+ next(options) {
this.paging.direction = "next";
return this._iterate(this.paging.pageSize, options);
- },
+ }
// `previous` is called with the number of items for the previous page.
// It returns the fetch promise.
- previous: function(options) {
+ previous(options) {
this.paging.direction = "previous";
return this._iterate(0 - this.paging.pageSize, options);
- },
+ }
- shouldStringify: function (val) {
+ shouldStringify(val) {
try {
JSON.parse(val);
return false;
} catch (e) {
return true;
}
- },
+ }
// Encodes the parameters so that couchdb will understand them
// and then sets the url with the new url.
- updateUrlQuery: function (params) {
- var url = _.result(this, "url").split("?")[0];
-
+ updateUrlQuery(params) {
+ let url = this.url().split("?")[0];
_.each(['startkey', 'endkey', 'key'], (key) => {
if (_.has(params, key) && this.shouldStringify(params[key])) {
params[key] = JSON.stringify(params[key]);
}
});
- this.url = url + '?' + app.utils.queryParams(params);
- },
+ url = url + '?' + app.utils.queryParams(params);
+ this.url = () => url;
+ }
- fetch: function () {
+ fetch() {
// if this is a fetch for the first time, fetch one extra to see if there is a next
if (!this.paging.direction && this.paging.params.limit > 0) {
this.paging.direction = 'fetch';
@@ -144,11 +145,11 @@ export const PagingCollection = Backbone.Collection.extend({
this.updateUrlQuery(this.paging.params);
}
- return Backbone.Collection.prototype.fetch.apply(this, arguments);
- },
+ return super.fetch.apply(this, arguments);
+ }
- parse: function (resp) {
- var rows = resp.rows;
+ parse(resp) {
+ const rows = resp.rows;
this.paging.hasNext = this.paging.hasPrevious = false;
@@ -170,31 +171,13 @@ export const PagingCollection = Backbone.Collection.extend({
this.viewMeta.total_rows = this.viewMeta.total_rows - 1;
}
return rows;
- },
+ }
- hasNext: function() {
+ hasNext() {
return this.paging.hasNext;
- },
+ }
- hasPrevious: function() {
+ hasPrevious() {
return this.paging.hasPrevious;
}
-});
-
-export default PagingCollection;
-
-
-// if (exports) {
-// // Overload the Backbone.ajax method, this allows PagingCollection to be able to
-// // work in node.js
-// exports.setAjax = function (ajax) {
-// Backbone.ajax = ajax;
-// };
-
-// exports.PagingCollection = PagingCollection;
-// }
-
-// return PagingCollection;
-// }));
-
-
+}
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
With regards,
Apache Git Services