Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nodkz committed May 11, 2017
0 parents commit 964432e
Show file tree
Hide file tree
Showing 13 changed files with 4,952 additions and 0 deletions.
14 changes: 14 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"presets": [
["env", {
"targets": {
"node": 4
},
}]
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties",
"transform-flow-strip-types"
]
}
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
flow-typed
35 changes: 35 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"extends": [
"airbnb-base",
"prettier"
],
"parser": "babel-eslint",
"rules": {
"no-underscore-dangle": 0,
"arrow-body-style": 0,
"no-unused-expressions": 0,
"no-plusplus": 0,
"no-console": 0,
"func-names": 0,
"comma-dangle": ["error", {
"arrays": "always-multiline",
"objects": "always-multiline",
"imports": "always-multiline",
"exports": "always-multiline",
"functions": "ignore",
}],
"prettier/prettier": ["error", {
"trailingComma": true,
"singleQuote": true,
"printWidth": 100
}]
},
"env": {
"jasmine": true,
"jest": true
},
"plugins": [
"flowtype",
"prettier"
]
}
8 changes: 8 additions & 0 deletions .flowconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[ignore]
.*/node_modules/.*

[include]

[libs]

[options]
46 changes: 46 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov


# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# IntelliJ Files
*.iml
*.ipr
*.iws
/out/
.idea/
.idea_modules/

# Dependency directory
node_modules

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

# Transpiled code
/es
/lib

coverage
.nyc_output
4 changes: 4 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.DS_Store
*.log
src
flow-typed
25 changes: 25 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
sudo: false
language: node_js
cache:
yarn: true
directories:
- node_modules
notifications:
email: true
node_js:
- "7"
# - "6"
# - "5"
# - "4"
script:
# - yarn run coverage
- yarn run build
after_success:
- 'curl -Lo travis_after_all.py https://git.io/travis_after_all'
- python travis_after_all.py
- export $(cat .to_export_back) &> /dev/null
# - if [[ "$TRAVIS_JOB_NUMBER" == *.1 && "$TRAVIS_BRANCH" == "master" && "$TRAVIS_PULL_REQUEST" == "false" ]]; then bash <(curl -s https://codecov.io/bash); fi
- if [[ "$TRAVIS_JOB_NUMBER" == *.1 && "$TRAVIS_BRANCH" == "master" && "$TRAVIS_PULL_REQUEST" == "false" ]]; then npm run semantic-release; fi
branches:
except:
- /^v\d+\.\d+\.\d+$/
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@



## 0.0.1 (May 11, 2017)
- First commit
9 changes: 9 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2017-present Pavel Chertorogov

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.
178 changes: 178 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
# mongodb-memory-server

