Skip to content
This repository was archived by the owner on Apr 19, 2020. It is now read-only.

Commit f6ea95d

Browse files
committed
Refactor config parsing
1 parent 2c848e4 commit f6ea95d

File tree

6 files changed

+161
-145
lines changed

6 files changed

+161
-145
lines changed

README.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,17 @@ npm install --save @synor/database-mongodb
2020

2121
## URI
2222

23-
**Format**: `mongodb://[user[:password]@][hostname][:port]/database[?param=value&...]`
23+
**Format**: `mongodb[+srv]://[username:password@]hostname[:port]/database[?param=value&...]`
2424

2525
**Params**:
2626

27-
| Name | Description | Default Value |
28-
| ------------------------------ | ------------------------------- | ------------------------ |
29-
| `synor_migration_record_table` | Name for Migration Record Table | `synor_migration_record` |
27+
| Name | Description | Default Value |
28+
| ----------------------------------- | ------------------------------------ | ------------------------ |
29+
| `synor_migration_record_collection` | Name for Migration Record Collection | `synor_migration_record` |
3030

3131
**Examples**:
3232

33-
- `mongodb://root:root@127.0.0.1:27017/synor?synor_migration_record_table=migration_record`
33+
- `mongodb://mongo:mongo@127.0.0.1:27017/synor?synor_migration_record_collection=migration_record`
3434

3535
## License
3636

