Skip to content

Commit

Permalink
Fixes #141 - Always brace single-line controlled statements.
Browse files Browse the repository at this point in the history
  • Loading branch information
n1k0 committed Sep 1, 2015
1 parent afdd3ba commit b46207b
Show file tree
Hide file tree
Showing 11 changed files with 86 additions and 44 deletions.
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"parser": "babel-eslint",
"rules": {
"curly": [2],
"indent": [2, 2],
"quotes": [2, "double"],
"linebreak-style": [2, "unix"],
Expand Down
3 changes: 2 additions & 1 deletion src/adapters/IDB.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ export default class IDB extends BaseAdapter {
* @return {Promise}
*/
open() {
if (this._db)
if (this._db) {
return Promise.resolve(this);
}
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.dbname, 1);
request.onupgradeneeded = event => {
Expand Down
6 changes: 4 additions & 2 deletions src/adapters/LocalStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,9 @@ export default class LocalStorage extends BaseAdapter {
* @return {Promise}
*/
create(record) {
if (this.keys.indexOf(record.id) !== -1)
if (this.keys.indexOf(record.id) !== -1) {
return Promise.reject(new Error("Exists."));
}
try {
localStorage.setItem(`${this.dbname}/${record.id}`, JSON.stringify(record));
this.keys = this.keys.concat(record.id);
Expand All @@ -84,8 +85,9 @@ export default class LocalStorage extends BaseAdapter {
* @return {Promise}
*/
update(record) {
if (this.keys.indexOf(record.id) === -1)
if (this.keys.indexOf(record.id) === -1) {
return Promise.reject(new Error("Doesn't exist."));
}
try {
localStorage.setItem(`${this.dbname}/${record.id}`, JSON.stringify(record));
return Promise.resolve(record);
Expand Down
21 changes: 14 additions & 7 deletions src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ export const SUPPORTED_PROTOCOL_VERSION = "v1";

export function cleanRecord(record, excludeFields=RECORD_FIELDS_TO_CLEAN) {
return Object.keys(record).reduce((acc, key) => {
if (excludeFields.indexOf(key) === -1)
if (excludeFields.indexOf(key) === -1) {
acc[key] = record[key];
}
return acc;
}, {});
}
Expand All @@ -32,10 +33,12 @@ export default class Api {
* @param {Object} options The options object.
*/
constructor(remote, options={}) {
if (typeof(remote) !== "string" || !remote.length)
if (typeof(remote) !== "string" || !remote.length) {
throw new Error("Invalid remote URL: " + remote);
if (remote[remote.length-1] === "/")
}
if (remote[remote.length-1] === "/") {
remote = remote.slice(0, -1);
}
this._backoffReleaseTime = null;
// public properties
this.remote = remote;
Expand All @@ -47,8 +50,9 @@ export default class Api {
} catch (err) {
throw new Error("The remote URL must contain the version: " + remote);
}
if (this.version !== SUPPORTED_PROTOCOL_VERSION)
if (this.version !== SUPPORTED_PROTOCOL_VERSION) {
throw new Error(`Unsupported protocol version: ${this.version}`);
}
this.http = new HTTP({events: this.events, requestMode: options.requestMode});
this._registerHTTPEvents();
}
Expand All @@ -61,8 +65,9 @@ export default class Api {
*/
get backoff() {
const currentTime = new Date().getTime();
if (this._backoffReleaseTime && currentTime < this._backoffReleaseTime)
if (this._backoffReleaseTime && currentTime < this._backoffReleaseTime) {
return this._backoffReleaseTime - currentTime;
}
return 0;
}

Expand Down Expand Up @@ -103,8 +108,9 @@ export default class Api {
* @return {Promise}
*/
fetchServerSettings() {
if (this.serverSettings)
if (this.serverSettings) {
return Promise.resolve(this.serverSettings);
}
return this.http.request(this.endpoints().root())
.then(res => {
this.serverSettings = res.json.settings;
Expand Down Expand Up @@ -230,8 +236,9 @@ export default class Api {
conflicts: [],
skipped: []
};
if (!records.length)
if (!records.length) {
return Promise.resolve(results);
}
return this.fetchServerSettings()
.then(serverSettings => {
const maxRequests = serverSettings["cliquet.batch_max_requests"];
Expand Down
56 changes: 37 additions & 19 deletions src/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ export class SyncResultObject {
}

add(type, entries) {
if (!Array.isArray(this[type]))
if (!Array.isArray(this[type])) {
return;
}
this[type] = this[type].concat(entries);
this.ok = this.errors.length + this.conflicts.length === 0;
}
Expand Down Expand Up @@ -63,8 +64,9 @@ export default class Collection {
const DBAdapter = options.adapter || IDB;
const dbPrefix = options.dbPrefix || "";
const db = new DBAdapter(`${dbPrefix}${bucket}/${name}`);
if (!(db instanceof BaseAdapter))
if (!(db instanceof BaseAdapter)) {
throw new Error("Unsupported adapter.");
}
// public properties
this.db = db;
this.api = api;
Expand Down Expand Up @@ -114,8 +116,9 @@ export default class Collection {
* @return {Promise}
*/
_encodeRecord(type, record) {
if (!this._transformers[type].length)
if (!this._transformers[type].length) {
return Promise.resolve(record);
}
return waterfall(this._transformers[type].map(transfomer => {
return record => transfomer.encode(record);
}), record);
Expand All @@ -129,8 +132,9 @@ export default class Collection {
* @return {Promise}
*/
_decodeRecord(type, record) {
if (!this._transformers[type].length)
if (!this._transformers[type].length) {
return Promise.resolve(record);
}
return waterfall(this._transformers[type].reverse().map(transformer => {
return record => transformer.decode(record);
}), record);
Expand All @@ -149,14 +153,16 @@ export default class Collection {
* @return {Promise}
*/
create(record, options={forceUUID: false, synced: false}) {
if (typeof(record) !== "object")
if (typeof(record) !== "object") {
return Promise.reject(new Error("Record is not an object."));
}
const newRecord = Object.assign({}, record, {
id: options.synced || options.forceUUID ? record.id : uuid4(),
_status: options.synced ? "synced" : "created"
});
if (!isUUID4(newRecord.id))
if (!isUUID4(newRecord.id)) {
return Promise.reject(new Error(`Invalid UUID: ${newRecord.id}`));
}
return this.db.create(newRecord).then(record => {
return {data: record, permissions: {}};
});
Expand All @@ -173,12 +179,15 @@ export default class Collection {
* @return {Promise}
*/
update(record, options={synced: false}) {
if (typeof(record) !== "object")
if (typeof(record) !== "object") {
return Promise.reject(new Error("Record is not an object."));
if (!record.id)
}
if (!record.id) {
return Promise.reject(new Error("Cannot update a record missing id."));
if (!isUUID4(record.id))
}
if (!isUUID4(record.id)) {
return Promise.reject(new Error(`Invalid UUID: ${record.id}`));
}
return this.get(record.id).then(_ => {
var newStatus = "updated";
if (record._status === "deleted") {
Expand Down Expand Up @@ -216,8 +225,9 @@ export default class Collection {
* @return {Promise}
*/
get(id, options={includeDeleted: false}) {
if (!isUUID4(id))
if (!isUUID4(id)) {
return Promise.reject(Error(`Invalid UUID: ${id}`));
}
return this.db.get(id).then(record => {
if (!record ||
(!options.includeDeleted && record._status === "deleted")) {
Expand All @@ -240,8 +250,9 @@ export default class Collection {
* @return {Promise}
*/
delete(id, options={virtual: true}) {
if (!isUUID4(id))
if (!isUUID4(id)) {
return Promise.reject(new Error(`Invalid UUID: ${id}`));
}
// Ensure the record actually exists.
return this.get(id, {includeDeleted: true}).then(res => {
if (options.virtual) {
Expand Down Expand Up @@ -281,8 +292,9 @@ export default class Collection {
params = Object.assign({order: "-last_modified", filters: {}}, params);
return this.db.list().then(results => {
var reduced = reduceRecords(params.filters, params.order, results);
if (!options.includeDeleted)
if (!options.includeDeleted) {
reduced = reduced.filter(record => record._status !== "deleted");
}
return {data: reduced, permissions: {}};
});
}
Expand Down Expand Up @@ -345,12 +357,14 @@ export default class Collection {
// Matching local record found
.then(res => this._processChangeImport(res.data, _decodedChange))
.catch(err => {
if (!(/not found/i).test(err.message))
if (!(/not found/i).test(err.message)) {
return {type: "errors", data: err};
}
// Not found locally but remote change is marked as deleted; skip to
// avoid recreation.
if (_decodedChange.deleted)
if (_decodedChange.deleted) {
return {type: "skipped", data: _decodedChange};
}
return this.create(_decodedChange, {synced: true}).then(res => {
return {type: "created", data: res.data};
});
Expand All @@ -377,8 +391,9 @@ export default class Collection {
.then(syncResultObject => {
syncResultObject.lastModified = changeObject.lastModified;
// Don't persist lastModified value if conflicts occured
if (syncResultObject.conflicts.length > 0)
if (syncResultObject.conflicts.length > 0) {
return syncResultObject;
}
// No conflict occured, persist collection's lastModified value
return this.db.saveLastModified(syncResultObject.lastModified)
.then(lastModified => {
Expand All @@ -401,10 +416,11 @@ export default class Collection {
return this.list({}, {includeDeleted: true})
.then(res => {
return res.data.reduce((acc, record) => {
if (record._status === "deleted" && !record.last_modified)
if (record._status === "deleted" && !record.last_modified) {
acc.toDelete.push(record);
else if (record._status !== "synced")
} else if (record._status !== "synced") {
acc.toSync.push(record);
}
return acc;
// rename toSync to toPush or toPublish
}, {toDelete: [], toSync: []});
Expand Down Expand Up @@ -514,12 +530,14 @@ export default class Collection {
.then(lastModified => this._lastModified = lastModified)
.then(_ => this.pullChanges(result, options))
.then(result => {
if (!result.ok)
if (!result.ok) {
return result;
}
return this.pushChanges(result, options)
.then(result => {
if (!result.ok || result.published.length === 0)
if (!result.ok || result.published.length === 0) {
return result;
}
return this.pullChanges(result, options);
});
});
Expand Down
9 changes: 6 additions & 3 deletions src/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,9 @@ export default class HTTP {
this._checkForDeprecationHeader(headers);
this._checkForBackoffHeader(status, headers);
const contentLength = headers.get("Content-Length");
if (!contentLength || contentLength == 0)
if (!contentLength || contentLength == 0) {
return null;
}
return res.json();
})
.catch(err => {
Expand Down Expand Up @@ -90,8 +91,9 @@ export default class HTTP {

_checkForDeprecationHeader(headers) {
const alertHeader = headers.get("Alert");
if (!alertHeader)
if (!alertHeader) {
return;
}
var alert;
try {
alert = JSON.parse(alertHeader);
Expand All @@ -106,8 +108,9 @@ export default class HTTP {
_checkForBackoffHeader(status, headers) {
// XXX Temporary fix
// see https://github.com/mozilla-services/kinto/issues/148
if (status === 304)
if (status === 304) {
return;
}
var backoffMs;
const backoffSeconds = parseInt(headers.get("Backoff"), 10);
if (backoffSeconds > 0) {
Expand Down
3 changes: 2 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,9 @@ export default class Kinto {
* @return {Collection}
*/
collection(collName) {
if (!collName)
if (!collName) {
throw new Error("missing collection name");
}

const remote = this._options.remote;
const api = new Api(remote, {
Expand Down
20 changes: 13 additions & 7 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,15 @@ export function sortObjects(order, list) {
const field = hasDash ? order.slice(1) : order;
const direction = hasDash ? -1 : 1;
return list.slice().sort((a, b) => {
if (a[field] && _isUndefined(b[field]))
if (a[field] && _isUndefined(b[field])) {
return direction;
if (b[field] && _isUndefined(a[field]))
}
if (b[field] && _isUndefined(a[field])) {
return -direction;
if (_isUndefined(a[field]) && _isUndefined(b[field]))
}
if (_isUndefined(a[field]) && _isUndefined(b[field])) {
return 0;
}
return a[field] > b[field] ? direction : -direction;
});
}
Expand Down Expand Up @@ -107,13 +110,15 @@ export function reduceRecords(filters, order, list) {
* @return {Array}
*/
export function partition(array, n) {
if (n <= 0)
if (n <= 0) {
return array;
}
return array.reduce((acc, x, i) => {
if (i === 0 || i % n === 0)
if (i === 0 || i % n === 0) {
acc.push([x]);
else
} else {
acc[acc.length - 1].push(x);
}
return acc;
}, []);
}
Expand All @@ -137,8 +142,9 @@ export function isUUID4(uuid) {
* @return {Promise}
*/
export function waterfall(fns, init) {
if (!fns.length)
if (!fns.length) {
return Promise.resolve(init);
}
return fns.reduce((promise, nextFn) => {
return promise.then(nextFn);
}, Promise.resolve(init));
Expand Down
3 changes: 2 additions & 1 deletion test/http_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,9 @@ describe("HTTP class", () => {
status: 200,
headers: {
get(name) {
if (name !== "Alert")
if (name !== "Alert") {
return "fake";
}
}
},
json() {
Expand Down

0 comments on commit b46207b

Please sign in to comment.