Skip to content

Commit

Permalink
fix: shall re-throw errors on first connect (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
legendecas authored and popomore committed Apr 28, 2018
1 parent b281b15 commit dde9037
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/mongoose.js
Expand Up @@ -3,7 +3,7 @@
const assert = require('assert');
const path = require('path');
const mongoose = require('mongoose');
const awaitEvent = require('await-event');
const awaitFirst = require('await-first');

let count = 0;

Expand Down Expand Up @@ -76,7 +76,7 @@ function createOneClient(config, app) {

app.beforeStart(function* () {
app.coreLogger.info('[egg-mongoose] starting...');
yield awaitEvent(db, 'connected');
yield awaitFirst(db, [ 'connected', 'error' ]);
const index = count++;
/*
*remove heartbeat to avoid no authentication
Expand Down
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -13,7 +13,7 @@
"egg-plugin"
],
"dependencies": {
"await-event": "^2.0.0",
"await-first": "^1.0.0",
"mongoose": "^4.8.6"
},
"devDependencies": {
Expand Down
53 changes: 53 additions & 0 deletions test/mongoose.test.js
Expand Up @@ -3,6 +3,8 @@
const assert = require('assert');
const request = require('supertest');
const mm = require('egg-mock');
const mongoose = require('mongoose');
const EventEmitter = require('events');

describe('test/mongoose.test.js', () => {
describe('base', () => {
Expand Down Expand Up @@ -201,4 +203,55 @@ describe('test/mongoose.test.js', () => {
assert(app.model.Other === undefined);
});
});

describe('throws on first connection', () => {
let app;
const createConnection = mongoose.createConnection;
let connection;
let onCreateConnection;
beforeEach(function* () {
connection = new EventEmitter();
mongoose.createConnection = () => {
setTimeout(onCreateConnection, 10);
return connection;
};
});

afterEach(function* () {
yield app.close();
});
afterEach(mm.restore);
afterEach(() => {
connection = null;
onCreateConnection = null;
mongoose.createConnection = createConnection;
});

it('should establish first connection', function* () {
app = mm.app({
baseDir: 'apps/mongoose',
});
onCreateConnection = () => {
connection.emit('connected');
};
yield app.ready();
});

it('should rethrow on first connection', function* () {
app = mm.app({
baseDir: 'apps/mongoose',
});
onCreateConnection = () => {
connection.emit('error', new Error('foobar'));
};
try {
yield app.ready();
} catch (err) {
assert(err != null);
assert(err.message === '[egg-mongoose]foobar');
return;
}
assert.fail('shall not succeeded');
});
});
});

0 comments on commit dde9037

Please sign in to comment.