[![NPM version](https://img.shields.io/npm/v/mongodb-memory-server.svg)](https://www.npmjs.com/package/mongodb-memory-server)
[![Downloads stat](https://img.shields.io/npm/dt/mongodb-memory-server.svg)](http://www.npmtrends.com/mongodb-memory-server)
[![Travis](https://img.shields.io/travis/nodkz/mongodb-memory-server.svg?maxAge=2592000)](https://travis-ci.org/nodkz/mongodb-memory-server)
[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)

This package spins up a actual/real MongoDB Server programmatically from node for testing or mocking during development. By default it holds the data in memory. Fresh spinned up `mongod` process takes about 7Mb of memory. The server will allow you to connect your favorite ODM or client library to the MongoDB Server and run integration tests isolated from each other. You can start up several mongod simultaneously, it automatically discovers free ports.

This package use [mongodb-prebuilt](https://github.com/winfinit/mongodb-prebuilt) which on first start downloads the latest MongoDB binaries and save it to `~/.mongodb-prebuilt` folder. So first run may take a time. All further runs will use downloaded version.

## Installation
```
yarn add mongodb-memory-server --dev
OR
npm install mongodb-memory-server --save-dev
```

## Usage

### Simple server start:
```js
import MongodbMemoryServer from 'mongodb-memory-server';

const mongod = new MongoMemoryServer();

const uri = await mongod.getConnectionString();
const port = await mongod.getPort();
const dbPath = await mongod.getDbPath();

mongod.stop();
```

### Provide connection string to mongoose
```js
import mongoose from 'mongoose';
import MongodbMemoryServer from 'mongodb-memory-server';

const mongoServer = new MongoMemoryServer();

mongoose.Promise = Promise;
mongoServer.getConnectionString().then((mongoUri) => {
const mongooseOpts = {
server: {
auto_reconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
},
};

mongoose.connect(mongoUri, mongooseOpts);

mongoose.connection.on('error', (e) => {
if (e.message.code === 'ETIMEDOUT') {
console.log(e);
mongoose.connect(mongoUri, mongooseOpts);
}
console.log(e);
});

mongoose.connection.once('open', () => {
console.log(`MongoDB successfully connected to ${mongoUri}`);
});
});
```
For additional information I recommend you to read this article [Testing a GraphQL Server using Jest with Mongoose](https://medium.com/entria/testing-a-graphql-server-using-jest-4e00d0e4980e)


### Several mongoose connections simultaneously
```js
import mongoose from 'mongoose';
import MongodbMemoryServer from 'mongodb-memory-server';

mongoose.Promise = Promise;

const mongoServer1 = new MongoMemoryServer();
const mongoServer2 = new MongoMemoryServer();

const mongooseOpts = {
server: {
promiseLibrary = Promise;
auto_reconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
},
};

function addEvents(connection, mongoUri) {
connection.on('error', (e) => {
if (e.message.code === 'ETIMEDOUT') {
console.log(e);
connect(mongoUri, mongooseOpts);
}
console.log(e);
});

connection.once('open', () => {
console.log(`MongoDB successfully connected to ${mongoUri}`);
});
}

// Firstly create connection objects, which you may import in other files and create mongoose models.
// Connection to databases will be estimated later (after model creation).
const connections = {
conn1: mongoose.createConnection(),
conn2: mongoose.createConnection(),
conn3: mongoose.createConnection(),
};

mongoServer1.getConnectionString('server1_db1').then((mongoUri) => {
connections.conn1.connect(mongoUri, mongooseOpts);
addEvents(connections.conn1, mongoUri);
});

mongoServer1.getConnectionString('server1_db2').then((mongoUri) => {
connections.conn2.connect(mongoUri, mongooseOpts);
addEvents(connections.conn2, mongoUri);
});

mongoServer2.getConnectionString('server2_db').then((mongoUri) => {
connections.conn3.connect(mongoUri, mongooseOpts);
addEvents(connections.conn3, mongoUri);
});

export default connections;


// somewhere in other file
import { Schema } from 'mongoose';
import { conn1, conn2, conn3 } from './file_above';

const userSchema = new Schema({
name: String,
});

const taskSchema = new Schema({
userId: String,
task: String,
});

export default {
User: conn1.model('user', userSchema),
Task: conn2.model('task', taskSchema),
UserOnServer2: conn3.model('user', userSchema),
}
```

### Simple Mocha test example
```js
import mongoose from 'mongoose';
import MongodbMemoryServer from 'mongodb-memory-server';

before(function(done) {
const mongoServer = new MongodbMemoryServer();
mongoServer.getConnectionString().then((mongoUri) => {
mongoose.connect(mongoUri, function(err) {
done(err);
});
});
});

describe('...', function() {
it("...", function() {
// ...
});
});

```


## Credits
Inspired by alternative runners for [mongodb-prebuilt](https://github.com/winfinit/mongodb-prebuilt):
- [mockgoose](https://github.com/mockgoose/Mockgoose)
- [mongomem](https://github.com/CImrie/mongomem)

## License

MIT
Loading

0 comments on commit 964432e

Please sign in to comment.