Skip to content

Commit

Permalink
feat: support options
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Jul 6, 2021
1 parent a2470d9 commit 77242a1
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 24 deletions.
30 changes: 20 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
# 🥭 mongoz

> Ad hoc MongoDB server for Node.js
> Zero Config MongoDB Server for Node.js
## Why?

[MongoDB](https://www.mongodb.com) is fantastic but setup for small projects can be lots of trouble.

This little package does everything necessary to download and start a fresh mongo server!
This little package does everything necessary to download and start a fresh MongoDB server!

## Usage

**Note:** You need to have [Node.js](https://nodejs.org/en/) and [npm](https://docs.npmjs.com/cli/v7/commands/npm) already installed!

**Note:** Make sure there is not already a local mongodb server listening on default port (`2701`). If you do, either stop it or use `PORT` environment variable to change the port.
**Note:** Make sure there is not already a local mongodb server listening on default port (`2701`). If you do, either stop it or use `MONGO_PORT` environment variable to change the port.

### Standalone Server

Let's start a fresh mongoz shall we?
Let's start a fresh db shall we?

```sh
npx mongoz
```

It will take few seconds on first time of usage to install and extract mongo server.

### Programmatic Usage
### Programmatic usage

Do you need a MongoDB server? No problems!
Do you need a MongoDB server programmatically? No problems!

```js
// CommonJS
Expand All @@ -37,15 +37,25 @@ import { startMongo } from 'mongoz'

// Install and start listening MongoDB on 127.0.0.1:27017 in background
await startMongo()

// Or with options
await startMongo({ port: 27018 })
```

When closing server, mongo will also gracefully shutdown with [node-graceful-shutdown](https://www.npmjs.com/package/node-graceful-shutdown).

### In parallel with server
#### Options

- `name`: Unique instance name. Default is `default` (env var: `MONGO_NAME`)
- `dir`: Data directory to store logs and data. Default is `${os.tmpDir}/mongo`. (env var: `MONGO_DIR`)
- `port`: Listening port. Default is `27017` (env var: `MONGO_PORT` or `PORT`)
- `platform`: OS to download binraries for.

### In parallel with script

You can also use [concurrently](https://www.npmjs.com/package/concurrently) to start mongo alongside with server:
You can also use [concurrently](https://www.npmjs.com/package/concurrently) to start mongo alongside with server:.

`package.json`:
Via `package.json`:

```json
{
Expand All @@ -63,7 +73,7 @@ npx concurrently 'npx mongoz' 'node ./server.mjs'

## Supported platforms

Windows, Linux and Darwin (Mac) are supported. Check [formula](./src/formula) for details.
Windows, Linux and Darwin (Mac) are supported. Check [formula](./src/formula.ts) for details.

## Changing data dir

Expand Down
46 changes: 32 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,45 @@ import fsExtra from 'fs-extra'
import download from 'download'
import consola from 'consola'
import decompress from 'decompress'
import execa from 'execa'
import execa, { ExecaChildProcess } from 'execa'
import ora from 'ora'
import { onShutdown } from 'node-graceful-shutdown'
import { mongoFormula as formula } from './formula'

export async function startMongo (opts = { args: null }) {
const platformName = process.platform
let platform = formula.platforms.find(p => p.name === platformName)
if (!platform) {
throw new Error(`Platform '${platformName}' is not available for '${formula.name}'`)
export interface MongoOptions {
name?: string
platform?: string
dir?: string
port?: string | number
args?: string[]
}

export interface MongoService {
server: ExecaChildProcess
close: () => Promise<void>
}

export async function startMongo(opts: MongoOptions): MongoService {
// Apply defaults
opts = {
name: process.env.MONGO_NAME || 'default',
port: process.env.MONGO_PORT || process.env.PORT || formula.port,
platform: process.env.MONGO_PLATFORM || process.platform,
dir: process.env.MONGO_DIR || path.resolve(os.tmpdir(), 'mongo'),
...opts
}

const instanceName = 'default'
const appDir = process.env.MONGO_DIR || path.resolve(os.tmpdir(), formula.name)
// Find platform
const platform = formula.platforms.find(p => p.name === opts.platform)
if (!platform) {
throw new Error(`Platform '${opts.platform}' is not available for '${formula.name}'`)
}

// Resolve paths
const dataDir = path.resolve(appDir, 'data', instanceName, formula.name)
const logsDir = path.resolve(appDir, 'logs', instanceName, formula.name)
const dataDir = path.resolve(opts.dir, 'data', opts.name, formula.name)
const logsDir = path.resolve(opts.dir, 'logs', opts.name, formula.name)
const logFile = path.resolve(logsDir, 'logs.txt')
const sourceDir = path.resolve(appDir, 'source', formula.name, formula.version, platform.name)
const sourceDir = path.resolve(opts.dir, 'source', formula.name, formula.version, platform.name)
const sourceFileName = `${formula.name}-${formula.version}-${platform.name}` + path.extname(platform.source)
const sourceFile = path.resolve(sourceDir, sourceFileName)
const extractDir = path.resolve(sourceDir, 'unpacked')
Expand Down Expand Up @@ -60,14 +79,13 @@ export async function startMongo (opts = { args: null }) {
consola.info(`Writing logs to: ${logFile}`)

// Port and args
const port = process.env.PORT || formula.port
const execArgs = formula.execArgs.replace('{port}', port + '').replace('{data}', dataDir).split(' ')
const execArgs = formula.execArgs.replace('{port}', opts.port + '').replace('{data}', dataDir).split(' ')
if (Array.isArray(opts.args)) {
execArgs.push(...opts.args)
}

// Start app
spinner.info(`Starting ${formula.name} at port ${port}`)
spinner.info(`Starting ${formula.name} at port ${opts.port}`)
const server = execa(execFile, execArgs, {
stdout,
stderr
Expand Down

0 comments on commit 77242a1

Please sign in to comment.