Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update feathers-service-tests to version 0.8.1 πŸš€ #124

Merged
merged 3 commits into from
Nov 6, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
"feathers": "^2.0.0",
"feathers-hooks": "^1.1.0",
"feathers-rest": "^1.2.2",
"feathers-service-tests": "^0.8.1",
"feathers-service-tests": "^0.8.2",
"feathers-socketio": "^1.3.3",
"istanbul": "^1.1.0-alpha.1",
"mocha": "^3.0.0",
Expand Down
20 changes: 7 additions & 13 deletions src/error-handler.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,26 @@
import errors from 'feathers-errors';

export default function errorHandler (error) {
let feathersError = error;

if (error.name) {
switch (error.name) {
case 'ValidationError':
case 'ValidatorError':
case 'CastError':
case 'VersionError':
feathersError = new errors.BadRequest(error);
break;
return Promise.reject(new errors.BadRequest(error));
case 'OverwriteModelError':
feathersError = new errors.Conflict(error);
break;
return Promise.reject(new errors.Conflict(error));
case 'MissingSchemaError':
case 'DivergentArrayError':
feathersError = new errors.GeneralError(error);
break;
return Promise.reject(new errors.GeneralError(error));
case 'MongoError':
if (error.code === 11000) {
feathersError = new errors.Conflict(error);
} else {
feathersError = new errors.GeneralError(error);
return Promise.reject(new errors.Conflict(error));
}
break;

return Promise.rejct(new errors.GeneralError(error));
}
}

return Promise.reject(feathersError);
return Promise.reject(error);
}
48 changes: 35 additions & 13 deletions src/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ class Service {
throw new Error('You must provide a Mongoose Model');
}

// this.name = options.name;
this.Model = options.Model;
this.id = options.id || '_id';
this.paginate = options.paginate || {};
this.lean = options.lean || false;
this.overwrite = options.overwrite !== false;
this.events = options.events || [];
}