package.json

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,39 +29,39 @@
2929
"watch": "bili --format cjs --watch"
3030
},
3131
"dependencies": {
32-
"connection-string": "^3.1.1",
32+
"connection-string": "^3.1.3",
3333
"debug": "^4.1.1",
34-
"mongodb": "^3.5.3"
34+
"mongodb": "^3.5.4"
3535
},
3636
"devDependencies": {
37-
"@synor/core": "^0.9.1",
37+
"@synor/core": "^0.9.2",
3838
"@synor/eslint-config": "^0.1.0",
3939
"@types/debug": "^4.1.5",
4040
"@types/jest": "^25.1.2",
41-
"@types/mongodb": "^3.3.16",
42-
"@typescript-eslint/eslint-plugin": "^2.19.0",
43-
"@typescript-eslint/parser": "^2.19.0",
41+
"@types/mongodb": "^3.5.2",
42+
"@typescript-eslint/eslint-plugin": "^2.22.0",
43+
"@typescript-eslint/parser": "^2.22.0",
4444
"bili": "^4.8.1",
4545
"eslint": "^6.8.0",
4646
"eslint-config-prettier": "^6.10.0",
4747
"eslint-config-standard-with-typescript": "^14.0.0",
4848
"eslint-plugin-import": "^2.20.1",
49-
"eslint-plugin-jest": "^23.7.0",
49+
"eslint-plugin-jest": "^23.8.2",
5050
"eslint-plugin-node": "^11.0.0",
5151
"eslint-plugin-prettier": "^3.1.2",
5252
"eslint-plugin-promise": "^4.2.1",
5353
"eslint-plugin-standard": "^4.0.1",
5454
"husky": "^4.2.1",
5555
"jest": "^25.1.0",
56-
"lint-staged": "^10.0.7",
56+
"lint-staged": "^10.0.8",
5757
"prettier": "^1.19.1",
5858
"pretty-quick": "^2.0.1",
5959
"rimraf": "^3.0.2",
60-
"rollup-plugin-typescript2": "^0.25.3",
61-
"typescript": "^3.8.2"
60+
"rollup-plugin-typescript2": "^0.26.0",
61+
"typescript": "^3.8.3"
6262
},
6363
"peerDependencies": {
64-
"@synor/core": "^0.9.1"
64+
"@synor/core": "^0.9.2"
6565
},
6666
"publishConfig": {
6767
"access": "public"

src/index.ts

Lines changed: 16 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { MigrationRecord, SynorError } from '@synor/core';
2-
import { ConnectionString } from 'connection-string';
32
import Debug from 'debug';
43
import { Db, MongoClient } from 'mongodb';
54
import { performance } from 'perf_hooks';
5+
import { getConfig } from './utils/get-config';
66

77
type DatabaseEngine = import('@synor/core').DatabaseEngine;
88
type DatabaseEngineFactory = import('@synor/core').DatabaseEngineFactory;
@@ -15,50 +15,6 @@ async function noOp(): Promise<null> {
1515
return null;
1616
}
1717

18-
function parseConnectionString(
19-
cn: string
20-
): {
21-
protocol: string;
22-
host: string;
23-
port: number | undefined;
24-
path: string[];
25-
params: Record<string, any>;
26-
database: string;
27-
migrationRecordTable: string;
28-
} {
29-
debug(cn);
30-
const { protocol, hostname: host, port, path, params } = new ConnectionString(
31-
cn,
32-
{
33-
params: {
34-
synor_migration_record_table: 'synor_migration_record'
35-
}
36-
}
37-
);
38-
39-
debug('host ', host);
40-
debug('port ', port);
41-
debug('protocol ', protocol);
42-
debug('path ', path);
43-
debug('params ', params);
44-
45-
if (!host || !protocol || !path || !params) {
46-
throw new SynorError('Invalid connection uri');
47-
}
48-
const database = path?.[0];
49-
const migrationRecordTable = params.synor_migration_record_table;
50-
51-
return {
52-
database,
53-
host,
54-
protocol,
55-
port,
56-
path,
57-
params,
58-
migrationRecordTable
59-
};
60-
}
61-
6218
async function doesMigrationRecordTableExists(
6319
db: Db,
6420
mgCollName: string
@@ -150,19 +106,22 @@ export const MongoDBDatabaseEngine: DatabaseEngineFactory = (
150106
throw new SynorError(`Missing: getUserInfo`);
151107
}
152108

153-
const { database, migrationRecordTable } = parseConnectionString(uri);
109+
const { databaseConfig, engineConfig } = getConfig(uri);
154110

155111
let client: MongoClient | null = null;
156112
let db: Db | null = null;
157113

158114
return {
159115
async open() {
160116
debug('in open function');
161-
client = await MongoClient.connect(uri);
162-
db = await client.db(database);
117+
client = await MongoClient.connect(uri, {
118+
appname: databaseConfig.appname,
119+
poolSize: 1
120+
});
121+
db = await client.db();
163122
await ensureMigrationRecordTableExists(
164123
db,
165-
migrationRecordTable,
124+
engineConfig.migrationRecordCollection,
166125
baseVersion
167126
);
168127
},
@@ -229,9 +188,9 @@ export const MongoDBDatabaseEngine: DatabaseEngineFactory = (
229188
const endTime = performance.now();
230189
const newRecordId = await findNextAutoIncrementedId(
231190
db as Db,
232-
migrationRecordTable
191+
engineConfig.migrationRecordCollection
233192
);
234-
await db?.collection(migrationRecordTable).insert({
193+
await db?.collection(engineConfig.migrationRecordCollection).insert({
235194
id: newRecordId,
236195
version,
237196
type,
@@ -249,10 +208,13 @@ export const MongoDBDatabaseEngine: DatabaseEngineFactory = (
249208
if (!db) {
250209
throw new SynorError('Database connection is null');
251210
}
252-
await deleteDirtyRecords(db, migrationRecordTable);
211+
await deleteDirtyRecords(db, engineConfig.migrationRecordCollection);
253212

254213
for (const { id, hash } of records) {
255-
await updateRecord(db, migrationRecordTable, { id, hash });
214+
await updateRecord(db, engineConfig.migrationRecordCollection, {
215+
id,
216+
hash
217+
});
256218
}
257219
},
258220
async records(startid: number) {
@@ -262,7 +224,7 @@ export const MongoDBDatabaseEngine: DatabaseEngineFactory = (
262224
}
263225

264226
const records = (await (
265-
await db.collection(migrationRecordTable).find({
227+
await db.collection(engineConfig.migrationRecordCollection).find({
266228
id: {
267229
$gte: startid
268230
}

src/utils/get-config.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { SynorError } from '@synor/core';
2+
import { ConnectionString } from 'connection-string';
3+
4+
type MongoClientOptions = import('mongodb').MongoClientOptions;
5+
6+
type MongoDBDatabaseConfig = Required<Pick<MongoClientOptions, 'appname'>>;
7+
8+
type MongoDBEngineConfig = {
9+
migrationRecordCollection: string;
10+
};
11+
12+
const validProtocol = ['mongodb', 'mongodb+srv'];
13+
14+
export function getConfig(
15+
uri: string
16+
): {
17+
databaseConfig: MongoDBDatabaseConfig;
18+
engineConfig: MongoDBEngineConfig;
19+
} {
20+
try {
21+
const { protocol, hostname: host, path, params } = new ConnectionString(
22+
uri,
23+
{
24+
params: {
25+
appname: '@synor/database-mongodb',
26+
synor_migration_record_collection: 'synor_migration_record'
27+
}
28+
}
29+
);
30+
31+
if (!protocol) {
32+
throw new Error(`[URI] missing: protocol!`);
33+
}
34+
35+
if (!validProtocol.includes(protocol)) {
36+
throw new Error(`[URI] unsupported: protocol(${protocol})!`);
37+
}
38+
39+
if (!host) {
40+
throw new Error(`[URI] missing: host!`);
41+
}
42+
43+
const database = path?.[0];
44+
45+
if (!database) {
46+
throw new Error('[URI] missing: database!');
47+
}
48+
49+
const databaseConfig: MongoDBDatabaseConfig = {
50+
appname: params!.appname
51+
};
52+
53+
const engineConfig: MongoDBEngineConfig = {
54+
migrationRecordCollection: params!.synor_migration_record_collection
55+
};
56+
57+
return {
58+
databaseConfig,
59+
engineConfig
60+
};
61+
} catch (error) {
62+
throw new SynorError('Invalid DatabaseURI', 'exception', error);
63+
}
64+
}

tsconfig.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
/* Basic Options */
44
// "incremental": true, /* Enable incremental compilation */
55
"target": "ES2019" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
6-
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
6+
"module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
77
// "lib": [], /* Specify library files to be included in the compilation. */
88
// "allowJs": true, /* Allow javascript files to be compiled. */
99
// "checkJs": true, /* Report errors in .js files. */
@@ -17,7 +17,7 @@
1717
// "composite": true, /* Enable project compilation */
1818
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
1919
// "removeComments": true, /* Do not emit comments to output. */
20-
// "noEmit": true /* Do not emit outputs. */,
20+
"noEmit": true /* Do not emit outputs. */,
2121
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
2222
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
2323
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

0 commit comments

Comments
 (0)