Skip to content

Commit

Permalink
feat: Common database adapter utilities and test suite (#1130)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: Move database adapter utilities from @feathersjs/commons into its own module
  • Loading branch information
daffl authored Dec 16, 2018
1 parent c73d322 commit 17b3dc8
Show file tree
Hide file tree
Showing 26 changed files with 1,933 additions and 603 deletions.
1 change: 1 addition & 0 deletions .codeclimate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ plugins:
count_threshold: 3
exclude_patterns:
- "**/test/*"
- "**/tests/*"
- "**/dist/*"
- "**/*.dist.js"
- "**/templates/*"
22 changes: 22 additions & 0 deletions packages/adapter-commons/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2018 Feathers

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

22 changes: 22 additions & 0 deletions packages/adapter-commons/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Feathers Adapter Commons

[![Build Status](https://travis-ci.org/feathersjs/feathers.png?branch=master)](https://travis-ci.org/feathersjs/feathers)
[![Dependency Status](https://img.shields.io/david/feathersjs/feathers.svg?style=flat-square&path=packages/commons)](https://david-dm.org/feathersjs/feathers?path=packages/commons)
[![Download Status](https://img.shields.io/npm/dm/@feathersjs/adapter-commons.svg?style=flat-square)](https://www.npmjs.com/package/@feathersjs/adapter-commons)

> Shared utility functions for Feathers adatabase adapters
## About

This is a repository for handling Feathers common database syntax.


## Authors

[Feathers contributors](https://github.com/feathersjs/commons/graphs/contributors)

## License

Copyright (c) 2018 Feathers contributors

Licensed under the [MIT license](LICENSE).
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { _ } = require('./utils');
const { _ } = require('@feathersjs/commons');

function parse (number) {
if (typeof number !== 'undefined') {
Expand Down Expand Up @@ -34,10 +34,13 @@ function convertSort (sort) {
}

function cleanQuery (query, operators) {
if (_.isObject(query)) {
if (_.isObject(query) && query.constructor === {}.constructor) {
const result = {};
_.each(query, (query, key) => {
if (key[0] === '$' && operators.indexOf(key) === -1) return;
if (key[0] === '$' && operators.indexOf(key) === -1) {
return;
}

result[key] = cleanQuery(query, operators);
});
return result;
Expand All @@ -49,11 +52,17 @@ function cleanQuery (query, operators) {
function assignFilters (object, query, filters, options) {
if (Array.isArray(filters)) {
_.each(filters, (key) => {
object[key] = query[key];
if (query[key] !== undefined) {
object[key] = query[key];
}
});
} else {
_.each(filters, (converter, key) => {
object[key] = converter(query[key], options);
const converted = converter(query[key], options);

if (converted !== undefined) {
object[key] = converted;
}
});
}

Expand Down
38 changes: 38 additions & 0 deletions packages/adapter-commons/lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const { _ } = require('@feathersjs/commons');

const AdapterService = require('./service');
const filterQuery = require('./filter-query');
const sort = require('./sort');

// Return a function that filters a result object or array
// and picks only the fields passed as `params.query.$select`
// and additional `otherFields`
const select = function select (params, ...otherFields) {
const fields = params && params.query && params.query.$select;

if (Array.isArray(fields) && otherFields.length) {
fields.push(...otherFields);
}

const convert = result => {
if (!Array.isArray(fields)) {
return result;
}

return _.pick(result, ...fields);
};

return result => {
if (Array.isArray(result)) {
return result.map(convert);
}

return convert(result);
};
};

module.exports = Object.assign({
select,
filterQuery,
AdapterService
}, sort);
87 changes: 87 additions & 0 deletions packages/adapter-commons/lib/service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
const { NotImplemented, BadRequest, MethodNotAllowed } = require('@feathersjs/errors');
const filterQuery = require('./filter-query');

const callMethod = (self, name, ...args) => {
if (typeof self[name] !== 'function') {
return Promise.reject(new NotImplemented(`Method ${name} not available`));
}

return self[name](...args);
};

const checkMulti = (method, option) => {
if (option === true) {
return;
}

return Array.isArray(option) ? option.includes(method) : false;
};

module.exports = class AdapterService {
constructor (options) {
this.options = Object.assign({
events: [],
paginate: {},
multi: false
}, options);
}

get id () {
return this.options.id;
}

get events () {
return this.options.events;
}

filterQuery (params = {}, options = {}) {
const paginate = typeof params.paginate !== 'undefined'
? params.paginate : this.options.paginate;
const { query = {} } = params;
const result = filterQuery(query, Object.assign({ paginate }, options));

return Object.assign(result, { paginate });
}

find (params) {
return callMethod(this, '_find', params);
}

get (id, params) {
return callMethod(this, '_get', id, params);
}

create (data, params) {
if (Array.isArray(data) && !checkMulti('create', this.options.multi)) {
return Promise.reject(new MethodNotAllowed(`Can not create multiple entries`));
}

return callMethod(this, '_create', data, params);
}

update (id, data, params) {
if (id === null || Array.isArray(data)) {
return Promise.reject(new BadRequest(
`You can not replace multiple instances. Did you mean 'patch'?`
));
}

return callMethod(this, '_update', id, data, params);
}

patch (id, data, params) {
if (id === null && !checkMulti('patch', this.options.multi)) {
return Promise.reject(new MethodNotAllowed(`Can not patch multiple entries`));
}

return callMethod(this, '_patch', id, data, params);
}

remove (id, data, params) {
if (id === null && !checkMulti('remove', this.options.multi)) {
return Promise.reject(new MethodNotAllowed(`Can not remove multiple entries`));
}

return callMethod(this, '_remove', id, data, params);
}
};
92 changes: 92 additions & 0 deletions packages/adapter-commons/lib/sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Sorting algorithm taken from NeDB (https://github.com/louischatriot/nedb)
// See https://github.com/louischatriot/nedb/blob/e3f0078499aa1005a59d0c2372e425ab789145c1/lib/model.js#L189

exports.compareNSB = function (a, b) {
if (a < b) { return -1; }
if (a > b) { return 1; }
return 0;
};

exports.compareArrays = function (a, b) {
var i, comp;

for (i = 0; i < Math.min(a.length, b.length); i += 1) {
comp = exports.compare(a[i], b[i]);

if (comp !== 0) { return comp; }
}

// Common section was identical, longest one wins
return exports.compareNSB(a.length, b.length);
};

exports.compare = function (a, b, compareStrings = exports.compareNSB) {
const { compareNSB, compare, compareArrays } = exports;

// undefined
if (a === undefined) { return b === undefined ? 0 : -1; }
if (b === undefined) { return a === undefined ? 0 : 1; }

// null
if (a === null) { return b === null ? 0 : -1; }
if (b === null) { return a === null ? 0 : 1; }

// Numbers
if (typeof a === 'number') { return typeof b === 'number' ? compareNSB(a, b) : -1; }
if (typeof b === 'number') { return typeof a === 'number' ? compareNSB(a, b) : 1; }

// Strings
if (typeof a === 'string') { return typeof b === 'string' ? compareStrings(a, b) : -1; }
if (typeof b === 'string') { return typeof a === 'string' ? compareStrings(a, b) : 1; }

// Booleans
if (typeof a === 'boolean') { return typeof b === 'boolean' ? compareNSB(a, b) : -1; }
if (typeof b === 'boolean') { return typeof a === 'boolean' ? compareNSB(a, b) : 1; }

// Dates
if (a instanceof Date) { return b instanceof Date ? compareNSB(a.getTime(), b.getTime()) : -1; }
if (b instanceof Date) { return a instanceof Date ? compareNSB(a.getTime(), b.getTime()) : 1; }

// Arrays (first element is most significant and so on)
if (Array.isArray(a)) { return Array.isArray(b) ? compareArrays(a, b) : -1; }
if (Array.isArray(b)) { return Array.isArray(a) ? compareArrays(a, b) : 1; }

// Objects
const aKeys = Object.keys(a).sort();
const bKeys = Object.keys(b).sort();
let comp = 0;

for (let i = 0; i < Math.min(aKeys.length, bKeys.length); i += 1) {
comp = compare(a[aKeys[i]], b[bKeys[i]]);

if (comp !== 0) { return comp; }
}

return compareNSB(aKeys.length, bKeys.length);
};

// An in-memory sorting function according to the
// $sort special query parameter
exports.sorter = function ($sort) {
const criteria = Object.keys($sort).map(key => {
const direction = $sort[key];

return { key, direction };
});

return function (a, b) {
let compare;

for (let i = 0; i < criteria.length; i++) {
const criterion = criteria[i];

compare = criterion.direction * exports.compare(a[criterion.key], b[criterion.key]);

if (compare !== 0) {
return compare;
}
}

return 0;
};
};
53 changes: 53 additions & 0 deletions packages/adapter-commons/lib/tests/basic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const assert = require('assert');

module.exports = (test, app, errors, serviceName, idProp) => {
describe('Basic Functionality', () => {
let service;

beforeEach(() => {
service = app.service(serviceName);
});

it('.id', () => {
assert.strictEqual(service.id, idProp,
'id property is set to expected name'
);
});

test('.options', () => {
assert.ok(service.options, 'Options are available in service.options');
});

test('.events', () => {
assert.ok(service.events.includes('testing'),
'service.events is set and includes "testing"'
);
});

describe('Raw Methods', () => {
test('._get', () => {
assert.strictEqual(typeof service._get, 'function');
});

test('._find', () => {
assert.strictEqual(typeof service._find, 'function');
});

test('._create', () => {
assert.strictEqual(typeof service._create, 'function');
});

test('._update', () => {
assert.strictEqual(typeof service._update, 'function');
});

test('._patch', () => {
assert.strictEqual(typeof service._patch, 'function');
});

test('._remove', () => {
assert.strictEqual(typeof service._remove, 'function');
});
});
});
};
Loading

0 comments on commit 17b3dc8

Please sign in to comment.