diff --git a/build-flow.sh b/build-flow.sh new file mode 100644 index 0000000..3f3c97f --- /dev/null +++ b/build-flow.sh @@ -0,0 +1,2 @@ +#!/bin/bash +find ./src -name '*.js' -not -path '*/__*' | while read filepath; do cp $filepath `echo $filepath | sed 's/\\/src\\//\\/lib\\//g'`.flow; done \ No newline at end of file diff --git a/build-ts.sh b/build-ts.sh new file mode 100644 index 0000000..94d98b8 --- /dev/null +++ b/build-ts.sh @@ -0,0 +1,2 @@ +#!/bin/bash +find ./src -name '*.d.ts' -not -path '*/__*' | while read filepath; do cp $filepath `echo $filepath | sed 's/\\/src\\//\\/lib\\//g'`; done \ No newline at end of file diff --git a/package.json b/package.json index ddb6a08..b193f32 100644 --- a/package.json +++ b/package.json @@ -64,10 +64,12 @@ ] }, "scripts": { - "build": "npm run build-cjs && npm run build-flow && npm run build-ts", + "build": "npm run build-cjs && npm run build-flow-sh && npm run build-ts-sh", "build-cjs": "rimraf lib && babel src --ignore __tests__,__mocks__ -d lib", "build-flow": "find ./src -name '*.js' -not -path '*/__*' | while read filepath; do cp $filepath `echo $filepath | sed 's/\\/src\\//\\/lib\\//g'`.flow; done", + "build-flow-sh": "sh build-flow.sh", "build-ts": "find ./src -name '*.d.ts' -not -path '*/__*' | while read filepath; do cp $filepath `echo $filepath | sed 's/\\/src\\//\\/lib\\//g'`; done", + "build-ts-sh": "sh build-ts.sh", "watch": "jest --watch", "coverage": "jest --coverage --maxWorkers 2", "lint": "npm run eslint && npm run tslint && npm run tscheck", diff --git a/src/index.js b/src/index.js index 3aa9f49..c3cb70e 100755 --- a/src/index.js +++ b/src/index.js @@ -114,7 +114,22 @@ async function createCounterIfNotExist( count: settings.startAt - settings.incrementBy, }): any); - await existedCounter.save(); + try { + // this might fail if invoked in parallel + await existedCounter.save(); + } catch (e) { + if (isMongoDuplicateError(e)) { + // just to be consistent with the method return type + // but to tell the truth it could return boolean at this point + existedCounter = (await IC.findOne({ + model: settings.model, + field: settings.field, + groupingField, + }).exec(): any); + } else { + throw e; // other unhandled errors + } + } } return (existedCounter: any); @@ -177,7 +192,7 @@ async function preSave( doc.set(settings.field, count); // $FlowFixMe - doc.__maiRanOnce = true; // eslint-disable-line + doc.__maiRanOnce = true; // eslint-disable-line } next();