extend (obj) {
Expand Down Expand Up @@ -134,6 +134,19 @@ class Service {
}

create (data) {
const convert = current => {
const result = Object.assign({}, current);
delete result[this.id];

return result;
};

if (Array.isArray(data)) {
data = data.map(convert);
} else {
data = convert(data);
}

return this.Model.create(data).catch(errorHandler);
}

Expand Down Expand Up @@ -177,7 +190,18 @@ class Service {
}

patch (id, data, params) {
params.query = params.query || {};
const query = params.query || {};
const patchQuery = {};

// Account for potentially modified data
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@daffl Can you elaborate or add a more detailed comment on what this is actually doing? I know it fixes something but I don't really understand what this is for. Is there a test that this refers to?

Copy link
Member

@daffl daffl Nov 6, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test is https://github.com/feathersjs/feathers-service-tests/blob/master/src/common-tests.js#L525. Basically if you did something like .patch(null, { name: 'Eric' }, { query: { name: 'David' } }) you didn't get events or the changed items. This is also not a complete fix but covers a fairly common case.There does not seem to be a way to get the actually changed items or at least the ids from MongoDB multi updates (or many other db adapters).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok cool. Thanks! I added some more detail to the comment for future reference.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the better fix is to make a find, run the update and then another find with the list of original ids via find({ _id: { $in: oldFindIds } }) after.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@daffl probably. That would be easier to trace and also the way I would normally do it in my own code. However, it might be more expensive an operation than just doing what you are doing in memory. Especially if patching a lot of objects. We'd almost need to test with 10k documents or something.

A common use case for patches like that are database migrations so large numbers would be common.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could add a flag for that case. But in order to get real-time events there isn't really a way around returning all changed items. I think it makes sense to change the adapters to what I suggested because then it'll at least return only the changed items (right now it returns everything that matches the query).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I didn't notice that. You're right. It is better to do that. At least then we are dispatching for the correct records. We can optimize for speed later (it might not be bad, it could just use some testing).

Object.keys(query).forEach(key => {
if (query[key] !== undefined && data[key] !== undefined &&
typeof data[key] !== 'object') {
patchQuery[key] = data[key];
} else {
patchQuery[key] = query[key];
}
});

// Handle case where data might be a mongoose model
if (typeof data.toObject === 'function') {
Expand All @@ -195,7 +219,7 @@ class Service {
}, params.mongoose);

if (id !== null) {
params.query[this.id] = id;
query[this.id] = id;
}

if (this.id === '_id') {
Expand All @@ -212,13 +236,11 @@ class Service {
try {
// If params.query.$populate was provided, remove it
// from the query sent to mongoose.
const query = omit(params.query, '$populate');

return this.Model
.update(query, data, options)
.update(omit(query, '$populate'), data, options)
.lean(this.lean)
.exec()
.then(() => this._getOrFind(id, params))
.then(() => this._getOrFind(id, { query: patchQuery }))
.catch(errorHandler);
} catch (e) {
return errorHandler(e);
Expand All @@ -235,12 +257,12 @@ class Service {
// NOTE (EK): First fetch the record(s) so that we can return
// it/them when we delete it/them.
return this._getOrFind(id, params)
.then(data => this.Model
.remove(query)
.lean(this.lean)
.exec()
.then(() => data)
.catch(errorHandler)
.then(data =>
this.Model
.remove(query)
.lean(this.lean)
.exec()
.then(() => data)
)
.catch(errorHandler);
}
Expand Down
56 changes: 33 additions & 23 deletions test/index.test.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
import { expect } from 'chai';
import { base, orm, example } from 'feathers-service-tests';
import { base, example } from 'feathers-service-tests';
import errors from 'feathers-errors';
import feathers from 'feathers';
import service, { hooks, Service } from '../src';
import server from './test-app';
import User from './models/user';
import Pet from './models/pet';
import { User, Pet, Peeps, CustomPeeps } from './models';

const _ids = {};
const _petIds = {};
const app = feathers().use('/people', service({ name: 'User', Model: User }))
.use('/pets', service({ name: 'Pet', Model: Pet }))
.use('/people2', service({ name: 'User', Model: User, lean: true }))
.use('/pets2', service({ name: 'Pet', Model: Pet, lean: true }));
const app = feathers()
.use('/peeps', service({ Model: Peeps, events: [ 'testing' ] }))
.use('/peeps-customid', service({
id: 'customid',
Model: CustomPeeps,
events: [ 'testing' ]
}))
.use('/people', service({ Model: User }))
.use('/pets', service({ Model: Pet }))
.use('/people2', service({ Model: User, lean: true }))
.use('/pets2', service({ Model: Pet, lean: true }));
const people = app.service('people');
const pets = app.service('pets');
const leanPeople = app.service('people2');
const leanPets = app.service('pets2');

let testApp;

describe('Feathers Mongoose Service', () => {
Expand Down Expand Up @@ -97,29 +104,28 @@ describe('Feathers Mongoose Service', () => {
});

describe('Common functionality', () => {
beforeEach((done) => {
beforeEach(() => {
// FIXME (EK): This is shit. We should be loading fixtures
// using the raw driver not our system under test
pets.create({type: 'dog', name: 'Rufus'}).then(pet => {
return pets.create({type: 'dog', name: 'Rufus'}).then(pet => {
_petIds.Rufus = pet._id;

return people.patch({ name: 'Doug', age: 32, pets: [pet._id] }).then(user => {
return people.create({
name: 'Doug',
age: 32,
pets: [pet._id]
}).then(user => {
_ids.Doug = user._id;
done();
});
});
});

afterEach(done => {
pets.remove(null, { query: {} }).then(() => {
return people.remove(null, { query: {} }).then(() => {
return done();
});
});
afterEach(() => {
return pets.remove(null, { query: {} }).then(() =>
people.remove(null, { query: {} })
);
});

base(app, errors);

it('can $populate with find', function (done) {
var params = {
query: {
Expand Down Expand Up @@ -289,8 +295,6 @@ describe('Feathers Mongoose Service', () => {
});
});

base(app, errors, 'people2');

it('can $populate with find', function (done) {
var params = {
query: {
Expand Down Expand Up @@ -319,8 +323,14 @@ describe('Feathers Mongoose Service', () => {
});
});

describe.skip('Mongoose service ORM errors', () => {
orm(people, _ids, errors);
describe('Common tests', () => {
before(() => Promise.all([
app.service('peeps').remove(null),
app.service('peeps-customid').remove(null)
]));

base(app, errors, 'peeps', '_id');
base(app, errors, 'peeps-customid', 'customid');
});

describe('Mongoose service example test', () => {
Expand Down
8 changes: 8 additions & 0 deletions test/models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import Pet from './pet';
import User from './user';
import Peeps from './peeps';
import CustomPeeps from './peeps-customid';

export default {
Pet, User, Peeps, CustomPeeps
};
17 changes: 17 additions & 0 deletions test/models/peeps-customid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import mongoose from 'mongoose';
const Schema = mongoose.Schema;

const PeepsSchema = new Schema({
customid: {
type: Schema.Types.ObjectId,
default: function () {
return new mongoose.Types.ObjectId();
}
},
name: { type: String, required: true },
age: { type: Number },
created: {type: Boolean, 'default': false},
time: {type: Number}
});

export default mongoose.model('PeepsCustomid', PeepsSchema);
11 changes: 11 additions & 0 deletions test/models/peeps.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import mongoose from 'mongoose';
const Schema = mongoose.Schema;

const PeepsSchema = new Schema({
name: { type: String, required: true },
age: { type: Number },
created: {type: Boolean, 'default': false},
time: {type: Number}
});

export default mongoose.model('Peeps', PeepsSchema);
7 changes: 5 additions & 2 deletions test/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ const negativeAgeValidator = function () {
};

const UserSchema = new Schema({
name: {type: String, required: true},
age: {type: Number, validate: [negativeAgeValidator, 'Age couldn\'t be negative']},
name: { type: String, required: true },
age: {
type: Number,
validate: [negativeAgeValidator, 'Age couldn\'t be negative']
},
created: {type: Boolean, 'default': false},
time: {type: Number},
pets: [{type: Schema.ObjectId, ref: 'Pet'}]
Expand Down