diff --git a/.ci/test-cluster.yml b/.ci/test-cluster.yml index fae78c3c8a..912f23077d 100644 --- a/.ci/test-cluster.yml +++ b/.ci/test-cluster.yml @@ -52,8 +52,8 @@ services: <<: *kuzzle-config container_name: kuzzle_node_1 ports: - - "17510:7512" # Kuzzle API port, used to check if it is up - - "1883:1883" # TCP load balancing is hard with nginx + - "17510:7512" + - "1883:1883" kuzzle_node_2: <<: *kuzzle-config diff --git a/.eslintrc.json b/.eslintrc.json index 14186574bb..a3229fee13 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,4 +1,13 @@ { - "plugins": ["kuzzle"], - "extends": ["plugin:kuzzle/default", "plugin:kuzzle/node"] -} + "plugins": [ + "kuzzle" + ], + "extends": [ + "plugin:kuzzle/default", + "plugin:kuzzle/node" + ], + "rules": { + "sort-keys": "warn", + "kuzzle/array-foreach": "warn" + } +} \ No newline at end of file diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index e124fa7729..23bc12e6bd 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -11,7 +11,7 @@ on: jobs: analyze: name: Analyze - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 permissions: actions: read contents: read diff --git a/.github/workflows/core-dev.workflow.yml b/.github/workflows/core-dev.workflow.yml new file mode 100644 index 0000000000..15f68ab919 --- /dev/null +++ b/.github/workflows/core-dev.workflow.yml @@ -0,0 +1,38 @@ +name: kuzzleio/core-dev + +on: + push: + branches: + - master + +env: + DOCKER_PLATFORMS: "linux/amd64,linux/arm64,linux/arm/v7" + +jobs: + build-and-push: + name: Build and push core-dev image + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + id: buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + - name: Build and push + uses: docker/build-push-action@v2 + with: + context: ./core-dev + file: ./core-dev/Dockerfile + push: true + platforms: ${{ env.DOCKER_PLATFORMS }} + tags: kuzzleio/core-dev:2,kuzzleio/core-dev:latest diff --git a/.github/workflows/elasticsearch.workflow.yml b/.github/workflows/elasticsearch.workflow.yml new file mode 100644 index 0000000000..ce5c466880 --- /dev/null +++ b/.github/workflows/elasticsearch.workflow.yml @@ -0,0 +1,40 @@ +name: kuzzleio/elasticsearch + +on: + push: + branches: + - master + +env: + DOCKER_PLATFORMS: "linux/amd64,linux/arm64" + ELASTICSEARCH_VERSION: "7.16.2" + +jobs: + build-and-push: + name: Build and push elasticsearch image + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + id: buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + - name: Build and push + uses: docker/build-push-action@v2 + with: + context: ./elasticsearch + file: ./elasticsearch/Dockerfile + push: true + build-args: ELASTICSEARCH_VERSION=${{ env.ELASTICSEARCH_VERSION }} + platforms: ${{ env.DOCKER_PLATFORMS }} + tags: kuzzleio/elasticsearch:${{ env.ELASTICSEARCH_VERSION }},kuzzleio/elasticsearch:7, kuzzleio/elasticsearch:latest diff --git a/.github/workflows/kuzzle-runner.workflow.yml b/.github/workflows/kuzzle-runner.workflow.yml new file mode 100644 index 0000000000..f5c364e4aa --- /dev/null +++ b/.github/workflows/kuzzle-runner.workflow.yml @@ -0,0 +1,41 @@ +name: kuzzleio/kuzzle-runner + +on: + push: + branches: + - master + +env: + DOCKER_PLATFORMS: "linux/amd64,linux/arm64,linux/arm/v7" + +jobs: + publish-runner: + name: Build and push image embedding Node.js + runs-on: ubuntu-22.04 + matrix: + node-version: [16, 18, 20] + steps: + - uses: actions/checkout@v3 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + id: buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + - name: Build and push + uses: docker/build-push-action@v3 + with: + context: ./kuzzle-runner + file: ./kuzzle-runner/Dockerfile + push: true + build-args: NODE_LTS_VERSION=${{ matrix.node-version }} + platforms: ${{ env.DOCKER_PLATFORMS }} + tags: kuzzleio/kuzzle-runner:${{ matrix.node-version }} \ No newline at end of file diff --git a/.github/workflows/workflow-deployments.yaml b/.github/workflows/workflow-deployments.yaml index 036b82f08d..88e0a04e7f 100644 --- a/.github/workflows/workflow-deployments.yaml +++ b/.github/workflows/workflow-deployments.yaml @@ -4,20 +4,23 @@ on: workflow_call: inputs: node_lts_maintenance_version: - description: "Current Node LTS Version" + description: "Maintenance Node LTS Version" required: true default: "16" type: string - node_lts_current_version: - description: "Current Node LTS Version" - required: true - default: "20" - type: string + node_lts_active_version: description: "Active Node LTS Version" required: true default: "18" type: string + + node_lts_current_version: + description: "Current Node LTS Version" + required: true + default: "20" + type: string + docker_platforms: description: "Docker platforms" required: true @@ -30,31 +33,37 @@ on: required: true default: true type: boolean + dockerhub_deploy: description: "Deploy to DockerHub" required: true default: true type: boolean + npm_deploy: description: "Deploy to NPM" required: true default: true type: boolean + node_lts_maintenance_version: - description: "Current Node LTS Version" + description: "Maintenance Node LTS Version" required: true default: "16" type: string - node_lts_current_version: - description: "Current Node LTS Version" - required: true - default: "20" - type: string + node_lts_active_version: description: "Active Node LTS Version" required: true default: "18" type: string + + node_lts_current_version: + description: "Current Node LTS Version" + required: true + default: "20" + type: string + docker_platforms: description: "Docker platforms" required: true @@ -68,18 +77,20 @@ jobs: doc-deploy: name: Documentation - Deploy if: ${{ (github.event_name != 'workflow_dispatch' || inputs.doc_deploy) && (github.ref_name == 'master' || github.ref_name == '2-dev') }} - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 + - name: Checkout project + uses: actions/checkout@v3 + - name: Extract references from context shell: bash id: extract-refs run: | - echo "::set-output name=version::$(git describe --abbrev=0 --tags | cut -d. -f 1)" - echo "::set-output name=repo::$(echo $GITHUB_REPOSITORY | cut -d/ -f 2)" - - uses: convictional/trigger-workflow-and-wait@v1.6.3 + echo "version=$(git describe --abbrev=0 --tags | cut -d. -f 1)" >> $GITHUB_OUTPUT + echo "repo=$(echo $GITHUB_REPOSITORY | cut -d/ -f 2)" >> $GITHUB_OUTPUT + + - name: Trigger documentation workflow + uses: convictional/trigger-workflow-and-wait@v1.6.3 with: owner: kuzzleio repo: documentation @@ -91,37 +102,45 @@ jobs: dockerhub-deploy: name: Build and deploy images to Dockerhub if: ${{ (github.event_name != 'workflow_dispatch' || inputs.dockerhub_deploy) && github.ref_name == 'master' }} - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 - - uses: ./.github/actions/install-packages - - uses: actions/setup-node@v3 - with: - node-version: ${{ inputs.node_lts_maintenance_version }} - - uses: actions/cache@v3 + - name: Checkout project + uses: actions/checkout@v3 + + - name: Install additional libraries + uses: ./.github/actions/install-packages + + - name: Node version ${{ inputs.node_lts_active_version }} + uses: actions/setup-node@v4 with: - path: "**/node_modules" - key: ${{ runner.os }}-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }} + node-version: ${{ inputs.node_lts_active_version }} + cache: 'npm' + - name: Set up QEMU uses: docker/setup-qemu-action@v1 + - name: Set up Docker Buildx id: buildx uses: docker/setup-buildx-action@v1 + - name: Login to DockerHub uses: docker/login-action@v1 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} + - name: Get current version from package.json shell: bash id: get-version run: | - echo "::set-output name=version::$(jq -r .version package.json)" - echo "::set-output name=major-version::$(jq -r .version package.json | cut -d. -f 1)" + echo "version=$(jq -r .version package.json)" >> $GITHUB_OUTPUT + echo "major-version=$(jq -r .version package.json | cut -d. -f 1)" >> $GITHUB_OUTPUT + - name: Build TS files run: | npm ci npm run build + - name: Build and push uses: docker/build-push-action@v2 with: @@ -134,15 +153,25 @@ jobs: npm-deploy: name: Build and deploy release on NPM.js if: ${{ (github.event_name != 'workflow_dispatch' || inputs.npm_deploy) && github.ref_name == 'master' }} - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 - - uses: ./.github/actions/install-packages - - uses: actions/setup-node@v3 + - name: Checkout project + uses: actions/checkout@v3 + + - name: Install additional libraries + uses: ./.github/actions/install-packages + + - name: Node version ${{ inputs.node_lts_active_version }} + uses: actions/setup-node@v4 with: - node-version: ${{ inputs.node_lts_maintenance_version }} + node-version: ${{ inputs.node_lts_active_version }} registry-url: "https://registry.npmjs.org" - - run: npm ci - - run: npm publish + cache: 'npm' + + - name: Install depedencies + run: npm ci + + - name: Publish package + run: npm publish env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.github/workflows/workflow.yaml b/.github/workflows/workflow.yaml index d2b51e070c..9af89b207f 100644 --- a/.github/workflows/workflow.yaml +++ b/.github/workflows/workflow.yaml @@ -5,22 +5,22 @@ on: branches: - master - 2-dev - pull_request: # This syntax stand for all PRs events + pull_request: env: NODE_LTS_MAINTENANCE_VERSION: "16" NODE_LTS_ACTIVE_VERSION: "18" - NODE_LTS_CURRENT_VERSION: "20" # Stand for the latest LTS version + NODE_LTS_CURRENT_VERSION: "20" DOCKER_PLATFORMS: "linux/amd64,linux/arm64" jobs: prepare-matrix: name: Forge Node LTS Matrix - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - id: set-matrix run: | - echo "::set-output name=matrix::{\"node-version\": [\"$NODE_LTS_MAINTENANCE_VERSION\", \"$NODE_LTS_ACTIVE_VERSION\"]}" + echo "matrix={\"node-version\": [\"$NODE_LTS_MAINTENANCE_VERSION\", \"$NODE_LTS_ACTIVE_VERSION\"]}" >> $GITHUB_OUTPUT outputs: matrix: ${{ steps.set-matrix.outputs.matrix }} node_lts_maintenance_version: ${{ env.NODE_LTS_MAINTENANCE_VERSION }} @@ -30,29 +30,48 @@ jobs: error-codes-check: name: Documentation - Error codes check - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 - - uses: ./.github/actions/install-packages - - run: npm ci + - name: Checkout project + uses: actions/checkout@v3 + + - name: Install additional libraries + uses: ./.github/actions/install-packages + + - name: Node version ${{ env.NODE_LTS_ACTIVE_VERSION }} + uses: actions/setup-node@v4 + with: + node_version: ${{ env.NODE_LTS_ACTIVE_VERSION }} + cache: "npm" + + - name: Install depedencies + run: npm ci + - name: Test error codes run: ./.ci/scripts/check-error-codes-documentation.sh lint: name: Lint - Node.js LTS ${{ matrix.node-version }} - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 needs: [prepare-matrix] strategy: matrix: node-version: ${{ fromJson(needs.prepare-matrix.outputs.matrix).node-version }} steps: - - uses: actions/checkout@v3 - - uses: ./.github/actions/install-packages - - uses: actions/setup-node@v3 + - name: Checkout project + uses: actions/checkout@v3 + + - name: Install additional libraries + uses: ./.github/actions/install-packages + + - name: Node version ${{ matrix.node-version }} + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - key: ${{ runner.os }}-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }} - - uses: ./.github/actions/es-lint + cache: "npm" + + - name: Run ESlint + uses: ./.github/actions/es-lint unit-tests: name: Unit Tests @@ -60,15 +79,22 @@ jobs: strategy: matrix: node-version: ${{ fromJson(needs.prepare-matrix.outputs.matrix).node-version }} - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 - - uses: ./.github/actions/install-packages - - uses: actions/setup-node@v3 + - name: Checkout project + uses: actions/checkout@v3 + + - name: Install additional libraries + uses: ./.github/actions/install-packages + + - name: Node version ${{ matrix.node-version }} + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - key: ${{ runner.os }}-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }} - - uses: ./.github/actions/unit-tests + cache: "npm" + + - name: Run unit test using Node ${{ matrix.node-version }} + uses: ./.github/actions/unit-tests env: NODE_VERSION: ${{ matrix.node-version }} @@ -78,25 +104,32 @@ jobs: build-and-run-kuzzle: needs: [unit-tests, prepare-matrix] - name: Build and Run ${{ matrix.kuzzle-image }} - runs-on: ubuntu-latest + name: Build and Run + runs-on: ubuntu-22.04 strategy: matrix: node-version: ${{ fromJson(needs.prepare-matrix.outputs.matrix).node-version }} kuzzle-image: ["kuzzle"] steps: - - uses: actions/checkout@v3 - - uses: ./.github/actions/install-packages - - uses: actions/setup-node@v3 + - name: Checkout project + uses: actions/checkout@v3 + + - name: Install additional libraries + uses: ./.github/actions/install-packages + + - name: Node version ${{ matrix.node-version }} + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - key: ${{ runner.os }}-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }} - - uses: ./.github/actions/build-and-run-kuzzle + cache: "npm" + + - name: Test to run Kuzzle image + uses: ./.github/actions/build-and-run-kuzzle with: KUZZLE_IMAGE: ${{ matrix.kuzzle-image }} functional-tests: - name: Functional Tests - ${{ matrix.test_set }} - Node.js v${{ matrix.node-version }} + name: ${{ matrix.test_set }} - Node.js v${{ matrix.node-version }} needs: [unit-tests, prepare-matrix] strategy: matrix: @@ -110,15 +143,28 @@ jobs: "legacy:websocket", ] node-version: ${{ fromJson(needs.prepare-matrix.outputs.matrix).node-version }} - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 - - uses: ./.github/actions/install-packages - - uses: actions/setup-node@v3 + - name: Checkout project + uses: actions/checkout@v3 + + - name: Install additional libraries + uses: ./.github/actions/install-packages + + - name: Node version ${{ matrix.node-version }} + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - key: ${{ runner.os }}-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }} - - uses: ./.github/actions/functional-tests + cache: "npm" + + - name: Install depedencies + run: npm ci + + - name: Build kuzzle + run: npm run build + + - name: test suit ${{ matrix.test_set }} + uses: ./.github/actions/functional-tests with: test-set: test:functional:${{ matrix.test_set }} node-version: ${{ matrix.node-version }} @@ -128,23 +174,31 @@ jobs: cluster-monkey-tests: name: Cluster Monkey Tests needs: [functional-tests, build-and-run-kuzzle, prepare-matrix] - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 strategy: matrix: node-version: ${{ fromJson(needs.prepare-matrix.outputs.matrix).node-version }} steps: - - uses: actions/checkout@v3 - - uses: ./.github/actions/install-packages + - name: Checkout project + uses: actions/checkout@v3 + + - name: Install additional libraries + uses: ./.github/actions/install-packages + - name: Cloning Monkey Tester uses: actions/checkout@v3 with: repository: kuzzleio/kuzzle-monkey-tests path: "kuzzle-monkey-tests" - - uses: actions/setup-node@v3 + + - name: Node version ${{ matrix.node-version }} + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - key: ${{ runner.os }}-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }} - - uses: ./.github/actions/monkey-tests + cache: "npm" + + - name: Run monkey testing tests suit + uses: ./.github/actions/monkey-tests with: node-version: ${{ matrix.node-version }} env: diff --git a/README.md b/README.md index c8e8f27b7c..28dc3d7c1f 100644 --- a/README.md +++ b/README.md @@ -145,7 +145,7 @@ First of all make sure that you have at least `4GB` of ram allocated to your vm Run the following command to install all the dependencies in your container: ```bash -npm run docker:install +docker compose run kuzzle_node_1 npm ci ``` Finally, run the command `docker compose up` to start your Kuzzle stack. diff --git a/bin/.upgrades/connectors/es.js b/bin/.upgrades/connectors/es.js index 6043d381f7..425f324764 100644 --- a/bin/.upgrades/connectors/es.js +++ b/bin/.upgrades/connectors/es.js @@ -34,13 +34,13 @@ let promise = null; async function getEsClient(context) { const currentConfiguration = _.get( context.config, - "services.storageEngine.client" + "services.storageEngine.client", ); if (!currentConfiguration) { context.log.error("Missing Kuzzle configuration for Elasticsearch."); context.log.error( - "Missing configuration value: services.storageEngine.client" + "Missing configuration value: services.storageEngine.client", ); context.log.error("Aborted."); process.exit(1); @@ -48,7 +48,7 @@ async function getEsClient(context) { context.log.notice("Current Elasticsearch configuration:"); context.log.print( - formatWithOptions({ colors: false, depth: null }, currentConfiguration) + formatWithOptions({ colors: false, depth: null }, currentConfiguration), ); const answers = await context.inquire.prompt([ diff --git a/bin/.upgrades/connectors/redis.js b/bin/.upgrades/connectors/redis.js index 6d9ba807f3..3829b20259 100644 --- a/bin/.upgrades/connectors/redis.js +++ b/bin/.upgrades/connectors/redis.js @@ -40,7 +40,7 @@ async function getRedisClient(context) { context.log.notice("Current Redis configuration:"); context.log.print( - formatWithOptions({ colors: false, depth: null }, currentConfiguration) + formatWithOptions({ colors: false, depth: null }, currentConfiguration), ); const current = await context.inquire.direct({ diff --git a/bin/.upgrades/lib/context.js b/bin/.upgrades/lib/context.js index 899207e302..1f9e4fdc6b 100644 --- a/bin/.upgrades/lib/context.js +++ b/bin/.upgrades/lib/context.js @@ -79,7 +79,7 @@ class UpgradeContext { this.log.error(`Cannot load configuration files: ${e.message}`); if (this.config === null) { this.log.error( - "Check your configuration files, and restart the upgrade script." + "Check your configuration files, and restart the upgrade script.", ); process.exit(1); } @@ -120,7 +120,7 @@ class UpgradeContext { .filter((entry) => entry.isDirectory() && entry.name.match(/^v\d+$/)) .map((entry) => entry.name) .sort( - (a, b) => parseInt(a[0].substring(1)) - parseInt(b[0].substring(1)) + (a, b) => parseInt(a[0].substring(1)) - parseInt(b[0].substring(1)), ); if (version.list.length === 1) { diff --git a/bin/.upgrades/lib/inquirerExtended.js b/bin/.upgrades/lib/inquirerExtended.js index 923648d869..65ff08c368 100644 --- a/bin/.upgrades/lib/inquirerExtended.js +++ b/bin/.upgrades/lib/inquirerExtended.js @@ -33,11 +33,11 @@ const assert = require("assert").strict, inquirer.direct = async function direct(prompt) { assert( _.isPlainObject(prompt), - "Invalid argument: expected a non-empty object" + "Invalid argument: expected a non-empty object", ); assert( typeof prompt.name === "undefined", - 'Unexpected "name" argument: if you need to set a name, use inquirer.prompt' + 'Unexpected "name" argument: if you need to set a name, use inquirer.prompt', ); const p = _.cloneDeep(prompt); diff --git a/bin/.upgrades/versions/v1/upgradeCache.js b/bin/.upgrades/versions/v1/upgradeCache.js index a06beb8521..30f45d6ed8 100644 --- a/bin/.upgrades/versions/v1/upgradeCache.js +++ b/bin/.upgrades/versions/v1/upgradeCache.js @@ -37,7 +37,7 @@ async function copyKey(context, key) { async function getSourceKeys(context, pattern) { if (!context.source.nodes) { - return await context.source.keys(pattern); + return context.source.keys(pattern); } const keys = []; diff --git a/bin/.upgrades/versions/v1/upgradeStorage.js b/bin/.upgrades/versions/v1/upgradeStorage.js index 79a222dcf8..391e69d8c8 100644 --- a/bin/.upgrades/versions/v1/upgradeStorage.js +++ b/bin/.upgrades/versions/v1/upgradeStorage.js @@ -37,10 +37,10 @@ function transformProfile(profile) { for (const policy of profile.policies.filter((p) => p.restrictedTo)) { for (const restriction of policy.restrictedTo.filter( - (r) => r.collections + (r) => r.collections, )) { restriction.collections = restriction.collections.map((c) => - c.toLowerCase() + c.toLowerCase(), ); } } @@ -59,7 +59,7 @@ function fixIndexName(context, index, collection, newIndex) { if (lowercased !== newIndex) { // uppercase letters were already forbidden in index names context.log.warn( - `Index "${index}": collection "${collection}" has been renamed to "${collection.toLowerCase()}"` + `Index "${index}": collection "${collection}" has been renamed to "${collection.toLowerCase()}"`, ); } @@ -79,7 +79,7 @@ async function moveData(context, index, collection, newIndex, transform) { const progressBar = new ProgressBar( context, `Importing: ${index}/${collection}`, - total + total, ); let moved = 0; @@ -166,7 +166,7 @@ async function upgrade(context, index, collection, newIndex) { await createNewIndex(context, fixedIndexName); await upgradeMappings(context, index, collection, fixedIndexName); - return await moveData(context, index, collection, fixedIndexName); + return moveData(context, index, collection, fixedIndexName); } async function upgradeInternalStorage(context) { @@ -198,14 +198,14 @@ async function upgradeInternalStorage(context) { index, collection, newIndex, - collection === "profiles" && transformProfile + collection === "profiles" && transformProfile, ); } else { total = await upgrade(context, index, collection, newIndex); } context.log.ok( - `... migrated internal data: ${collection} (${total} documents)` + `... migrated internal data: ${collection} (${total} documents)`, ); } @@ -242,7 +242,7 @@ async function upgradePluginsStorage(context) { const total = await upgrade(context, index, collection, newIndex); context.log.ok( - `... migrated storage for plugin ${plugin}: ${collection} (${total} documents)` + `... migrated storage for plugin ${plugin}: ${collection} (${total} documents)`, ); } } @@ -302,7 +302,7 @@ async function upgradeDataStorage(context) { .filter((n) => !n.startsWith(INTERNAL_PREFIX)); context.log.notice( - `There are ${indexes.length} data indexes that can be upgraded` + `There are ${indexes.length} data indexes that can be upgraded`, ); const choices = { all: "upgrade all indexes", @@ -355,7 +355,7 @@ async function upgradeDataStorage(context) { upgraded[index].targets.push(newIndex); context.log.ok( - `... migrated data index ${index}: ${collection} (${total} documents)` + `... migrated data index ${index}: ${collection} (${total} documents)`, ); } } @@ -384,10 +384,10 @@ async function destroyPreviousStructure(context, upgraded) { ]; context.log.notice( - "Since this is an in-place migration, the previous structure can be removed." + "Since this is an in-place migration, the previous structure can be removed.", ); context.log.notice( - "(only data indexes with ALL their collections upgraded can be deleted)" + "(only data indexes with ALL their collections upgraded can be deleted)", ); const choices = { diff --git a/docker/docker-compose-swarm.yml b/docker/docker-compose-swarm.yml deleted file mode 100644 index 353c20cae9..0000000000 --- a/docker/docker-compose-swarm.yml +++ /dev/null @@ -1,100 +0,0 @@ -version: '3.4' - -services: - traefik: - image: traefik - container_name: traefik - ports: - - "7512:7512" - - "1883:1883" - command: - - --log.level=WARN - - --providers.docker=true - - --providers.docker.exposedbydefault=false - - --providers.docker.endpoint=unix:///var/run/docker.sock - - --entrypoints.kuzzle_http.address=:7512 - - --entrypoints.kuzzle_mqtt.address=:1883 - depends_on: - kuzzle: - condition: service_healthy - volumes: - - "/var/run/docker.sock:/var/run/docker.sock:ro" - - kuzzle: - image: kuzzleio/core-dev:2 - command: node app.js - volumes: - - "..:/var/app" - - "./scripts/run-dev.sh:/run-dev.sh" - - "./fixtures:/fixtures" - cap_add: - - SYS_PTRACE - ulimits: - nofile: 65536 - sysctls: - - net.core.somaxconn=8192 - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:7512/_healthcheck"] - timeout: 1s - interval: 2s - retries: 30 - depends_on: - redis: - condition: service_healthy - elasticsearch: - condition: service_healthy - labels: - - "traefik.enable=true" - # Kuzzle HTTP/WS - - "traefik.http.services.kuzzle_http.loadbalancer.server.port=7512" - - "traefik.http.services.kuzzle_http.loadbalancer.healthCheck.path=/_healthcheck" - - "traefik.http.services.kuzzle_http.loadbalancer.healthCheck.interval=5s" - - "traefik.http.routers.kuzzle.entrypoints=kuzzle_http" - - "traefik.http.routers.kuzzle.rule=Host(`localhost`)" - - "traefik.http.routers.kuzzle.service=kuzzle_http" - # Kuzzle MQTT - - "traefik.tcp.services.kuzzle_mqtt.loadbalancer.server.port=1883" - - "traefik.tcp.routers.kuzzle.entrypoints=kuzzle_mqtt" - - "traefik.tcp.routers.kuzzle.rule=HostSNI(`*`)" - - "traefik.tcp.routers.kuzzle.service=kuzzle_mqtt" - environment: - - kuzzle_services__storageEngine__client__node=http://elasticsearch:9200 - - kuzzle_services__storageEngine__commonMapping__dynamic=true - - kuzzle_services__internalCache__node__host=redis - - kuzzle_services__memoryStorage__node__host=redis - - kuzzle_server__protocols__mqtt__enabled=true - - kuzzle_server__protocols__mqtt__developmentMode=false - - kuzzle_limits__loginsPerSecond=50 - # - NODE_ENV=${NODE_ENV:-development} - - NODE_ENV=production - # - DEBUG=${DEBUG:-kuzzle:*,-kuzzle:network:protocols:websocket,-kuzzle:events} - - DEBUG=${DEBUG:-kuzzle:cluster:sync} - - DEBUG_DEPTH=${DEBUG_DEPTH:-0} - - DEBUG_MAX_ARRAY_LENGTH=${DEBUG_MAX_ARRAY:-100} - - DEBUG_EXPAND=${DEBUG_EXPAND:-off} - - DEBUG_SHOW_HIDDEN={$DEBUG_SHOW_HIDDEN:-on} - - DEBUG_COLORS=${DEBUG_COLORS:-on} - - redis: - image: redis:6.2.4 - container_name: kuzzle_redis - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 1s - timeout: 3s - retries: 30 - ports: - - "6379:6379" - - elasticsearch: - image: kuzzleio/elasticsearch:7 - container_name: kuzzle_elasticsearch - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:9200"] - interval: 2s - timeout: 2s - retries: 10 - ports: - - "9200:9200" - ulimits: - nofile: 65536 diff --git a/docker/images/core-dev/Dockerfile b/docker/images/core-dev/Dockerfile new file mode 100644 index 0000000000..25cba5b446 --- /dev/null +++ b/docker/images/core-dev/Dockerfile @@ -0,0 +1,32 @@ +ARG NODE_LTS_VERSION="18" +FROM node:${NODE_LTS_VERSION}-bullseye-slim + +LABEL io.kuzzle.vendor="Kuzzle " +LABEL description="Enhance the Kuzzle core with ease" + +RUN mkdir /var/npm && chown node:node /var/npm + +ENV NPM_CONFIG_CACHE=/var/npm + +WORKDIR /var/app + +RUN set -x \ + \ + && apt-get update \ + && apt-get install -y \ + bash-completion \ + build-essential \ + curl \ + g++ \ + gdb \ + git \ + gnupg \ + libfontconfig \ + libzmq3-dev \ + python3 \ + procps \ + wget \ + libunwind-dev \ + && npm install -g kourou \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* diff --git a/docker/images/core-dev/README.md b/docker/images/core-dev/README.md new file mode 100644 index 0000000000..e82814f03a --- /dev/null +++ b/docker/images/core-dev/README.md @@ -0,0 +1,21 @@ +# kuzzleio/core-dev + +*~ 720 MB.* +This image is useful for core developer. Kuzzle source code is mounted inside the container. + +Contains: + * all needed to watch and build kuzzleio projects on the fly: + * NVM with node 18 + * build-essential + * g++ + * python + * rbenv + * libfontconfig + * [gem] sass + * [npm] bower + * [npm] node-inspector + * tools to improve development experience: + * bash-completion + * ll alias + * curl + * wget diff --git a/docker/images/elasticsearch/Dockerfile b/docker/images/elasticsearch/Dockerfile new file mode 100644 index 0000000000..fe8d79ff46 --- /dev/null +++ b/docker/images/elasticsearch/Dockerfile @@ -0,0 +1,13 @@ +ARG ELASTICSEARCH_VERSION="7.16.2" +FROM docker.elastic.co/elasticsearch/elasticsearch:${ELASTICSEARCH_VERSION} + +LABEL maintainer="kuzzle" contact="" + +COPY jvm.options /usr/share/elasticsearch/config/jvm.options + +ENV ES_JAVA_OPTS="-Xms512m -Xmx512m" + +ENV cluster.name=kuzzle +ENV node.name=alyx +ENV discovery.type=single-node +ENV ingest.geoip.downloader.enabled=false diff --git a/docker/images/elasticsearch/README.md b/docker/images/elasticsearch/README.md new file mode 100644 index 0000000000..95b9c18d44 --- /dev/null +++ b/docker/images/elasticsearch/README.md @@ -0,0 +1,7 @@ +# Elasticsearch + +This container is built from [Elasticsearch official 7.10 image](https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html) with a few modifications: + +* All xpack plugins are disabled by default +* `jvm.options` file is modified to remove the jvm heap size settings, thus allowing to set them with `ES_JAVA_OPTS` environment variable (default to 512m). +* The GeoIP downloader is disabled by default diff --git a/docker/images/elasticsearch/jvm.options b/docker/images/elasticsearch/jvm.options new file mode 100644 index 0000000000..7a5ab342cb --- /dev/null +++ b/docker/images/elasticsearch/jvm.options @@ -0,0 +1,94 @@ +################################################################ +## +## JVM configuration +## +################################################################ +## +## WARNING: DO NOT EDIT THIS FILE. If you want to override the +## JVM options in this file, or set any additional options, you +## should create one or more files in the jvm.options.d +## directory containing your adjustments. +## +## See https://www.elastic.co/guide/en/elasticsearch/reference/current/jvm-options.html +## for more information. +## +################################################################ + + + +################################################################ +## IMPORTANT: JVM heap size +################################################################ +## +## The heap size is automatically configured by Elasticsearch +## based on the available memory in your system and the roles +## each node is configured to fulfill. If specifying heap is +## required, it should be done through a file in jvm.options.d, +## and the min and max should be set to the same value. For +## example, to set the heap to 4 GB, create a new file in the +## jvm.options.d directory containing these lines: +## +## -Xms4g +## -Xmx4g +## +## See https://www.elastic.co/guide/en/elasticsearch/reference/current/heap-size.html +## for more information +## +################################################################ + + +################################################################ +## Expert settings +################################################################ +## +## All settings below here are considered expert settings. Do +## not adjust them unless you understand what you are doing. Do +## not edit them in this file; instead, create a new file in the +## jvm.options.d directory containing your adjustments. +## +################################################################ + +## GC configuration +8-13:-XX:+UseConcMarkSweepGC +8-13:-XX:CMSInitiatingOccupancyFraction=75 +8-13:-XX:+UseCMSInitiatingOccupancyOnly + +## G1GC Configuration +# NOTE: G1 GC is only supported on JDK version 10 or later +# to use G1GC, uncomment the next two lines and update the version on the +# following three lines to your version of the JDK +# 10-13:-XX:-UseConcMarkSweepGC +# 10-13:-XX:-UseCMSInitiatingOccupancyOnly +14-:-XX:+UseG1GC + +## JVM temporary directory + +## heap dumps + +# generate a heap dump when an allocation from the Java heap fails; heap dumps +# are created in the working directory of the JVM unless an alternative path is +# specified +-XX:+HeapDumpOnOutOfMemoryError + +# specify an alternative path for heap dumps; ensure the directory exists and +# has sufficient space +-XX:HeapDumpPath=data + +# specify an alternative path for JVM fatal error logs +-XX:ErrorFile=logs/hs_err_pid%p.log + +## JDK 8 GC logging +8:-XX:+PrintGCDetails +8:-XX:+PrintGCDateStamps +8:-XX:+PrintTenuringDistribution +8:-XX:+PrintGCApplicationStoppedTime +8:-Xloggc:logs/gc.log +8:-XX:+UseGCLogFileRotation +8:-XX:NumberOfGCLogFiles=32 +8:-XX:GCLogFileSize=64m + +# JDK 9+ GC logging +9-:-Xlog:gc*,gc+age=trace,safepoint:file=logs/gc.log:utctime,pid,tags:filecount=32,filesize=64m + +# Log4Shell mitigation +-Dlog4j2.formatMsgNoLookups=true diff --git a/docker/images/kuzzle-runner/Dockerfile b/docker/images/kuzzle-runner/Dockerfile new file mode 100644 index 0000000000..d4e648cec1 --- /dev/null +++ b/docker/images/kuzzle-runner/Dockerfile @@ -0,0 +1,25 @@ +ARG NODE_LTS_VERSION="18" +FROM node:${NODE_LTS_VERSION}-bullseye-slim + +LABEL io.kuzzle.vendor="Kuzzle " +LABEL description="Run your in-development Kuzzle application with ease" + +RUN mkdir /var/npm && chown node:node /var/npm + +ENV NPM_CONFIG_CACHE=/var/npm + +WORKDIR /var/app + +RUN set -x \ + && apt-get update && apt-get install -y \ + curl \ + python3 \ + make \ + g++ \ + git \ + libzmq3-dev \ + libunwind-dev \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* + +RUN npm i -g kourou diff --git a/features/step_definitions/auth-steps.js b/features/step_definitions/auth-steps.js index 7c86236a5f..2acdd73603 100644 --- a/features/step_definitions/auth-steps.js +++ b/features/step_definitions/auth-steps.js @@ -11,7 +11,7 @@ Given( username, password, }); - } + }, ); Given("I'm logged as the anonymous user", function () { @@ -37,7 +37,7 @@ Given( } else { should(valid).be.true("Provided token is invalid"); } - } + }, ); Given("I save the created API key", function () { @@ -68,5 +68,5 @@ Given( throw error; } } - } + }, ); diff --git a/features/step_definitions/bulk-steps.js b/features/step_definitions/bulk-steps.js index ffd2fd59d1..0bfa6e2d11 100644 --- a/features/step_definitions/bulk-steps.js +++ b/features/step_definitions/bulk-steps.js @@ -12,7 +12,7 @@ When("I perform a bulk import with the following:", async function (dataTable) { this.props.result = await this.sdk.bulk.import( this.props.index, this.props.collection, - bulkData + bulkData, ); }); @@ -55,5 +55,5 @@ Then( const { result } = await this.sdk.query(request); this.props.result = result; - } + }, ); diff --git a/features/step_definitions/collection-steps.js b/features/step_definitions/collection-steps.js index f425726254..a8ccbb10e9 100644 --- a/features/step_definitions/collection-steps.js +++ b/features/step_definitions/collection-steps.js @@ -23,7 +23,7 @@ Given( this.props.index = index; this.props.collection = collection; - } + }, ); Then( @@ -50,7 +50,7 @@ Then( this.props.result = await this.sdk.collection[action]( index, collection, - { mappings, settings } + { mappings, settings }, ); } @@ -59,7 +59,7 @@ Then( } catch (error) { this.props.error = error; } - } + }, ); Then( @@ -70,7 +70,7 @@ Then( this.props.result = { collections: collections.filter(({ type }) => type === expectedType), }; - } + }, ); Then( @@ -85,14 +85,14 @@ Then( } else { should(collectionNames).containEql(collection); } - } + }, ); Then( "I get mappings of collection {string}:{string}", async function (index, collection) { this.props.result = await this.sdk.collection.getMapping(index, collection); - } + }, ); Then("I refresh the collection", function () { diff --git a/features/step_definitions/controllers-steps.js b/features/step_definitions/controllers-steps.js index a4fc9e95d9..a3969246c5 100644 --- a/features/step_definitions/controllers-steps.js +++ b/features/step_definitions/controllers-steps.js @@ -25,7 +25,7 @@ Then( this.props.error = error; } - } + }, ); Then( @@ -45,7 +45,7 @@ Then( this.props.error = error; } - } + }, ); Then( @@ -63,7 +63,7 @@ Then( this.props.error = error; } - } + }, ); Then( @@ -76,7 +76,7 @@ Then( should(result.length).be.eql( expected.length, - `Array are not the same size: expected ${expected.length} got ${result.length}` + `Array are not the same size: expected ${expected.length} got ${result.length}`, ); if (!objects) { @@ -86,7 +86,7 @@ Then( for (let i = 0; i < expected.length; i++) { should(result[i]).matchObject(expected[i]); } - } + }, ); Then( @@ -95,7 +95,7 @@ Then( const result = name ? this.props.result[name] : this.props.result; should(result).have.length(expectedCount); - } + }, ); Then("I should receive a result matching:", function (dataTable) { @@ -128,7 +128,7 @@ Then( } else { should(property).match(expectedProperty); } - } + }, ); Then("The result should be {string}", function (rawValue) { @@ -145,7 +145,7 @@ Then( should(property).not.be.undefined(); should(typeof property).be.eql(type); - } + }, ); Then( @@ -164,7 +164,7 @@ Then( should(this.props.result).not.be.undefined(); should(this.props.result).eql(expectedResult); - } + }, ); Then("I should receive an empty result", function () { @@ -196,12 +196,12 @@ Then("I should receive a empty {string} array", function (name) { Then("I got an error with id {string}", function (id) { assert( this.props.error !== null, - "Expected the previous step to return an error" + "Expected the previous step to return an error", ); assert( this.props.error.id === id, - `Expected error to have id "${id}", but got "${this.props.error.id}"` + `Expected error to have id "${id}", but got "${this.props.error.id}"`, ); }); @@ -210,7 +210,7 @@ Then( async function (dataTable) { const expectedResult = this.parseObject(dataTable); should(this.props.response.headers).deepEqual(expectedResult); - } + }, ); Then( @@ -218,14 +218,14 @@ Then( async function (key, dataTable) { const array = this.parseObjectArray(dataTable); should(this.props.response[key]).deepEqual(array); - } + }, ); Then( "The response should contains a {string} equals to undefined", async function (key) { should(this.props.response[key]).equal(undefined); - } + }, ); Then("The raw response should match:", function (dataTable) { @@ -268,7 +268,7 @@ Then( throw err; } } - } + }, ); Then("I wait {int} milliseconds", async function (ms) { diff --git a/features/step_definitions/documents-steps.js b/features/step_definitions/documents-steps.js index 8a09c9fccc..fe6cbe04f5 100644 --- a/features/step_definitions/documents-steps.js +++ b/features/step_definitions/documents-steps.js @@ -16,13 +16,13 @@ Given( await this.tryAction( this.sdk.document.create(index, collection, document.body, document._id), not, - "Document should not have been created" + "Document should not have been created", ); if (!not) { this.props.documentId = this.props.result._id; } - } + }, ); Then( @@ -33,13 +33,13 @@ Then( const document = await this.sdk.document.get( this.props.index, this.props.collection, - documentId + documentId, ); for (const [key, value] of Object.entries(expectedContent)) { should(_.get(document._source, key)).be.eql(value); } - } + }, ); Then( @@ -52,9 +52,9 @@ Then( this.props.result = await this.sdk.document[action]( this.props.index, this.props.collection, - documents + documents, ); - } + }, ); Then( @@ -71,7 +71,7 @@ Then( }); this.props.result = response.result; - } + }, ); Then( @@ -84,23 +84,23 @@ Then( this.props.index, this.props.collection, body, - _id + _id, ); } else { this.props.result = await this.sdk.document[action]( this.props.index, this.props.collection, _id, - body + body, ); } - } + }, ); Then("I count {int} documents", async function (expectedCount) { const count = await this.sdk.document.count( this.props.index, - this.props.collection + this.props.collection, ); should(count).be.eql(expectedCount); @@ -120,18 +120,18 @@ Then( const count = await this.sdk.document.count( this.props.index, this.props.collection, - { query } + { query }, ); should(count).be.eql(expectedCount); - } + }, ); Then(/The document "(.*?)" should( not)? exist/, async function (id, not) { const exists = await this.sdk.document.exists( this.props.index, this.props.collection, - id + id, ); if (not && exists) { @@ -155,9 +155,9 @@ Then( this.props.index, this.props.collection, ids, - options + options, ); - } + }, ); Then("I search documents with the following query:", function (queryRaw) { @@ -172,7 +172,7 @@ Then( const searchBody = JSON.parse(searchBodyRaw); this.props.searchBody = searchBody; - } + }, ); Then("with the following highlights:", function (highlightsRaw) { @@ -257,7 +257,7 @@ Then("I delete the document {string}", async function (id) { this.props.result = await this.sdk.document.delete( this.props.index, this.props.collection, - id + id, ); }); @@ -286,12 +286,12 @@ Then( response.on("error", (error) => { reject(error); }); - } + }, ); req.end(); }); - } + }, ); Then( @@ -334,12 +334,12 @@ Then( response.on("error", (error) => { reject(error); }); - } + }, ); req.end(); }); - } + }, ); Then( @@ -370,11 +370,11 @@ Then( response.on("error", (error) => { reject(error); }); - } + }, ); req.write(JSON.stringify(options)); req.end(); }); - } + }, ); diff --git a/features/step_definitions/plugin-events-steps.js b/features/step_definitions/plugin-events-steps.js index 53064744a7..c4c1234427 100644 --- a/features/step_definitions/plugin-events-steps.js +++ b/features/step_definitions/plugin-events-steps.js @@ -17,7 +17,7 @@ Given( }; await this.sdk.query(request); - } + }, ); Given( @@ -32,5 +32,5 @@ Given( state, event, }); - } + }, ); diff --git a/features/step_definitions/realtime-steps.js b/features/step_definitions/realtime-steps.js index 6d78a1f0a1..d4d36a22c1 100644 --- a/features/step_definitions/realtime-steps.js +++ b/features/step_definitions/realtime-steps.js @@ -16,16 +16,16 @@ Then( {}, (notification) => { this.props.subscriptions[`${index}:${collection}`].notifications.push( - notification + notification, ); - } + }, ); this.props.subscriptions[`${index}:${collection}`] = { unsubscribe: () => this.sdk.realtime.unsubscribe(roomId), notifications: [], }; - } + }, ); Then("I unsubscribe from the current room via the plugin", async function () { @@ -51,10 +51,10 @@ Then( const expectedCount = parseInt(rawNumber, 10); should( - this.props.subscriptions[`${index}:${collection}`].notifications + this.props.subscriptions[`${index}:${collection}`].notifications, ).have.length(expectedCount); }); - } + }, ); Then( @@ -64,18 +64,18 @@ Then( const expectedNotifications = this.parseObjectArray(datatable); should( - this.props.subscriptions[`${index}:${collection}`] + this.props.subscriptions[`${index}:${collection}`], ).not.be.undefined(); const subscription = this.props.subscriptions[`${index}:${collection}`]; should(subscription.notifications).be.length( - expectedNotifications.length + expectedNotifications.length, ); for (let i = 0; i < expectedNotifications.length; i++) { should(subscription.notifications[i]).matchObject( - expectedNotifications[i] + expectedNotifications[i], ); } }; @@ -94,5 +94,5 @@ Then( }, 500); } }, 100); - } + }, ); diff --git a/features/step_definitions/security-steps.js b/features/step_definitions/security-steps.js index 9e08ee7c1f..ea09522970 100644 --- a/features/step_definitions/security-steps.js +++ b/features/step_definitions/security-steps.js @@ -38,7 +38,7 @@ Then( } throw e; } - } + }, ); Then( @@ -51,9 +51,9 @@ Then( await this.tryAction( this.sdk.security[method + "Role"](roleId, { controllers }, options), - not + not, ); - } + }, ); Then(/I am (not )?able to get a role with id "(.*?)"/, function (not, roleId) { @@ -66,9 +66,9 @@ Then( return this.tryAction( this.sdk.security.getProfile(profileId), not, - `Profile ${profileId} exists` + `Profile ${profileId} exists`, ); - } + }, ); Then( @@ -79,7 +79,7 @@ Then( const result = await this.sdk.security.searchRoles(controller); this.props.result = result; - } + }, ); Then( @@ -92,20 +92,20 @@ Then( } this.props.result = await this.sdk.security.mGetRoles(roleIds); - } + }, ); Then(/I (can not )?delete the role "(.*?)"/, function (not, roleId) { return this.tryAction( this.sdk.security.deleteRole(roleId, { refresh: "wait_for" }), - not + not, ); }); Then(/I (can not )?delete the profile "(.*?)"/, function (not, profileId) { return this.tryAction( this.sdk.security.deleteProfile(profileId, { refresh: "wait_for" }), - not + not, ); }); @@ -133,7 +133,7 @@ Then( this.props.result = await this.sdk.security.createUser(userId, body, { refresh: "wait_for", }); - } + }, ); Then("I update the role {string} with:", async function (roleId, dataTable) { @@ -148,7 +148,7 @@ Then("I update the role {string} with:", async function (roleId, dataTable) { this.props.result = await this.sdk.security.updateRole( roleId, { controllers: rights }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); }); @@ -183,7 +183,7 @@ Then( for (let i = 0; i < profile.policies; i++) { should(profile.policies[i]).match(expectedPolicies[i]); } - } + }, ); Then( @@ -194,7 +194,7 @@ Then( const user = await this.sdk.security.getUser(userId); should(user.profileIds).be.eql(expectedProfiles); - } + }, ); Then( @@ -215,7 +215,7 @@ Then( throw error; } } - } + }, ); Then( @@ -223,5 +223,5 @@ Then( async function (dataTable) { const userIds = _.flatten(dataTable.rawTable).map(JSON.parse); this.props.result = await this.sdk.security.mGetUsers(userIds); - } + }, ); diff --git a/features/step_definitions/websocket-steps.js b/features/step_definitions/websocket-steps.js index e8cdc9999d..0e12a2a6f7 100644 --- a/features/step_definitions/websocket-steps.js +++ b/features/step_definitions/websocket-steps.js @@ -21,7 +21,7 @@ When( "I send the message {string} to Kuzzle through websocket", function (message) { this.props.client.send(message); - } + }, ); Then("I wait to receive a websocket response from Kuzzle", function () { @@ -40,5 +40,5 @@ Then( function (dataTable) { const message = this.parseObject(dataTable); should(this.props.result).be.eql(message); - } + }, ); diff --git a/features/support/assertions.js b/features/support/assertions.js index 4508c7c786..063445a2a8 100644 --- a/features/support/assertions.js +++ b/features/support/assertions.js @@ -29,27 +29,27 @@ should.Assertion.add( should(objectValue).matchObject( expectedValue, `"${keyPath}" does not match. Expected "${JSON.stringify( - expectedValue - )}" have "${JSON.stringify(objectValue)}"` + expectedValue, + )}" have "${JSON.stringify(objectValue)}"`, ); } else if (_.isArray(objectValue)) { for (let i = 0; i < objectValue.length; i++) { should(objectValue[i]).matchObject( expectedValue[i], `"${keyPath}[${i}]" does not match. Expected "${JSON.stringify( - expectedValue[i] - )}" have "${JSON.stringify(objectValue[i])}"` + expectedValue[i], + )}" have "${JSON.stringify(objectValue[i])}"`, ); } } else { should(objectValue).match( expectedValue, `"${keyPath}" does not match. Expected "${JSON.stringify( - expectedValue - )}" have "${JSON.stringify(objectValue)}"` + expectedValue, + )}" have "${JSON.stringify(objectValue)}"`, ); } } }, - false + false, ); diff --git a/features/support/hooks.js b/features/support/hooks.js index b622fceafd..1982416528 100644 --- a/features/support/hooks.js +++ b/features/support/hooks.js @@ -34,7 +34,7 @@ BeforeAll({ timeout: 10 * 1000 }, async function () { const world = new World({}); console.log( - `Start tests with ${world.protocol.toLocaleUpperCase()} protocol.` + `Start tests with ${world.protocol.toLocaleUpperCase()} protocol.`, ); await world.sdk.connect(); @@ -172,7 +172,7 @@ After({ tags: "@realtime" }, function () { return; } const promises = Object.values(this.props.subscriptions).map( - ({ unsubscribe }) => unsubscribe() + ({ unsubscribe }) => unsubscribe(), ); return Promise.all(promises); diff --git a/jest/api/controller/document/mCreate.test.ts b/jest/api/controller/document/mCreate.test.ts index c6c722b016..7d634b6a44 100644 --- a/jest/api/controller/document/mCreate.test.ts +++ b/jest/api/controller/document/mCreate.test.ts @@ -28,7 +28,6 @@ beforeAll(async () => { }, }, }); - console.log("End beforeAll"); }); afterAll(async () => { diff --git a/lib/api/controllers/adminController.js b/lib/api/controllers/adminController.js index a469d378e9..0a866f79d1 100644 --- a/lib/api/controllers/adminController.js +++ b/lib/api/controllers/adminController.js @@ -81,7 +81,7 @@ class AdminController extends NativeController { "api", "process", "action_locked", - "Kuzzle is already reseting roles, profiles and users." + "Kuzzle is already reseting roles, profiles and users.", ); } @@ -92,22 +92,22 @@ class AdminController extends NativeController { result.deletedUsers = await this.ask( "core:security:user:truncate", - options + options, ); result.deletedProfiles = await this.ask( "core:security:profile:truncate", - options + options, ); result.deletedRoles = await this.ask( "core:security:role:truncate", - options + options, ); await global.kuzzle.internalIndex.createInitialSecurities(); await this.ask( "core:cache:internal:del", - `${BACKEND_IMPORT_KEY}:permissions` + `${BACKEND_IMPORT_KEY}:permissions`, ); } finally { await mutex.unlock(); @@ -127,7 +127,7 @@ class AdminController extends NativeController { "api", "process", "action_locked", - "Kuzzle is already reseting all indexes." + "Kuzzle is already reseting all indexes.", ); } @@ -137,7 +137,7 @@ class AdminController extends NativeController { await this.ask( "core:cache:internal:del", - `${BACKEND_IMPORT_KEY}:mappings` + `${BACKEND_IMPORT_KEY}:mappings`, ); return { acknowledge: true }; @@ -168,7 +168,7 @@ class AdminController extends NativeController { "api", "process", "action_locked", - "Kuzzle is already shutting down." + "Kuzzle is already shutting down.", ); } @@ -193,7 +193,7 @@ class AdminController extends NativeController { request.getRefresh("wait_for"), global.kuzzle.ask("core:storage:public:mappings:import", mappings, { rawMappings: true, - }) + }), ); } diff --git a/lib/api/controllers/authController.ts b/lib/api/controllers/authController.ts index 08d6c4d225..ef3fdfe0e4 100644 --- a/lib/api/controllers/authController.ts +++ b/lib/api/controllers/authController.ts @@ -77,7 +77,7 @@ export class AuthController extends NativeController { */ async init() { const anonymous = await global.kuzzle.ask( - "core:security:user:anonymous:get" + "core:security:user:anonymous:get", ); this.anonymousId = anonymous._id; } @@ -91,7 +91,7 @@ export class AuthController extends NativeController { "token", "invalid_expiration", "expiresIn", - "cannot be infinite" + "cannot be infinite", ); } @@ -101,7 +101,7 @@ export class AuthController extends NativeController { { expiresIn: request.input.args.expiresIn, singleUse, - } + }, ); return { @@ -129,7 +129,7 @@ export class AuthController extends NativeController { const user = request.context.user; const allowed = await user.isActionAllowed( - new KuzzleRequest(requestPayload) + new KuzzleRequest(requestPayload), ); return { @@ -219,13 +219,13 @@ export class AuthController extends NativeController { if ( global.kuzzle.config.internal.notifiableProtocols.includes( - request.context.connection.protocol + request.context.connection.protocol, ) ) { // Unlink connection so the connection will not be notified when the token expires. global.kuzzle.tokenManager.unlink( request.context.token, - request.context.connection.id + request.context.connection.id, ); } @@ -234,7 +234,7 @@ export class AuthController extends NativeController { await global.kuzzle.ask( "core:security:token:deleteByKuid", request.getKuid(), - { keepApiKeys: true } + { keepApiKeys: true }, ); } else if ( request.context.token && @@ -242,7 +242,7 @@ export class AuthController extends NativeController { ) { await global.kuzzle.ask( "core:security:token:delete", - request.context.token + request.context.token, ); } } @@ -339,7 +339,7 @@ export class AuthController extends NativeController { const content = await global.kuzzle.passport.authenticate( passportRequest, - strategy + strategy, ); // do not trigger the "auth:strategyAutenticated" pipe if the result is @@ -366,7 +366,7 @@ export class AuthController extends NativeController { const existingToken = global.kuzzle.tokenManager.getConnectedUserToken( authResponse.content._id, - request.context.connection.id + request.context.connection.id, ); /** @@ -385,7 +385,7 @@ export class AuthController extends NativeController { const token = await this.ask( "core:security:token:create", authResponse.content, - options + options, ); if (existingToken) { @@ -394,7 +394,7 @@ export class AuthController extends NativeController { if ( global.kuzzle.config.internal.notifiableProtocols.includes( - request.context.connection.protocol + request.context.connection.protocol, ) ) { // Link the connection with the token, this way the connection can be notified when the token has expired. @@ -421,13 +421,13 @@ export class AuthController extends NativeController { for (const strategy of global.kuzzle.pluginsManager.listStrategies()) { const existsMethod = global.kuzzle.pluginsManager.getStrategyMethod( strategy, - "exists" + "exists", ); promises.push( existsMethod(request, userId, strategy) .then((exists) => (exists ? strategy : null)) - .catch((err) => wrapPluginError(err)) + .catch((err) => wrapPluginError(err)), ); } } @@ -453,8 +453,8 @@ export class AuthController extends NativeController { .then((rights) => Object.keys(rights).reduce( (array, item) => array.concat(rights[item]), - [] - ) + [], + ), ) .then((rights) => ({ hits: rights, total: rights.length })); } @@ -480,7 +480,7 @@ export class AuthController extends NativeController { try { const { expiresAt = -1, userId } = await this.ask( "core:security:token:verify", - token + token, ); return { expiresAt, kuid: userId, valid: true }; @@ -515,13 +515,13 @@ export class AuthController extends NativeController { refresh: request.getRefresh("wait_for"), retryOnConflict: request.getInteger("retryOnConflict", 10), userId, - } + }, ); global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }" on user "${userId}."` + }" on user "${userId}."`, ); return formatProcessing.serializeUser(user); @@ -551,11 +551,11 @@ export class AuthController extends NativeController { const createMethod = global.kuzzle.pluginsManager.getStrategyMethod( strategy, - "create" + "create", ), validateMethod = global.kuzzle.pluginsManager.getStrategyMethod( strategy, - "validate" + "validate", ); return validateMethod(request, credentials, userId, strategy, false) @@ -578,11 +578,11 @@ export class AuthController extends NativeController { const updateMethod = global.kuzzle.pluginsManager.getStrategyMethod( request.input.args.strategy, - "update" + "update", ), validateMethod = global.kuzzle.pluginsManager.getStrategyMethod( request.input.args.strategy, - "validate" + "validate", ); return validateMethod(request, credentials, userId, strategy, true) @@ -604,11 +604,11 @@ export class AuthController extends NativeController { const existsMethod = global.kuzzle.pluginsManager.getStrategyMethod( strategy, - "exists" + "exists", ); return existsMethod(request, userId, strategy).catch((err) => - wrapPluginError(err) + wrapPluginError(err), ); } @@ -627,11 +627,11 @@ export class AuthController extends NativeController { const validateMethod = global.kuzzle.pluginsManager.getStrategyMethod( strategy, - "validate" + "validate", ); return validateMethod(request, credentials, userId, strategy, false).catch( - (err) => wrapPluginError(err) + (err) => wrapPluginError(err), ); } @@ -649,7 +649,7 @@ export class AuthController extends NativeController { const deleteMethod = global.kuzzle.pluginsManager.getStrategyMethod( strategy, - "delete" + "delete", ); return deleteMethod(request, userId, strategy) @@ -675,11 +675,11 @@ export class AuthController extends NativeController { const getInfoMethod = global.kuzzle.pluginsManager.getStrategyMethod( strategy, - "getInfo" + "getInfo", ); return getInfoMethod(request, userId, strategy).catch((err) => - wrapPluginError(err) + wrapPluginError(err), ); } @@ -693,7 +693,7 @@ export class AuthController extends NativeController { "core:security:token:refresh", request.context.user, request.context.token, - request.input.args.expiresIn + request.input.args.expiresIn, ); return this._sendToken(token, request); @@ -706,7 +706,7 @@ export class AuthController extends NativeController { "rights", "unauthorized", request.input.controller, - request.input.action + request.input.action, ); } } @@ -719,7 +719,7 @@ function wrapPluginError(error) { "plugin", "runtime", "unexpected_error", - error.message + error.message, ); } diff --git a/lib/api/controllers/baseController.ts b/lib/api/controllers/baseController.ts index d8bb00faf0..7ca53b30ba 100644 --- a/lib/api/controllers/baseController.ts +++ b/lib/api/controllers/baseController.ts @@ -97,7 +97,7 @@ export class NativeController extends BaseController { throw assertionError.get( "koncorde_restricted_keyword", error.keyword.type, - error.keyword.name + error.keyword.name, ); } } @@ -140,7 +140,7 @@ export class NativeController extends BaseController { */ assertTargetsAreValid( targets: Array<{ index: string; collections?: string[] }>, - { allowEmptyCollections = false } = {} + { allowEmptyCollections = false } = {}, ) { for (let i = 0; i < targets.length; i++) { const target = targets[i]; @@ -150,7 +150,7 @@ export class NativeController extends BaseController { "api", "assert", "missing_argument", - `targets[${i}].index` + `targets[${i}].index`, ); } if (this._hasMultiTargets(target.index)) { @@ -159,7 +159,7 @@ export class NativeController extends BaseController { "storage", "invalid_target_format", `targets[${i}].index`, - target.index + target.index, ); } @@ -168,7 +168,7 @@ export class NativeController extends BaseController { "api", "assert", "missing_argument", - `targets[${i}].collections` + `targets[${i}].collections`, ); } @@ -178,7 +178,7 @@ export class NativeController extends BaseController { "assert", "invalid_type", `targets[${i}].collections`, - "array" + "array", ); } @@ -187,7 +187,7 @@ export class NativeController extends BaseController { "api", "assert", "empty_argument", - `targets[${i}].collections` + `targets[${i}].collections`, ); } @@ -207,7 +207,7 @@ export class NativeController extends BaseController { "assert", "invalid_type", `targets[${i}].collections[${j}]`, - "string" + "string", ); } @@ -217,7 +217,7 @@ export class NativeController extends BaseController { "storage", "invalid_target_format", `targets[${i}].collections[${j}]`, - collection + collection, ); } } diff --git a/lib/api/controllers/bulkController.js b/lib/api/controllers/bulkController.js index 9bb2242f72..11f3c32758 100644 --- a/lib/api/controllers/bulkController.js +++ b/lib/api/controllers/bulkController.js @@ -55,7 +55,7 @@ class BulkController extends NativeController { index, collection, bulkData, - options + options, ); if (strict && errors.length) { @@ -64,7 +64,7 @@ class BulkController extends NativeController { "process", "incomplete_multiple_request", "import", - errors + errors, ); } @@ -92,7 +92,7 @@ class BulkController extends NativeController { collection, id, content, - { injectKuzzleMeta: false, refresh } + { injectKuzzleMeta: false, refresh }, ); if (notify) { @@ -100,7 +100,7 @@ class BulkController extends NativeController { "core:realtime:document:notify", request, actionEnum.WRITE, - result + result, ); } @@ -126,7 +126,7 @@ class BulkController extends NativeController { index, collection, documents, - { injectKuzzleMeta: false, limits: false, refresh } + { injectKuzzleMeta: false, limits: false, refresh }, ); if (strict && errors.length) { @@ -135,7 +135,7 @@ class BulkController extends NativeController { "process", "incomplete_multiple_request", "write", - errors + errors, ); } @@ -146,7 +146,7 @@ class BulkController extends NativeController { "core:realtime:document:mNotify", request, actionEnum.WRITE, - items + items, ); } @@ -178,7 +178,7 @@ class BulkController extends NativeController { index, collection, query, - { fetch: false, refresh, size: -1 } + { fetch: false, refresh, size: -1 }, ); return { deleted }; @@ -202,7 +202,7 @@ class BulkController extends NativeController { collection, query, changes, - { refresh } + { refresh }, ); } } diff --git a/lib/api/controllers/collectionController.js b/lib/api/controllers/collectionController.js index 03f61e201c..9b432f931e 100644 --- a/lib/api/controllers/collectionController.js +++ b/lib/api/controllers/collectionController.js @@ -61,7 +61,7 @@ class CollectionController extends NativeController { async updateMapping(request) { request.addDeprecation( "2.1.0", - 'This action has been deprecated since Kuzzle version 2.1.0. This feature might be removed in a future major version. To update a collection, use this API action instead: "collection:update".' + 'This action has been deprecated since Kuzzle version 2.1.0. This feature might be removed in a future major version. To update a collection, use this API action instead: "collection:update".', ); const { index, collection } = request.getIndexAndCollection(); @@ -71,7 +71,7 @@ class CollectionController extends NativeController { "core:storage:public:mappings:update", index, collection, - mappings + mappings, ); return this._filterMappingResponse(updated); @@ -91,7 +91,7 @@ class CollectionController extends NativeController { "core:storage:public:mappings:get", index, collection, - { includeKuzzleMeta } + { includeKuzzleMeta }, ); return this._filterMappingResponse(mapping); @@ -117,7 +117,7 @@ class CollectionController extends NativeController { "assert", "not_found", index, - collection + collection, ); } @@ -143,7 +143,7 @@ class CollectionController extends NativeController { const { hits, scrollId, total } = await global.kuzzle.internalIndex.search( "validations", searchBody, - { from, scroll: scrollTTL, size } + { from, scroll: scrollTTL, size }, ); return { hits, scrollId, total }; @@ -182,7 +182,7 @@ class CollectionController extends NativeController { index, collection, specifications, - true + true, ); if (!isValid) { @@ -190,7 +190,7 @@ class CollectionController extends NativeController { "validation", "assert", "invalid_specifications", - errors.join("\n\t- ") + errors.join("\n\t- "), ); } @@ -201,7 +201,7 @@ class CollectionController extends NativeController { collection, index, validation: specifications, - } + }, ); await global.kuzzle.internalIndex.refreshCollection("validations"); @@ -279,7 +279,7 @@ class CollectionController extends NativeController { await this.ask( "core:storage:public:collection:truncate", index, - collection + collection, ); return { @@ -302,14 +302,14 @@ class CollectionController extends NativeController { "api", "assert", "invalid_argument", - '"all", "stored", "realtime"' + '"all", "stored", "realtime"', ); } if (request.input.args.type) { request.addDeprecation( "2.10.2", - 'The "type" argument and this route returning a list of realtime collections have both been deprecated since Kuzzle version 2.10.1. This feature might be removed in a future major version. To get a list of realtime collections, use this API action instead: "realtime:list".' + 'The "type" argument and this route returning a list of realtime collections have both been deprecated since Kuzzle version 2.10.1. This feature might be removed in a future major version. To get a list of realtime collections, use this API action instead: "realtime:list".', ); } @@ -323,11 +323,11 @@ class CollectionController extends NativeController { if (type !== "realtime") { const publicCollections = await this.ask( "core:storage:public:collection:list", - index + index, ); collections = collections.concat( - publicCollections.map((name) => ({ name, type: "stored" })) + publicCollections.map((name) => ({ name, type: "stored" })), ); } @@ -369,7 +369,7 @@ class CollectionController extends NativeController { config.mappings = body; request.addDeprecation( "2.1.0", - 'Using "properties", "dynamic" or "_meta" fields in the body has been deprecated since Kuzzle version 2.1.0. This feature might be removed in a future major version. Use "settings" and "mappings" fields instead' + 'Using "properties", "dynamic" or "_meta" fields in the body has been deprecated since Kuzzle version 2.1.0. This feature might be removed in a future major version. Use "settings" and "mappings" fields instead', ); } else { config = body; @@ -379,7 +379,7 @@ class CollectionController extends NativeController { "core:storage:public:collection:create", index, collection, - config + config, ); return { acknowledged: true }; @@ -399,7 +399,7 @@ class CollectionController extends NativeController { "core:storage:public:collection:update", index, collection, - config + config, ); return null; @@ -457,7 +457,7 @@ class CollectionController extends NativeController { response.collections = response.collections.slice( response.from, - response.from + response.size + response.from + response.size, ); } else { response.collections = response.collections.slice(response.from); diff --git a/lib/api/controllers/debugController.ts b/lib/api/controllers/debugController.ts index 7dd5a554aa..f8d435fd4b 100644 --- a/lib/api/controllers/debugController.ts +++ b/lib/api/controllers/debugController.ts @@ -54,7 +54,7 @@ export class DebugController extends NativeController { throw kerror.get( "core", "debugger", - "native_debug_protocol_usage_denied" + "native_debug_protocol_usage_denied", ); } @@ -69,7 +69,7 @@ export class DebugController extends NativeController { throw kerror.get( "core", "debugger", - "native_debug_protocol_usage_denied" + "native_debug_protocol_usage_denied", ); } @@ -85,7 +85,7 @@ export class DebugController extends NativeController { throw kerror.get( "core", "debugger", - "native_debug_protocol_usage_denied" + "native_debug_protocol_usage_denied", ); } @@ -104,7 +104,7 @@ export class DebugController extends NativeController { throw kerror.get( "core", "debugger", - "native_debug_protocol_usage_denied" + "native_debug_protocol_usage_denied", ); } @@ -114,7 +114,7 @@ export class DebugController extends NativeController { "assert", "unsupported_protocol", request.context.connection.protocol, - "debug:addListener" + "debug:addListener", ); } @@ -123,7 +123,7 @@ export class DebugController extends NativeController { await global.kuzzle.ask( "core:debugger:addListener", event, - request.context.connection.id + request.context.connection.id, ); } @@ -135,7 +135,7 @@ export class DebugController extends NativeController { throw kerror.get( "core", "debugger", - "native_debug_protocol_usage_denied" + "native_debug_protocol_usage_denied", ); } @@ -145,7 +145,7 @@ export class DebugController extends NativeController { "assert", "unsupported_protocol", request.context.connection.protocol, - "debug:removeListener" + "debug:removeListener", ); } @@ -154,7 +154,7 @@ export class DebugController extends NativeController { await global.kuzzle.ask( "core:debugger:removeListener", event, - request.context.connection.id + request.context.connection.id, ); } } diff --git a/lib/api/controllers/documentController.js b/lib/api/controllers/documentController.js index 4785609bc0..d11a621e1a 100644 --- a/lib/api/controllers/documentController.js +++ b/lib/api/controllers/documentController.js @@ -93,7 +93,7 @@ class DocumentController extends NativeController { "api", "assert", "missing_argument", - "index, collection or targets" + "index, collection or targets", ); } @@ -105,7 +105,7 @@ class DocumentController extends NativeController { throw kerror.get( "services", "storage", - "invalid_multi_index_collection_usage" + "invalid_multi_index_collection_usage", ); } @@ -128,7 +128,7 @@ class DocumentController extends NativeController { "core:storage:public:document:multiSearch", targets, searchBody, - { from, scroll: scrollTTL, size } + { from, scroll: scrollTTL, size }, ); } else { if (!index) { @@ -144,7 +144,7 @@ class DocumentController extends NativeController { index, collection, searchBody, - { from, scroll: scrollTTL, size } + { from, scroll: scrollTTL, size }, ); } @@ -169,7 +169,7 @@ class DocumentController extends NativeController { const result = await this.ask( "core:storage:public:document:scroll", _scrollId, - { scrollTTL } + { scrollTTL }, ); return { @@ -192,7 +192,7 @@ class DocumentController extends NativeController { "core:storage:public:document:exist", index, collection, - id + id, ); } @@ -219,7 +219,7 @@ class DocumentController extends NativeController { "core:storage:public:document:mExists", index, collection, - ids + ids, ); if (strict && errors.length) { @@ -228,7 +228,7 @@ class DocumentController extends NativeController { "process", "incomplete_multiple_request", "get", - errors + errors, ); } @@ -256,7 +256,7 @@ class DocumentController extends NativeController { "assert", "unsupported_protocol", request.context.connection.protocol, - "document:export" + "document:export", ); } @@ -289,7 +289,7 @@ class DocumentController extends NativeController { scroll: scrollTTL || "5s", separator, size, - } + }, ); } @@ -305,7 +305,7 @@ class DocumentController extends NativeController { "core:storage:public:document:get", index, collection, - id + id, ); return { @@ -341,7 +341,7 @@ class DocumentController extends NativeController { "core:storage:public:document:mGet", index, collection, - ids + ids, ); if (strict && errors.length) { @@ -350,7 +350,7 @@ class DocumentController extends NativeController { "process", "incomplete_multiple_request", "get", - errors + errors, ); } @@ -377,7 +377,7 @@ class DocumentController extends NativeController { "core:storage:public:document:count", index, collection, - searchBody + searchBody, ); return { count }; @@ -409,7 +409,7 @@ class DocumentController extends NativeController { updater: null, }, request, - } + }, ); const created = await this.ask( @@ -425,7 +425,7 @@ class DocumentController extends NativeController { injectKuzzleMeta: false, refresh, userId, - } + }, ); if (!silent) { @@ -433,7 +433,7 @@ class DocumentController extends NativeController { "core:realtime:document:notify", validated, actionEnum.CREATE, - created + created, ); } @@ -467,7 +467,7 @@ class DocumentController extends NativeController { const modifiedRequest = await global.kuzzle.validation.validate( request, - false + false, ); // Add metadata @@ -481,7 +481,7 @@ class DocumentController extends NativeController { updater: userId, }, request, - } + }, ); const response = await this.ask( @@ -497,7 +497,7 @@ class DocumentController extends NativeController { injectKuzzleMeta: false, refresh, userId, - } + }, ); if (!silent) { @@ -505,7 +505,7 @@ class DocumentController extends NativeController { "core:realtime:document:notify", modifiedRequest, actionEnum.WRITE, - response + response, ); } @@ -541,7 +541,7 @@ class DocumentController extends NativeController { const modifiedRequest = await global.kuzzle.validation.validate( request, - false + false, ); // Add metadata @@ -553,7 +553,7 @@ class DocumentController extends NativeController { updater: userId, }, request, - } + }, ); const updatedDocument = await this.ask( @@ -570,7 +570,7 @@ class DocumentController extends NativeController { refresh, retryOnConflict, userId, - } + }, ); const _updatedFields = extractFields(content, { @@ -586,7 +586,7 @@ class DocumentController extends NativeController { _id: updatedDocument._id, _source: updatedDocument._source, _updatedFields, - } + }, ); } @@ -632,7 +632,7 @@ class DocumentController extends NativeController { updater: userId, }, request, - } + }, ); const updatedDocument = await this.ask( @@ -653,7 +653,7 @@ class DocumentController extends NativeController { refresh, retryOnConflict, userId, - } + }, ); if (!silent && updatedDocument.created) { @@ -661,7 +661,7 @@ class DocumentController extends NativeController { "core:realtime:document:notify", request, actionEnum.CREATE, - updatedDocument._source + updatedDocument._source, ); } else if (!silent) { const _updatedFields = extractFields(content, { @@ -676,7 +676,7 @@ class DocumentController extends NativeController { _id: updatedDocument._id, _source: updatedDocument._source, _updatedFields, - } + }, ); } @@ -729,7 +729,7 @@ class DocumentController extends NativeController { const modifiedRequest = await global.kuzzle.validation.validate( request, - false + false, ); // Add metadata @@ -743,7 +743,7 @@ class DocumentController extends NativeController { updater: userId, }, request, - } + }, ); const response = await this.ask( @@ -759,7 +759,7 @@ class DocumentController extends NativeController { injectKuzzleMeta: false, refresh, userId, - } + }, ); if (!silent) { @@ -770,7 +770,7 @@ class DocumentController extends NativeController { { _id: modifiedRequest.input.args._id, _source: modifiedRequest.input.body, - } + }, ); } @@ -805,7 +805,7 @@ class DocumentController extends NativeController { "core:storage:public:document:get", index, collection, - id + id, ); await this.ask( @@ -815,7 +815,7 @@ class DocumentController extends NativeController { id, { refresh, - } + }, ); if (!silent) { @@ -823,7 +823,7 @@ class DocumentController extends NativeController { "core:realtime:document:notify", request, actionEnum.DELETE, - document + document, ); } @@ -849,7 +849,7 @@ class DocumentController extends NativeController { index, collection, ids, - { refresh } + { refresh }, ); if (strict && errors.length) { @@ -858,7 +858,7 @@ class DocumentController extends NativeController { "process", "incomplete_multiple_request", "delete", - errors + errors, ); } @@ -869,7 +869,7 @@ class DocumentController extends NativeController { "core:realtime:document:mNotify", request, actionEnum.DELETE, - documents + documents, ); } @@ -902,7 +902,7 @@ class DocumentController extends NativeController { index, collection, query, - { refresh } + { refresh }, ); if (!silent) { @@ -910,7 +910,7 @@ class DocumentController extends NativeController { "core:realtime:document:mNotify", request, actionEnum.DELETE, - result.documents + result.documents, ); } @@ -944,7 +944,7 @@ class DocumentController extends NativeController { collection, id, fields, - { refresh, userId } + { refresh, userId }, ); if (!silent) { @@ -955,7 +955,7 @@ class DocumentController extends NativeController { { _id: response._id, _source: response._source, - } + }, ); } @@ -995,7 +995,7 @@ class DocumentController extends NativeController { collection, query, changes, - { refresh, userId } + { refresh, userId }, ); if (!silent) { @@ -1009,7 +1009,7 @@ class DocumentController extends NativeController { _updatedFields: extractFields(changes, { fieldsToIgnore: ["_kuzzle_info"], }), - })) + })), ); } @@ -1079,7 +1079,7 @@ class DocumentController extends NativeController { "assert", "unexpected_argument", `documents[${i}]._source`, - `documents[${i}].body` + `documents[${i}].body`, ); } } @@ -1089,7 +1089,7 @@ class DocumentController extends NativeController { index, collection, documents, - { refresh, retryOnConflict, source, userId } + { refresh, retryOnConflict, source, userId }, ); if (strict && response.errors.length) { @@ -1098,7 +1098,7 @@ class DocumentController extends NativeController { "process", "incomplete_multiple_request", methodName, - response.errors + response.errors, ); } @@ -1122,18 +1122,18 @@ class DocumentController extends NativeController { if (!item.created) { item._updatedFields = extractFields( documentsDictionnary[item._id], - { fieldsToIgnore: ["_kuzzle_info"] } + { fieldsToIgnore: ["_kuzzle_info"] }, ); } return item; - }) + }), ); } else if (!silent) { await this.ask( "core:realtime:document:mNotify", request, action, - response.items + response.items, ); } diff --git a/lib/api/controllers/indexController.js b/lib/api/controllers/indexController.js index 10bfe839f6..868b77ec7f 100644 --- a/lib/api/controllers/indexController.js +++ b/lib/api/controllers/indexController.js @@ -53,7 +53,7 @@ class IndexController extends NativeController { const deleted = await this.ask( "core:storage:public:index:mDelete", - allowed + allowed, ); return { deleted }; @@ -109,8 +109,8 @@ class IndexController extends NativeController { this.ask("core:storage:public:collection:list", index).then( (collections) => { response.collections[index] = collections.length; - } - ) + }, + ), ); } @@ -160,7 +160,7 @@ class IndexController extends NativeController { const promises = publicIndexes.map((index) => { const deleteIndexRequest = new Request( { action: "delete", controller: "index", index }, - request.context + request.context, ); return request.context.user diff --git a/lib/api/controllers/memoryStorageController.js b/lib/api/controllers/memoryStorageController.js index e9362ce5a6..7cc2ab3408 100644 --- a/lib/api/controllers/memoryStorageController.js +++ b/lib/api/controllers/memoryStorageController.js @@ -46,7 +46,7 @@ class MemoryStorageController extends NativeController { return async (request) => global.kuzzle.ask( "core:cache:public:mExecute", - extractArgumentsFromRequest(command, request) + extractArgumentsFromRequest(command, request), ); } @@ -57,7 +57,7 @@ class MemoryStorageController extends NativeController { global.kuzzle.ask( "core:cache:public:execute", command, - extractArgumentsFromRequest(command, request) + extractArgumentsFromRequest(command, request), ); } @@ -65,7 +65,7 @@ class MemoryStorageController extends NativeController { global.kuzzle.ask( "core:cache:public:execute", command, - ...extractArgumentsFromRequest(command, request) + ...extractArgumentsFromRequest(command, request), ); }; @@ -172,7 +172,7 @@ function initMapping() { throw kerror.get( "invalid_argument", "points", - "" + "", ); } @@ -271,7 +271,7 @@ function initMapping() { throw kerror.get( "invalid_argument", "entries", - "" + "", ); } @@ -352,7 +352,7 @@ function initMapping() { throw kerror.get( "invalid_argument", "entries", - "" + "", ); } @@ -671,7 +671,7 @@ function extractArgumentsFromRequest(command, request) { } return undefined; }, - request.input + request.input, ); if (value === undefined) { @@ -709,7 +709,7 @@ function extractArgumentsFromRequestForSet(request) { if ( ["undefined", "boolean", "object"].indexOf( - typeof request.input.body.value + typeof request.input.body.value, ) !== -1 ) { throw kerror.get("invalid_type", "value", "string, number"); @@ -780,7 +780,7 @@ function extractArgumentsFromRequestForSort(request) { args.push( "LIMIT", request.input.body.limit[0], - request.input.body.limit[1] + request.input.body.limit[1], ); } @@ -831,7 +831,7 @@ function extractArgumentsFromRequestForMExecute(request) { const subRequest = new Request(command.args); const extractedArguments = extractArgumentsFromRequest( command.action, - subRequest + subRequest, ); return [command.action, ...extractedArguments]; @@ -933,7 +933,7 @@ function extractArgumentsFromRequestForZInterstore(request) { throw kerror.get( "invalid_argument", "aggregate", - '"SUM", "MIN" or "MAX"' + '"SUM", "MIN" or "MAX"', ); } diff --git a/lib/api/controllers/realtimeController.js b/lib/api/controllers/realtimeController.js index f3391a4ddc..fa1bc81316 100644 --- a/lib/api/controllers/realtimeController.js +++ b/lib/api/controllers/realtimeController.js @@ -92,7 +92,7 @@ class RealtimeController extends NativeController { await global.kuzzle.ask( "core:realtime:unsubscribe", request.context.connection.id, - roomId + roomId, ); return { roomId }; diff --git a/lib/api/controllers/securityController.js b/lib/api/controllers/securityController.js index 09212cfe60..5bf0f4f1d1 100644 --- a/lib/api/controllers/securityController.js +++ b/lib/api/controllers/securityController.js @@ -107,7 +107,7 @@ class SecurityController extends NativeController { // @deprecated - helper, will be loosely coupled in the near future this.getStrategyMethod = global.kuzzle.pluginsManager.getStrategyMethod.bind( - global.kuzzle.pluginsManager + global.kuzzle.pluginsManager, ); } @@ -157,7 +157,7 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(creatorId)} applied action "${ request.input.action - }" on user "${userId}."` + }" on user "${userId}."`, ); return apiKey.serialize({ includeToken: true }); } @@ -219,9 +219,8 @@ class SecurityController extends NativeController { * @returns {Promise} */ async getRoleMapping() { - const { properties } = await global.kuzzle.internalIndex.getMapping( - "roles" - ); + const { properties } = + await global.kuzzle.internalIndex.getMapping("roles"); return { mapping: properties }; } @@ -243,9 +242,8 @@ class SecurityController extends NativeController { * @returns {Promise} */ async getProfileMapping() { - const { properties } = await global.kuzzle.internalIndex.getMapping( - "profiles" - ); + const { properties } = + await global.kuzzle.internalIndex.getMapping("profiles"); return { mapping: properties }; } @@ -268,9 +266,8 @@ class SecurityController extends NativeController { * @returns {Promise} */ async getUserMapping() { - const { properties } = await global.kuzzle.internalIndex.getMapping( - "users" - ); + const { properties } = + await global.kuzzle.internalIndex.getMapping("users"); return { mapping: properties }; } @@ -329,7 +326,7 @@ class SecurityController extends NativeController { "assert", "unexpected_argument", collection, - this.securityCollections + this.securityCollections, ); } @@ -352,7 +349,7 @@ class SecurityController extends NativeController { if (body.controllers && body.query) { throw new BadRequestError( - 'You cannot specifify both "controllers" and "query". Prefer the usage of "query" property with a search query.' + 'You cannot specifify both "controllers" and "query". Prefer the usage of "query" property with a search query.', ); } @@ -394,13 +391,13 @@ class SecurityController extends NativeController { force: request.getBoolean("force"), refresh: request.getRefresh("wait_for"), userId, - } + }, ); global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }" on role "${role._id}."` + }" on role "${role._id}."`, ); return formatProcessing.serializeRole(role); } @@ -425,7 +422,7 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }" on role "${role._id}."` + }" on role "${role._id}."`, ); return formatProcessing.serializeRole(role); } @@ -445,8 +442,8 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk( - request.getKuid() - )} applied action "${request.input.action} on role "${id}."` + request.getKuid(), + )} applied action "${request.input.action} on role "${id}."`, ); // @todo This avoids a breaking change... but we should really return @@ -483,7 +480,7 @@ class SecurityController extends NativeController { // search route... return { hits: profiles.map((profile) => - formatProcessing.serializeProfile(profile) + formatProcessing.serializeProfile(profile), ), }; } @@ -510,13 +507,13 @@ class SecurityController extends NativeController { refresh: request.getRefresh("wait_for"), strict: request.getBoolean("strict"), userId, - } + }, ); global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }" on profile "${profile._id}."` + }" on profile "${profile._id}."`, ); return formatProcessing.serializeProfile(profile); @@ -544,13 +541,13 @@ class SecurityController extends NativeController { refresh: request.getRefresh("wait_for"), strict: request.getBoolean("strict"), userId, - } + }, ); global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }" on profile "${profile._id}."` + }" on profile "${profile._id}."`, ); return formatProcessing.serializeProfile(profile); @@ -576,7 +573,7 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }" on profile "${id}."` + }" on profile "${id}."`, ); // @todo - replace by an acknowledgement @@ -597,7 +594,7 @@ class SecurityController extends NativeController { if (body.roles && body.query) { throw new BadRequestError( - 'You cannot specifify both "roles" and "query". Prefer the usage of "query" property with a search query.' + 'You cannot specifify both "roles" and "query". Prefer the usage of "query" property with a search query.', ); } @@ -606,7 +603,7 @@ class SecurityController extends NativeController { request.addDeprecation( "auto-version", - 'Usage of the "roles" property is deprecated. Prefer the usage of "query" property with a search query.' + 'Usage of the "roles" property is deprecated. Prefer the usage of "query" property with a search query.', ); if (roles.length > 0) { @@ -628,7 +625,7 @@ class SecurityController extends NativeController { from, scroll: scrollTTL, size, - } + }, ); response.hits = response.hits.map(formatProcessing.serializeProfile); @@ -687,7 +684,7 @@ class SecurityController extends NativeController { const rights = await profile.getRights(); const hits = Object.keys(rights).reduce( (array, item) => array.concat(rights[item]), - [] + [], ); return { @@ -709,7 +706,7 @@ class SecurityController extends NativeController { const rights = await user.getRights(); const hits = Object.keys(rights).reduce( (array, item) => array.concat(rights[item]), - [] + [], ); return { @@ -741,14 +738,14 @@ class SecurityController extends NativeController { checkPromises.push( existMethod(request, userId, strategy).then((exists) => - exists ? strategy : null - ) + exists ? strategy : null, + ), ); } } const strategies = await Bluebird.all(checkPromises).filter( - (item) => item !== null + (item) => item !== null, ); return { @@ -806,7 +803,7 @@ class SecurityController extends NativeController { "strategy", "missing_optional_method", "search", - strategy + strategy, ); } @@ -833,8 +830,8 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk( - request.getKuid() - )} applied action "${request.input.action}" on user "${id}."` + request.getKuid(), + )} applied action "${request.input.action}" on user "${id}."`, ); return { _id: id }; @@ -869,7 +866,7 @@ class SecurityController extends NativeController { "api", "assert", "forbidden_argument", - "body.content.profileIds" + "body.content.profileIds", ); } @@ -877,7 +874,7 @@ class SecurityController extends NativeController { request, global.kuzzle.config.security.restrictedProfileIds, content, - { humanReadableId } + { humanReadableId }, ); } @@ -945,13 +942,13 @@ class SecurityController extends NativeController { id, profileIds, content, - { refresh: request.getRefresh("wait_for"), userId } + { refresh: request.getRefresh("wait_for"), userId }, ); global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }" on user "${id}."` + }" on user "${id}."`, ); return formatProcessing.serializeUser(user); @@ -978,7 +975,7 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }" on profile "${id}."` + }" on profile "${id}."`, ); return formatProcessing.serializeProfile(updated); } @@ -1004,7 +1001,7 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }" on role "${id}."` + }" on role "${id}."`, ); return formatProcessing.serializeRole(updated); @@ -1018,7 +1015,7 @@ class SecurityController extends NativeController { */ async createFirstAdmin(request) { const adminExists = await global.kuzzle.ask( - "core:security:user:admin:exist" + "core:security:user:admin:exist", ); if (adminExists) { @@ -1035,7 +1032,7 @@ class SecurityController extends NativeController { "api", "assert", "forbidden_argument", - "body.content.profileIds" + "body.content.profileIds", ); } @@ -1051,7 +1048,7 @@ class SecurityController extends NativeController { this.ask(`core:security:${type}:createOrReplace`, name, value, { refresh: "wait_for", userId, - }) + }), ); } } @@ -1059,7 +1056,7 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }".` + }".`, ); return user; @@ -1151,8 +1148,8 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk( - request.getKuid() - )} applied action "${request.input.action}" on user "${id}."` + request.getKuid(), + )} applied action "${request.input.action}" on user "${id}."`, ); return createMethod(request, body, id, strategy); } @@ -1179,8 +1176,8 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk( - request.getKuid() - )} applied action "${request.input.action}" on user "${id}."` + request.getKuid(), + )} applied action "${request.input.action}" on user "${id}."`, ); return updateMethod(request, body, id, strategy); @@ -1217,7 +1214,7 @@ class SecurityController extends NativeController { request.getBody(), request.getId({ ifMissing: "ignore" }), strategy, - false + false, ); } @@ -1237,8 +1234,8 @@ class SecurityController extends NativeController { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk( - request.getKuid() - )} applied action "${request.input.action}" on user "${id}."` + request.getKuid(), + )} applied action "${request.input.action}" on user "${id}."`, ); return { acknowledged: true }; @@ -1340,28 +1337,28 @@ class SecurityController extends NativeController { await Bluebird.map(ids, (id) => this.ask(`core:security:${type}:delete`, id, { refresh }) .then(() => successes.push(id)) - .catch((err) => errors.push(err)) + .catch((err) => errors.push(err)), ); if (errors.length) { request.setError( - kerror.get("services", "storage", "incomplete_delete", errors) + kerror.get("services", "storage", "incomplete_delete", errors), ); } if (successes.length > 1000) { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk( - request.getKuid() + request.getKuid(), )} deleted the following ${type}s: ${successes .slice(0, 1000) - .join(", ")}... (${successes.length - 1000} more users deleted)."` + .join(", ")}... (${successes.length - 1000} more users deleted)."`, ); } else { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk( - request.getKuid() - )} deleted the following ${type}s: ${successes.join(", ")}."` + request.getKuid(), + )} deleted the following ${type}s: ${successes.join(", ")}."`, ); } @@ -1382,13 +1379,13 @@ class SecurityController extends NativeController { refresh: request.getRefresh("wait_for"), retryOnConflict: request.getInteger("retryOnConflict", 10), userId, - } + }, ); global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk(userId)} applied action "${ request.input.action - }" on user "${id}."` + }" on user "${id}."`, ); return formatProcessing.serializeUser(updated); @@ -1403,7 +1400,7 @@ class SecurityController extends NativeController { request, profileIds, content, - { humanReadableId = true } = {} + { humanReadableId = true } = {}, ) { const credentials = request.getBodyObject("credentials", {}); const strategies = Object.keys(credentials); @@ -1431,7 +1428,7 @@ class SecurityController extends NativeController { "security", "credentials", "unknown_strategy", - strategy + strategy, ); } @@ -1446,7 +1443,7 @@ class SecurityController extends NativeController { "security", "credentials", "database_inconsistency", - id + id, ); } } @@ -1457,7 +1454,7 @@ class SecurityController extends NativeController { id, profileIds, content, - { refresh: request.getRefresh("wait_for") } + { refresh: request.getRefresh("wait_for") }, ); const createdUser = formatProcessing.serializeUser(user); @@ -1490,8 +1487,8 @@ class SecurityController extends NativeController { if (creationFailure === null) { global.kuzzle.log.info( `[SECURITY] ${SecurityController.userOrSdk( - request.getKuid() - )} applied action "${request.input.action}" on user "${id}."` + request.getKuid(), + )} applied action "${request.input.action}" on user "${id}."`, ); return createdUser; } @@ -1524,7 +1521,7 @@ class SecurityController extends NativeController { [ creationFailure.error.message, ...deletionErrors.map((e) => e.message), - ].join("\n") + ].join("\n"), ); } @@ -1538,7 +1535,7 @@ class SecurityController extends NativeController { "security", "credentials", "rejected", - creationFailure.error.message + creationFailure.error.message, ); } @@ -1547,7 +1544,7 @@ class SecurityController extends NativeController { "plugin", "runtime", "unexpected_error", - creationFailure.error.message + creationFailure.error.message, ); } @@ -1560,7 +1557,7 @@ class SecurityController extends NativeController { _getSearchPageSize(request) { const size = request.getInteger( "size", - global.kuzzle.config.limits.documentsFetchCount + global.kuzzle.config.limits.documentsFetchCount, ); this.assertNotExceedMaxFetch(size); diff --git a/lib/api/controllers/serverController.js b/lib/api/controllers/serverController.js index a005024dc8..d3f14d7aa6 100644 --- a/lib/api/controllers/serverController.js +++ b/lib/api/controllers/serverController.js @@ -214,7 +214,7 @@ class ServerController extends NativeController { if (!services || services.includes("storageEngine")) { try { const response = await global.kuzzle.ask( - "core:storage:public:info:get" + "core:storage:public:info:get", ); if (response.status !== "yellow" && response.status !== "green") { @@ -259,11 +259,11 @@ class ServerController extends NativeController { const kuzzleApi = this._buildApiDefinition( global.kuzzle.funnel.controllers, - global.kuzzle.config.http.routes + global.kuzzle.config.http.routes, ); const pluginsApi = this._buildApiDefinition( global.kuzzle.pluginsManager.controllers, - global.kuzzle.pluginsManager.routes + global.kuzzle.pluginsManager.routes, ); const apiDefinition = Object.assign({}, kuzzleApi, pluginsApi); @@ -291,11 +291,11 @@ class ServerController extends NativeController { async publicApi() { const kuzzleApi = this._buildApiDefinition( global.kuzzle.funnel.controllers, - global.kuzzle.config.http.routes + global.kuzzle.config.http.routes, ); const pluginsApi = this._buildApiDefinition( global.kuzzle.pluginsManager.controllers, - global.kuzzle.pluginsManager.routes + global.kuzzle.pluginsManager.routes, ); return { ...kuzzleApi, ...pluginsApi }; diff --git a/lib/api/documentExtractor.js b/lib/api/documentExtractor.js index b18c5b660e..111e67f759 100644 --- a/lib/api/documentExtractor.js +++ b/lib/api/documentExtractor.js @@ -82,7 +82,7 @@ const extractors = [ throw assertionError.get( "invalid_type", request.input.args.ids, - "Array or String" + "Array or String", ); } } @@ -118,7 +118,7 @@ const extractors = [ }, { status: request.status, - } + }, ); return request; @@ -284,7 +284,7 @@ class DocumentExtractor { "core", "fatal", "assertion_failed", - `no generic documents extractor for ${request.input.action}` + `no generic documents extractor for ${request.input.action}`, ); } diff --git a/lib/api/funnel.js b/lib/api/funnel.js index 8ed969fe54..f0539ab6be 100644 --- a/lib/api/funnel.js +++ b/lib/api/funnel.js @@ -101,7 +101,7 @@ class Funnel { * @returns {Boolean} */ global.kuzzle.onAsk("kuzzle:api:funnel:controller:isNative", (name) => - this.isNativeController(name) + this.isNativeController(name), ); /** @@ -129,7 +129,7 @@ class Funnel { this.controllers.set("ms", msController); const initPromises = Array.from(this.controllers.keys()).map((ctrl) => - this.controllers.get(ctrl).init() + this.controllers.get(ctrl).init(), ); return Bluebird.all(initPromises); @@ -183,7 +183,7 @@ class Funnel { const isRequestFromDebugSession = get( request, "context.connection.misc.internal.debugSession", - false + false, ); if (this.overloaded) { @@ -197,11 +197,11 @@ class Funnel { const overloadPercentage = Math.round( (10000 * this.pendingRequestsQueue.length) / - global.kuzzle.config.limits.requestsBufferSize + global.kuzzle.config.limits.requestsBufferSize, ) / 100; global.kuzzle.emit("core:overload", overloadPercentage); global.kuzzle.log.warn( - `[!WARNING!] Kuzzle overloaded: ${overloadPercentage}%. Delaying requests...` + `[!WARNING!] Kuzzle overloaded: ${overloadPercentage}%. Delaying requests...`, ); this.overloadWarned = true; @@ -245,7 +245,7 @@ class Funnel { if (!this.pendingRequestsById.has(request.internalId)) { this.pendingRequestsById.set( request.internalId, - new PendingRequest(request, fn, context) + new PendingRequest(request, fn, context), ); if (isRequestFromDebugSession) { @@ -291,7 +291,7 @@ class Funnel { if (!request.input.controller || !request.input.controller.length) { callback( kerror.get("api", "assert", "missing_argument", "controller"), - request + request, ); return 1; } @@ -299,7 +299,7 @@ class Funnel { if (!request.input.action || !request.input.action.length) { callback( kerror.get("api", "assert", "missing_argument", "action"), - request + request, ); return 1; } @@ -320,9 +320,9 @@ class Funnel { "assert", "mutually_exclusive", "index, collection", - "targets" + "targets", ), - request + request, ); return 1; } @@ -334,18 +334,18 @@ class Funnel { ) { debug( "Reject request, unauthorized origin %s", - request.input.headers.origin + request.input.headers.origin, ); return this._executeError( kerror.get( "api", "process", "unauthorized_origin", - request.input.headers.origin + request.input.headers.origin, ), request, true, - callback + callback, ); } @@ -365,7 +365,7 @@ class Funnel { req.input.controller, req.input.action, req.id, - req.input + req.input, ); global.kuzzle.asyncStore.run(() => { @@ -397,7 +397,7 @@ class Funnel { debug( "Request %s successfully executed. Result: %a", modifiedRequest.id, - processResult + processResult, ); return global.kuzzle @@ -418,7 +418,7 @@ class Funnel { debug( "Error processing request %s: %a", modifiedRequest.id, - err + err, ); return global.kuzzle .pipe("request:afterExecution", { @@ -431,8 +431,8 @@ class Funnel { pipeEvent.error, pipeEvent.request, true, - callback - ) + callback, + ), ); }); }) @@ -449,14 +449,14 @@ class Funnel { pipeEvent.error, pipeEvent.request, true, - callback - ) + callback, + ), ); }); }); }, this, - request + request, ); return executing ? 0 : -1; @@ -489,7 +489,7 @@ class Funnel { global.kuzzle.log.error( err instanceof Error && !(err instanceof KuzzleError) ? `${err.message}\n${err.stack}` - : err + : err, ); if ( @@ -511,7 +511,7 @@ class Funnel { .join("-"); global.kuzzle.dump( - `handled-${errorType.toLocaleLowerCase()}-${errorMessage}` + `handled-${errorType.toLocaleLowerCase()}-${errorMessage}`, ); } @@ -559,7 +559,7 @@ class Funnel { "security", "token", "verification_error", - "Both token and cookie are present, could not decide which one to use" + "Both token and cookie are present, could not decide which one to use", ); } @@ -579,7 +579,7 @@ class Funnel { request.context.token = await global.kuzzle.ask( "core:security:token:verify", - token + token, ); } catch (error) { await global.kuzzle.pipe("request:onUnauthorized", request); @@ -590,19 +590,19 @@ class Funnel { request.context.user = await global.kuzzle.ask( "core:security:user:get", - userId + userId, ); // If we have a token, link the connection with the token, // this way the connection can be notified when the token has expired. if ( global.kuzzle.config.internal.notifiableProtocols.includes( - request.context.connection.protocol + request.context.connection.protocol, ) ) { global.kuzzle.tokenManager.link( request.context.token, - request.context.connection.id + request.context.connection.id, ); } @@ -615,7 +615,7 @@ class Funnel { userId === "-1" ? "unauthorized" : "forbidden", request.input.controller, request.input.action, - request.context.user._id + request.context.user._id, ); request.setError(error); @@ -662,7 +662,7 @@ class Funnel { _request = await this.performDocumentAlias(_request, "before"); _request = await global.kuzzle.pipe( this.getEventName(_request, "before"), - _request + _request, ); const responseData = await doAction(controller, _request); @@ -688,7 +688,7 @@ class Funnel { _request = await global.kuzzle.pipe( this.getEventName(_request, "after"), - _request + _request, ); _request = await this.performDocumentAlias(_request, "after"); @@ -727,14 +727,14 @@ class Funnel { const alias = this.documentEventAliases.mirrorList[action]; const event = `${this.documentEventAliases.namespace}:${prefix}${capitalize( - alias + alias, )}`; const extractor = new DocumentExtractor(request); const documents = await global.kuzzle.pipe( event, extractor.extract(), - request + request, ); return extractor.insert(documents); @@ -767,7 +767,7 @@ class Funnel { try { const updated = await global.kuzzle.pipe( this.getEventName(modifiedRequest, "error"), - modifiedRequest + modifiedRequest, ); // If there is no pipe attached on this event, the same request is @@ -788,7 +788,7 @@ class Funnel { try { const updated = await global.kuzzle.pipe( "request:onError", - modifiedRequest + modifiedRequest, ); if (updated === modifiedRequest) { @@ -849,7 +849,7 @@ class Funnel { throw processError.get( "action_not_found", request.input.controller, - request.input.action + request.input.action, ); } } @@ -899,7 +899,7 @@ class Funnel { throw processError.get( "incompatible_sdk_version", sdkVersion, - "Kuzzle v2" + "Kuzzle v2", ); } @@ -960,13 +960,13 @@ class Funnel { // If there is room to play bufferized requests, do it now. If not, retry later const quantityToInject = Math.min( this.pendingRequestsQueue.length, - global.kuzzle.config.limits.concurrentRequests - this.concurrentRequests + global.kuzzle.config.limits.concurrentRequests - this.concurrentRequests, ); if (quantityToInject > 0) { for (let i = 0; i < quantityToInject; i++) { const pendingItem = this.pendingRequestsById.get( - this.pendingRequestsQueue.peekFront() + this.pendingRequestsQueue.peekFront(), ); try { @@ -974,7 +974,7 @@ class Funnel { this.throttle( pendingItem.fn, pendingItem.context, - pendingItem.request + pendingItem.request, ) ) { this.pendingRequestsQueue.shift(); @@ -1000,7 +1000,7 @@ class Funnel { ) { this.overloadWarned = false; global.kuzzle.log.info( - "End of overloaded state. Resuming normal activity." + "End of overloaded state. Resuming normal activity.", ); this.lastOverloadTime = now; } @@ -1020,7 +1020,7 @@ class Funnel { "plugin", "runtime", "unexpected_error", - error.message + error.message, ); } @@ -1084,7 +1084,7 @@ function doAction(controller, request) { "controller", "invalid_action_response", request.input.controller, - request.input.action + request.input.action, ); } diff --git a/lib/api/openapi/OpenApiManager.ts b/lib/api/openapi/OpenApiManager.ts index a81d1f4af7..a7cfb54be3 100644 --- a/lib/api/openapi/OpenApiManager.ts +++ b/lib/api/openapi/OpenApiManager.ts @@ -108,7 +108,7 @@ export class OpenApiManager { constructor( applicationDefinition: OpenApiDefinition, kuzzleRoutes: any[], - pluginsRoutes: any[] + pluginsRoutes: any[], ) { this.applicationDefinition = applicationDefinition; @@ -124,7 +124,7 @@ export class OpenApiManager { global.kuzzle.onAsk( "core:api:openapi:app", - () => this.applicationDefinition + () => this.applicationDefinition, ); } } diff --git a/lib/api/openapi/components/document/index.ts b/lib/api/openapi/components/document/index.ts index 09eaefeec2..b158387c40 100644 --- a/lib/api/openapi/components/document/index.ts +++ b/lib/api/openapi/components/document/index.ts @@ -74,7 +74,7 @@ export const OpenApiDocumentValidateComponent = // reading the description of the mCreateOrReplace action in the controller document. // The yaml objects are then stored in the variables below const mCreateOrReplaceObject = readYamlFile( - __dirname + "/mCreateOrReplace.yaml" + __dirname + "/mCreateOrReplace.yaml", ); export const OpenApiDocumentmCreateOrReplace = mCreateOrReplaceObject.DocumentmCreateOrReplace; diff --git a/lib/api/openapi/components/index.ts b/lib/api/openapi/components/index.ts index d03b6fcf31..c9c903bb3b 100644 --- a/lib/api/openapi/components/index.ts +++ b/lib/api/openapi/components/index.ts @@ -5,5 +5,5 @@ export * from "./security"; // Document definitions (reusable object for KuzzleRequest and KuzzleResponse) export const OpenApiPayloadsDefinitions = readYamlFile( - __dirname + "/payloads.yaml" + __dirname + "/payloads.yaml", ).definitions; diff --git a/lib/api/openapi/openApiGenerator.ts b/lib/api/openapi/openApiGenerator.ts index 0c1695b3cf..691144ace6 100644 --- a/lib/api/openapi/openApiGenerator.ts +++ b/lib/api/openapi/openApiGenerator.ts @@ -110,7 +110,7 @@ function generateResponse(route: JSONObject) { */ export function generateOpenApi( routes: JSONObject[], - definition: JSONObject + definition: JSONObject, ): JSONObject { for (const route of routes) { // Make sure route verbs are lowercase diff --git a/lib/api/rateLimiter.js b/lib/api/rateLimiter.js index cacbe8b918..9a4cc69a75 100644 --- a/lib/api/rateLimiter.js +++ b/lib/api/rateLimiter.js @@ -62,7 +62,7 @@ class RateLimiter { const profiles = await global.kuzzle.ask( "core:security:profile:mGet", - profileIds + profileIds, ); for (let i = 0; i < profiles.length; i++) { diff --git a/lib/api/request/kuzzleRequest.ts b/lib/api/request/kuzzleRequest.ts index 4691160ea5..029bdc4dd1 100644 --- a/lib/api/request/kuzzleRequest.ts +++ b/lib/api/request/kuzzleRequest.ts @@ -107,11 +107,11 @@ export class KuzzleRequest { } else { const error = new KuzzleError( options.error.message, - options.error.status || 500 + options.error.status || 500, ); for (const prop of Object.keys(options.error).filter( - (key) => key !== "message" && key !== "status" + (key) => key !== "message" && key !== "status", )) { error[prop] = options.error[prop]; } @@ -205,7 +205,7 @@ export class KuzzleRequest { setError(error: Error) { if (!error || !(error instanceof Error)) { throw new InternalError( - "Cannot set non-error object as a request's error" + "Cannot set non-error object as a request's error", ); } @@ -248,7 +248,7 @@ export class KuzzleRequest { * Returns directly the result instead of wrapping it in a Kuzzle response */ raw?: boolean; - } = {} + } = {}, ) { if (result instanceof Error) { throw new InternalError("cannot set an error as a request's response"); @@ -396,7 +396,7 @@ export class KuzzleRequest { "assert", "invalid_argument", "lang", - '"elasticsearch" or "koncorde"' + '"elasticsearch" or "koncorde"', ); } @@ -538,7 +538,7 @@ export class KuzzleRequest { */ getBodyObject( name: string, - def: JSONObject | undefined = undefined + def: JSONObject | undefined = undefined, ): JSONObject { const body = this.input.body; @@ -804,7 +804,7 @@ export class KuzzleRequest { options: { ifMissing?: "error" | "generate" | "ignore"; generator?: () => string; - } = { generator: uuid.v4, ifMissing: "error" } + } = { generator: uuid.v4, ifMissing: "error" }, ): string { const id = this.input.args._id; @@ -943,7 +943,7 @@ export class KuzzleRequest { * Gets the refresh value. */ getRefresh( - defaultValue: "false" | "wait_for" = "false" + defaultValue: "false" | "wait_for" = "false", ): "false" | "wait_for" { if (this.input.args.refresh === undefined) { return defaultValue; @@ -985,7 +985,7 @@ export class KuzzleRequest { obj: JSONObject, name: string, errorName: string, - querystring = false + querystring = false, ): boolean { let value = get(obj, name); @@ -1019,7 +1019,7 @@ export class KuzzleRequest { obj: JSONObject, name: string, errorName: string, - def: number | undefined = undefined + def: number | undefined = undefined, ): number { let value = get(obj, name, def); @@ -1048,7 +1048,7 @@ export class KuzzleRequest { obj: JSONObject, name: string, errorName: string, - def: number | undefined = undefined + def: number | undefined = undefined, ): number { let value = get(obj, name, def); @@ -1077,7 +1077,7 @@ export class KuzzleRequest { obj: JSONObject, name: string, errorName: string, - def: string | undefined = undefined + def: string | undefined = undefined, ): string { const value = get(obj, name, def); @@ -1105,7 +1105,7 @@ export class KuzzleRequest { name: string, errorName: string, def: [] | undefined = undefined, - querystring = false + querystring = false, ): any[] { const value = get(obj, name, def); @@ -1154,7 +1154,7 @@ export class KuzzleRequest { name: string, errorName: string, def: JSONObject | undefined = undefined, - querystring = false + querystring = false, ): JSONObject { const value = get(obj, name, def); diff --git a/lib/api/request/requestResponse.ts b/lib/api/request/requestResponse.ts index bb95c95eba..ed9e01e71d 100644 --- a/lib/api/request/requestResponse.ts +++ b/lib/api/request/requestResponse.ts @@ -283,7 +283,7 @@ export class RequestResponse { headers?: JSONObject; status?: number; format?: "standard" | "raw"; - } = {} + } = {}, ): void { if (options.headers) { this.setHeaders(options.headers); diff --git a/lib/cluster/command.js b/lib/cluster/command.js index 7d58ebd9e3..2c98ab7706 100644 --- a/lib/cluster/command.js +++ b/lib/cluster/command.js @@ -140,7 +140,7 @@ class ClusterCommand { async handleHandshake(data) { const decoder = this.protoroot.lookupType("HandshakeRequest"); const { nodeId, ip, lastMessageId } = decoder.toObject( - decoder.decode(data) + decoder.decode(data), ); const added = await this.node.addNode(nodeId, ip, lastMessageId); @@ -189,7 +189,7 @@ class ClusterCommand { // no response from the remote node in a timely fashion... retrying // with another one global.kuzzle.log.warn( - `Unable to fetch a full state from node ${id} (no response received)` + `Unable to fetch a full state from node ${id} (no response received)`, ); idx = (idx + 1) % nodes.length; } finally { @@ -229,7 +229,7 @@ class ClusterCommand { const encoded = encoder.encode(encoder.create(payload)).finish(); const responses = await Bluebird.map(nodes, ({ id, ip }) => - this._sendSingleHandshake(id, ip, encoded) + this._sendSingleHandshake(id, ip, encoded), ); const decoder = this.protoroot.lookupType("HandshakeResponse"); @@ -270,7 +270,7 @@ class ClusterCommand { [, response] = await req.receive(); } catch (e) { global.kuzzle.log.warn( - `Couldn't complete handshake with node ${id}: no response received` + `Couldn't complete handshake with node ${id}: no response received`, ); } finally { req.close(); diff --git a/lib/cluster/idCardHandler.ts b/lib/cluster/idCardHandler.ts index 1eb32be50f..39ba9059e7 100644 --- a/lib/cluster/idCardHandler.ts +++ b/lib/cluster/idCardHandler.ts @@ -172,7 +172,7 @@ export class ClusterIdCardHandler { await this.addIdCardToIndex(); this.refreshWorker = this.constructWorker( - `${__dirname}/workers/IDCardRenewer.js` + `${__dirname}/workers/IDCardRenewer.js`, ); this.refreshWorker.on("message", async (message: JSONObject) => { @@ -243,7 +243,7 @@ export class ClusterIdCardHandler { await this.save(); } catch (error) { global.kuzzle.log.error( - `An error occurred while refreshing the ID card during WorkerThread startup: ${error}` + `An error occurred while refreshing the ID card during WorkerThread startup: ${error}`, ); } }, this.refreshDelay * this.refreshMultiplier); @@ -255,7 +255,7 @@ export class ClusterIdCardHandler { clearInterval(this.refreshTimer); this.refreshTimer = null; } - } + }, ); } @@ -303,7 +303,7 @@ export class ClusterIdCardHandler { let keys: string[] = await global.kuzzle.ask( "core:cache:internal:execute", "smembers", - REDIS_ID_CARDS_INDEX + REDIS_ID_CARDS_INDEX, ); keys = keys.filter((nodeIdKey) => nodeIdKey !== this.nodeIdKey); @@ -314,7 +314,7 @@ export class ClusterIdCardHandler { const rawIdCards: string[] = await global.kuzzle.ask( "core:cache:internal:mget", - keys + keys, ); const expiredIdCards: string[] = []; @@ -334,7 +334,7 @@ export class ClusterIdCardHandler { "core:cache:internal:execute", "srem", REDIS_ID_CARDS_INDEX, - idCardKey + idCardKey, ); }); @@ -373,7 +373,7 @@ export class ClusterIdCardHandler { "core:cache:internal:execute", "sadd", REDIS_ID_CARDS_INDEX, - this.nodeIdKey + this.nodeIdKey, ); } @@ -387,11 +387,11 @@ export class ClusterIdCardHandler { return false; } - return await global.kuzzle.ask( + return global.kuzzle.ask( "core:cache:internal:store", this.nodeIdKey, JSON.stringify(this.idCard.serialize()), - { onlyIfNew: creation, ttl: this.refreshDelay * this.refreshMultiplier } + { onlyIfNew: creation, ttl: this.refreshDelay * this.refreshMultiplier }, ); } } diff --git a/lib/cluster/node.js b/lib/cluster/node.js index e91014e290..f8c6296423 100644 --- a/lib/cluster/node.js +++ b/lib/cluster/node.js @@ -170,7 +170,7 @@ class ClusterNode { debug("Found IP address: %s with config %o", this.ip, this.config); assert( this.ip !== null, - `[CLUSTER] No suitable IP address found with the provided configuration (family: ${family}, interface: ${this.config.interface}, ip: ${this.config.ip})` + `[CLUSTER] No suitable IP address found with the provided configuration (family: ${family}, interface: ${this.config.interface}, ip: ${this.config.ip})`, ); this.nodeId = null; @@ -220,7 +220,7 @@ class ClusterNode { if (this.countActiveNodes() < this.config.minimumNodes) { global.kuzzle.log.info( - "[CLUSTER] Not enough nodes active. Waiting for other nodes to join the cluster..." + "[CLUSTER] Not enough nodes active. Waiting for other nodes to join the cluster...", ); while (this.countActiveNodes() < this.config.minimumNodes) { @@ -295,7 +295,7 @@ class ClusterNode { ) { global.kuzzle.state = kuzzleStateEnum.RUNNING; global.kuzzle.log.warn( - `[CLUSTER] Minimum number of nodes reached (${this.countActiveNodes()}). This node is now accepting requests again.` + `[CLUSTER] Minimum number of nodes reached (${this.countActiveNodes()}). This node is now accepting requests again.`, ); } @@ -336,13 +336,13 @@ class ClusterNode { } global.kuzzle.log.warn( - `[CLUSTER] Node "${nodeId}" evicted. Reason: ${reason}` + `[CLUSTER] Node "${nodeId}" evicted. Reason: ${reason}`, ); this.trackActivity( nodeId, subscriber.remoteNodeIP, nodeActivityEnum.EVICTED, - reason + reason, ); await this.idCardHandler.removeNode(nodeId); @@ -359,7 +359,7 @@ class ClusterNode { global.kuzzle.log.warn( `[CLUSTER] Not enough nodes active (expected: ${ this.config.minimumNodes - }, active: ${this.countActiveNodes()}). Deactivating node until new ones are added.` + }, active: ${this.countActiveNodes()}). Deactivating node until new ones are added.`, ); } @@ -423,12 +423,12 @@ class ClusterNode { // First remove every non existing node from topologies splits = splits.map((topology) => - topology.filter((nodeId) => idCards.find((card) => card.id === nodeId)) + topology.filter((nodeId) => idCards.find((card) => card.id === nodeId)), ); splits = splits.sort((a, b) => a.length - b.length); const eligibleSplits = splits.filter( - (split) => split.length === splits[0].length + (split) => split.length === splits[0].length, ); let candidates; @@ -472,7 +472,7 @@ class ClusterNode { if (candidates.includes(this.nodeId)) { global.kuzzle.log.error( - "[CLUSTER] Network split detected. This node is outside the cluster: shutting down." + "[CLUSTER] Network split detected. This node is outside the cluster: shutting down.", ); this.shutdownNode(); return; @@ -482,7 +482,7 @@ class ClusterNode { await this.enforceClusterConsistency(); } catch (err) { global.kuzzle.log.error( - "[CLUSTER] Unexpected exception caught during a cluster consistency check. Shutting down..." + "[CLUSTER] Unexpected exception caught during a cluster consistency check. Shutting down...", ); global.kuzzle.log.error(err.stack); this.shutdownNode(); @@ -499,7 +499,7 @@ class ClusterNode { async handshake() { const handshakeTimeout = setTimeout(() => { global.kuzzle.log.error( - `[CLUSTER] Failed to join the cluster: timed out (joinTimeout: ${this.config.joinTimeout}ms)` + `[CLUSTER] Failed to join the cluster: timed out (joinTimeout: ${this.config.joinTimeout}ms)`, ); this.shutdownNode(); }, this.config.joinTimeout); @@ -542,7 +542,7 @@ class ClusterNode { if (duplicate.length > 0) { global.kuzzle.log.error( - `[CLUSTER] Another node share the same IP address as this one (${this.ip}): ${duplicate[0].id}. Shutting down.` + `[CLUSTER] Another node share the same IP address as this one (${this.ip}): ${duplicate[0].id}. Shutting down.`, ); this.shutdownNode(); return; @@ -566,7 +566,7 @@ class ClusterNode { if (fullState === null) { if (retried) { global.kuzzle.log.error( - "[CLUSTER] Could not connect to discovered cluster nodes (network split detected). Shutting down." + "[CLUSTER] Could not connect to discovered cluster nodes (network split detected). Shutting down.", ); this.shutdownNode(); return; @@ -582,7 +582,7 @@ class ClusterNode { retried = true; const retryDelay = this.heartbeatDelay * 1.5; global.kuzzle.log.warn( - `[CLUSTER] Unable to connect to discovered cluster nodes. Retrying in ${retryDelay}ms...` + `[CLUSTER] Unable to connect to discovered cluster nodes. Retrying in ${retryDelay}ms...`, ); await Bluebird.delay(retryDelay); } @@ -601,7 +601,7 @@ class ClusterNode { // Update subscribers: start synchronizing, or unsubscribes from nodes who // didn't respond for (const [nodeId, handshakeData] of Object.entries( - handshakeResponses + handshakeResponses, )) { const subscriber = this.remoteNodes.get(nodeId); if (handshakeData === null) { @@ -612,10 +612,10 @@ class ClusterNode { const nodesStates = fullState.nodesState || []; const nodeStatus = nodesStates.find((node) => node.id === nodeId); subscriber.sync( - nodeStatus ? nodeStatus.lastMessageId : handshakeData.lastMessageId + nodeStatus ? nodeStatus.lastMessageId : handshakeData.lastMessageId, ); global.kuzzle.log.info( - `[CLUSTER] Successfully completed the handshake with node ${nodeId}` + `[CLUSTER] Successfully completed the handshake with node ${nodeId}`, ); } } @@ -708,7 +708,7 @@ class ClusterNode { * @return {void} */ global.kuzzle.onAsk("cluster:realtime:room:remove", (roomId) => - this.removeRealtimeRoom(roomId) + this.removeRealtimeRoom(roomId), ); /** @@ -719,7 +719,7 @@ class ClusterNode { * @returns {Number} */ global.kuzzle.onAsk("cluster:realtime:room:count", (roomId) => - this.countRealtimeSubscribers(roomId) + this.countRealtimeSubscribers(roomId), ); /** @@ -728,7 +728,7 @@ class ClusterNode { * @returns {Object} */ global.kuzzle.onAsk("cluster:realtime:room:list", () => - this.fullState.listRealtimeRooms() + this.fullState.listRealtimeRooms(), ); /** @@ -739,7 +739,7 @@ class ClusterNode { * @returns {NormalizedFilter} */ global.kuzzle.onAsk("cluster:realtime:filters:get", (roomId) => - this.fullState.getNormalizedFilters(roomId) + this.fullState.getNormalizedFilters(roomId), ); /** @@ -749,7 +749,7 @@ class ClusterNode { * @param {Object} payload - event payload */ global.kuzzle.onAsk("cluster:event:broadcast", (event, payload) => - this.broadcast(event, payload) + this.broadcast(event, payload), ); /** @@ -759,7 +759,7 @@ class ClusterNode { * @param {Function} fn - event listener */ global.kuzzle.onAsk("cluster:event:on", (event, fn) => - this.eventEmitter.on(event, fn) + this.eventEmitter.on(event, fn), ); /** @@ -769,7 +769,7 @@ class ClusterNode { * @param {Function} fn - event listener */ global.kuzzle.onAsk("cluster:event:once", (event, fn) => - this.eventEmitter.once(event, fn) + this.eventEmitter.once(event, fn), ); /** @@ -779,7 +779,7 @@ class ClusterNode { * @param {Function} fn - event listener */ global.kuzzle.onAsk("cluster:event:off", (event, fn) => - this.eventEmitter.removeListener(event, fn) + this.eventEmitter.removeListener(event, fn), ); /** @@ -788,7 +788,7 @@ class ClusterNode { * @param {string} event name */ global.kuzzle.onAsk("cluster:event:removeAllListeners", (event) => - this.eventEmitter.removeAllListeners(event) + this.eventEmitter.removeAllListeners(event), ); /** @@ -804,19 +804,19 @@ class ClusterNode { */ registerEvents() { global.kuzzle.on("admin:afterRefreshIndexCache", () => - this.onIndexCacheRefreshed() + this.onIndexCacheRefreshed(), ); global.kuzzle.onCall("core:realtime:room:create:after", (payload) => - this.onNewRealtimeRoom(payload) + this.onNewRealtimeRoom(payload), ); global.kuzzle.onCall("core:realtime:subscribe:after", (roomId) => - this.onNewSubscription(roomId) + this.onNewSubscription(roomId), ); global.kuzzle.onCall("core:realtime:unsubscribe:after", (roomId) => - this.onUnsubscription(roomId) + this.onUnsubscription(roomId), ); global.kuzzle.on("core:notify:document", ({ notification, rooms }) => { @@ -824,18 +824,18 @@ class ClusterNode { }); global.kuzzle.on("core:notify:user", ({ notification, room }) => - this.onUserNotification(room, notification) + this.onUserNotification(room, notification), ); global.kuzzle.on( "core:auth:strategyAdded", ({ name, pluginName, strategy }) => { this.onAuthStrategyAdded(name, pluginName, strategy); - } + }, ); global.kuzzle.on("core:auth:strategyRemoved", ({ name, pluginName }) => - this.onAuthStrategyRemoved(name, pluginName) + this.onAuthStrategyRemoved(name, pluginName), ); global.kuzzle.on("admin:afterDump", (request) => { @@ -849,74 +849,74 @@ class ClusterNode { global.kuzzle.on("admin:afterShutdown", () => this.onShutdown()); global.kuzzle.on("collection:afterDeleteSpecifications", () => - this.onValidatorsChanged() + this.onValidatorsChanged(), ); global.kuzzle.on("collection:afterUpdateSpecifications", () => - this.onValidatorsChanged() + this.onValidatorsChanged(), ); // Profile change events global.kuzzle.on("core:security:profile:create", ({ args: [profileId] }) => - this.onProfileChanged(profileId) + this.onProfileChanged(profileId), ); global.kuzzle.on( "core:security:profile:createOrReplace", - ({ args: [profileId] }) => this.onProfileChanged(profileId) + ({ args: [profileId] }) => this.onProfileChanged(profileId), ); global.kuzzle.on("core:security:profile:update", ({ args: [profileId] }) => - this.onProfileChanged(profileId) + this.onProfileChanged(profileId), ); global.kuzzle.on("core:security:profile:delete", ({ args: [profileId] }) => - this.onProfileChanged(profileId) + this.onProfileChanged(profileId), ); // Role change events global.kuzzle.on("core:security:role:create", ({ args: [roleId] }) => - this.onRoleChanged(roleId) + this.onRoleChanged(roleId), ); global.kuzzle.on( "core:security:role:createOrReplace", - ({ args: [roleId] }) => this.onRoleChanged(roleId) + ({ args: [roleId] }) => this.onRoleChanged(roleId), ); global.kuzzle.on("core:security:role:update", ({ args: [roleId] }) => - this.onRoleChanged(roleId) + this.onRoleChanged(roleId), ); global.kuzzle.on("core:security:role:delete", ({ args: [roleId] }) => - this.onRoleChanged(roleId) + this.onRoleChanged(roleId), ); // Index cache change events global.kuzzle.on("core:storage:index:create:after", ({ index, scope }) => - this.onIndexAdded(scope, index) + this.onIndexAdded(scope, index), ); global.kuzzle.on("core:storage:index:delete:after", ({ index, scope }) => - this.onIndexesRemoved(scope, [index]) + this.onIndexesRemoved(scope, [index]), ); global.kuzzle.on("core:storage:index:mDelete:after", ({ indexes, scope }) => - this.onIndexesRemoved(scope, indexes) + this.onIndexesRemoved(scope, indexes), ); global.kuzzle.on( "core:storage:collection:create:after", ({ collection, index, scope }) => { this.onCollectionAdded(scope, index, collection); - } + }, ); global.kuzzle.on( "core:storage:collection:delete:after", ({ collection, index, scope }) => { this.onCollectionRemoved(scope, index, collection); - } + }, ); } @@ -933,7 +933,7 @@ class ClusterNode { "[%s] Broadcasting new realtime room %s (message: %d)", this.nodeId, payload.id, - roomMessageId + roomMessageId, ); const icpair = fromKoncordeIndex(payload.index); @@ -947,7 +947,7 @@ class ClusterNode { messageId: roomMessageId, nodeId: this.nodeId, subscribers: 0, - } + }, ); } @@ -964,7 +964,7 @@ class ClusterNode { "[%s] Broadcasting new realtime subscription on room %s (message: %d)", this.nodeId, roomId, - subMessageId + subMessageId, ); this.fullState.addRealtimeSubscription(roomId, this.nodeId, subMessageId); @@ -983,7 +983,7 @@ class ClusterNode { "[%s] Broadcasted the removal of room %s (message: %d)", this.nodeId, roomId, - messageId + messageId, ); this.fullState.removeRealtimeRoom(roomId, this.nodeId); @@ -1002,7 +1002,7 @@ class ClusterNode { '[%s] Emitted cluster-wide event "%s" (message: %d)', this.nodeId, event, - messageId + messageId, ); } @@ -1019,7 +1019,7 @@ class ClusterNode { "[%s] Broadcasting realtime unsubscription on room %s (message: %d)", this.nodeId, roomId, - messageId + messageId, ); this.fullState.removeRealtimeSubscription(roomId, this.nodeId, messageId); @@ -1059,7 +1059,7 @@ class ClusterNode { this.publisher.sendNewAuthStrategy( strategyName, pluginName, - strategyObject + strategyObject, ); this.fullState.addAuthStrategy({ diff --git a/lib/cluster/state.ts b/lib/cluster/state.ts index 9192947adc..301bc751ee 100644 --- a/lib/cluster/state.ts +++ b/lib/cluster/state.ts @@ -125,7 +125,7 @@ class RoomState { roomId: string, index: string, collection: string, - filters: JSONObject + filters: JSONObject, ) { this.id = roomId; this.index = index; @@ -144,13 +144,13 @@ class RoomState { if (this.nodes.has(nodeId)) { throw errorFatal.get( "desync", - `cannot add node ${nodeId} to room ${this.id} (duplicate node)` + `cannot add node ${nodeId} to room ${this.id} (duplicate node)`, ); } this.nodes.set( nodeId, - new RoomSubscriptions(nodeId, messageId, subscribers) + new RoomSubscriptions(nodeId, messageId, subscribers), ); } @@ -165,7 +165,7 @@ class RoomState { // die throw errorFatal.get( "desync", - `cannot add subscription to room ${this.id} (unknown node ${nodeId})` + `cannot add subscription to room ${this.id} (unknown node ${nodeId})`, ); } @@ -179,14 +179,14 @@ class RoomState { // die throw errorFatal.get( "desync", - `cannot remove subscription from room ${this.id} (unknown node ${nodeId})` + `cannot remove subscription from room ${this.id} (unknown node ${nodeId})`, ); } if (node.decr(messageId) < 0) { throw errorFatal.get( "desync", - `node ${nodeId} has a negative subscribers count on room ${this.id}` + `node ${nodeId} has a negative subscribers count on room ${this.id}`, ); } } @@ -268,7 +268,7 @@ export default class State { index: string, collection: string, filters: JSONObject, - node: SerializedRoomSubscriptions + node: SerializedRoomSubscriptions, ) { let room = this.realtime.get(roomId); @@ -281,7 +281,7 @@ export default class State { if (!global.kuzzle.koncorde.hasFilterId(roomId, kindex)) { global.kuzzle.koncorde.store( - new NormalizedFilter(filters, roomId, kindex) + new NormalizedFilter(filters, roomId, kindex), ); } @@ -303,7 +303,7 @@ export default class State { return new NormalizedFilter( room.filters, roomId, - toKoncordeIndex(room.index, room.collection) + toKoncordeIndex(room.index, room.collection), ); } @@ -331,7 +331,7 @@ export default class State { global.kuzzle.koncorde.remove( roomId, - toKoncordeIndex(room.index, room.collection) + toKoncordeIndex(room.index, room.collection), ); } } @@ -370,7 +370,7 @@ export default class State { if (!room) { throw errorFatal.get( "desync", - `cannot add subscription to room ${roomId} (room doesn't exist)` + `cannot add subscription to room ${roomId} (room doesn't exist)`, ); } @@ -383,7 +383,7 @@ export default class State { if (!room) { throw errorFatal.get( "desync", - `cannot remove subscription from room ${roomId} (room doesn't exist)` + `cannot remove subscription from room ${roomId} (room doesn't exist)`, ); } @@ -439,7 +439,7 @@ export default class State { state.index, state.collection, JSON.parse(state.filters), - node + node, ); } } @@ -450,7 +450,7 @@ export default class State { global.kuzzle.pluginsManager.registerStrategy( state.pluginName, state.strategyName, - state.strategy + state.strategy, ); this.addAuthStrategy(state); diff --git a/lib/cluster/subscriber.js b/lib/cluster/subscriber.js index 074b7292f2..bcc4683fe1 100644 --- a/lib/cluster/subscriber.js +++ b/lib/cluster/subscriber.js @@ -116,7 +116,7 @@ class ClusterSubscriber { this.socket.subscribe(); this.heartbeatTimer = setInterval( () => this.checkHeartbeat(), - this.heartbeatDelay + this.heartbeatDelay, ); this.listen(); @@ -225,9 +225,9 @@ class ClusterSubscriber { } catch (e) { this.localNode.evictSelf( `Unable to process sync message (topic: ${topic}, message: ${JSON.stringify( - message + message, )}`, - e + e, ); } } @@ -254,7 +254,7 @@ class ClusterSubscriber { async handleNodeEviction(message) { if (message.nodeId === this.localNode.nodeId) { global.kuzzle.log.error( - `[CLUSTER] Node evicted by ${message.evictor}. Reason: ${message.reason}` + `[CLUSTER] Node evicted by ${message.evictor}. Reason: ${message.reason}`, ); global.kuzzle.shutdown(); return; @@ -295,7 +295,7 @@ class ClusterSubscriber { messageId, id, icpair.index, - icpair.collection + icpair.collection, ); this.localNode.fullState.addRealtimeRoom( @@ -307,7 +307,7 @@ class ClusterSubscriber { messageId, nodeId: this.remoteNodeId, subscribers: 0, - } + }, ); } @@ -322,13 +322,13 @@ class ClusterSubscriber { "New realtime subscription received from node %s (message: %d, room: %s)", this.remoteNodeId, message.messageId, - message.roomId + message.roomId, ); this.localNode.fullState.addRealtimeSubscription( message.roomId, this.remoteNodeId, - message.messageId + message.messageId, ); } @@ -343,12 +343,12 @@ class ClusterSubscriber { "Realtime room removal received from node %s (message: %d, room: %s)", this.remoteNodeId, message.messageId, - message.roomId + message.roomId, ); this.localNode.fullState.removeRealtimeRoom( message.roomId, - this.remoteNodeId + this.remoteNodeId, ); } @@ -363,13 +363,13 @@ class ClusterSubscriber { "Realtime unsubscription received from node %s (message: %d, room: %s)", this.remoteNodeId, message.messageId, - message.roomId + message.roomId, ); this.localNode.fullState.removeRealtimeSubscription( message.roomId, this.remoteNodeId, - message.messageId + message.messageId, ); } @@ -410,7 +410,7 @@ class ClusterSubscriber { return global.kuzzle.ask( "core:realtime:document:dispatch", message.rooms, - notification + notification, ); } @@ -438,7 +438,7 @@ class ClusterSubscriber { return global.kuzzle.ask( "core:realtime:user:sendMessage", message.room, - notification + notification, ); } @@ -455,7 +455,7 @@ class ClusterSubscriber { "New authentication strategy added by node %s (plugin: %s, strategy: %s)", this.remoteNodeId, pluginName, - strategyName + strategyName, ); this.localNode.fullState.addAuthStrategy(message); @@ -463,7 +463,7 @@ class ClusterSubscriber { global.kuzzle.pluginsManager.registerStrategy( pluginName, strategyName, - strategy + strategy, ); } @@ -480,7 +480,7 @@ class ClusterSubscriber { "Authentication strategy removed by node %s (plugin: %s, strategy: %s)", this.remoteNodeId, pluginName, - strategyName + strategyName, ); global.kuzzle.pluginsManager.unregisterStrategy(pluginName, strategyName); @@ -516,10 +516,10 @@ class ClusterSubscriber { handleShutdown() { debug( "Cluster-wide shutdown request received from node %s", - this.remoteNodeId + this.remoteNodeId, ); global.kuzzle.log.error( - `[CLUSTER] Cluster wide shutdown from ${this.remoteNodeId}` + `[CLUSTER] Cluster wide shutdown from ${this.remoteNodeId}`, ); global.kuzzle.shutdown(); } @@ -532,7 +532,7 @@ class ClusterSubscriber { async handleRefreshValidators() { debug( "Validators changed notification received from node %s", - this.remoteNodeId + this.remoteNodeId, ); await global.kuzzle.validation.curateSpecification(); } @@ -543,7 +543,7 @@ class ClusterSubscriber { async handleRefreshIndexCache() { debug( "Index cache manually refresh received from node %s", - this.remoteNodeId + this.remoteNodeId, ); await global.kuzzle.ask("core:storage:public:cache:refresh", { from: "cluster", @@ -560,12 +560,12 @@ class ClusterSubscriber { debug( "Profile invalidation request received from node %s (profile: %s)", this.remoteNodeId, - message.profileId + message.profileId, ); await global.kuzzle.ask( "core:security:profile:invalidate", - message.profileId + message.profileId, ); } @@ -579,7 +579,7 @@ class ClusterSubscriber { debug( "Role invalidation request received from node %s (role: %s)", this.remoteNodeId, - message.roleId + message.roleId, ); await global.kuzzle.ask("core:security:role:invalidate", message.roleId); @@ -598,7 +598,7 @@ class ClusterSubscriber { "New index added by node %s (scope: %s, index: %s)", this.remoteNodeId, scope, - index + index, ); await global.kuzzle.ask(`core:storage:${scope}:cache:addIndex`, index); @@ -617,12 +617,12 @@ class ClusterSubscriber { "Indexes removed by node %s (scope: %s, indexes: %s)", this.remoteNodeId, scope, - indexes + indexes, ); await global.kuzzle.ask( `core:storage:${scope}:cache:removeIndexes`, - indexes + indexes, ); } @@ -640,13 +640,13 @@ class ClusterSubscriber { this.remoteNodeId, scope, index, - collection + collection, ); await global.kuzzle.ask( `core:storage:${scope}:cache:addCollection`, index, - collection + collection, ); } @@ -664,13 +664,13 @@ class ClusterSubscriber { this.remoteNodeId, scope, index, - collection + collection, ); await global.kuzzle.ask( `core:storage:${scope}:cache:removeCollection`, index, - collection + collection, ); } @@ -730,7 +730,7 @@ class ClusterSubscriber { async validateMessage(message) { if (!has(message, "messageId")) { global.kuzzle.log.warn( - `Invalid message received from node ${this.remoteNodeId}. Evicting it.` + `Invalid message received from node ${this.remoteNodeId}. Evicting it.`, ); await this.evictNode({ @@ -754,7 +754,7 @@ class ClusterSubscriber { await this.localNode.evictSelf( `Node out-of-sync: ${ message.messageId - this.lastMessageId - 1 - } messages lost from node ${this.remoteNodeId}` + } messages lost from node ${this.remoteNodeId}`, ); return false; } diff --git a/lib/cluster/workers/IDCardRenewer.js b/lib/cluster/workers/IDCardRenewer.js index a6d257e32e..4049de3981 100644 --- a/lib/cluster/workers/IDCardRenewer.js +++ b/lib/cluster/workers/IDCardRenewer.js @@ -31,7 +31,7 @@ class IDCardRenewer { } catch (error) { // eslint-disable-next-line no-console console.error( - `Failed to connect to redis, could not refresh ID card: ${error.message}` + `Failed to connect to redis, could not refresh ID card: ${error.message}`, ); this.parentPort.postMessage({ error: `Failed to connect to redis, could not refresh ID card: ${error.message}`, @@ -47,7 +47,7 @@ class IDCardRenewer { if (!this.disposed) { this.refreshTimer = setInterval( this.renewIDCard.bind(this), - this.refreshDelay + this.refreshDelay, ); } @@ -69,7 +69,7 @@ class IDCardRenewer { try { const refreshed = await this.redis.commands.pexpire( this.nodeIdKey, - this.refreshDelay * this.refreshMultiplier + this.refreshDelay * this.refreshMultiplier, ); // Unable to refresh the key in time before it expires // => this node is too slow, we need to remove it from the cluster @@ -108,7 +108,7 @@ class IDCardRenewer { } catch (error) { // eslint-disable-next-line no-console console.error( - `Could not delete key '${this.nodeIdKey}' from redis: ${error.message}` + `Could not delete key '${this.nodeIdKey}' from redis: ${error.message}`, ); } } diff --git a/lib/config/documentEventAliases.ts b/lib/config/documentEventAliases.ts index 12a03cfe7a..bcbbbc7993 100644 --- a/lib/config/documentEventAliases.ts +++ b/lib/config/documentEventAliases.ts @@ -29,7 +29,7 @@ interface EventAliases { function filter( obj: Record, - expectValue: string + expectValue: string, ): Array { const result = []; diff --git a/lib/config/index.js b/lib/config/index.js index eed078ecbf..8bc21385f6 100644 --- a/lib/config/index.js +++ b/lib/config/index.js @@ -82,7 +82,7 @@ function unstringify(cfg) { .filter( (k) => !/version$/i.test(k) && - (typeof cfg[k] === "string" || cfg[k] instanceof Object) + (typeof cfg[k] === "string" || cfg[k] instanceof Object), ) .forEach((k) => { if (typeof cfg[k] === "string") { @@ -96,7 +96,7 @@ function unstringify(cfg) { } catch (e) { throw kerror.get( "cannot_parse", - `the key "${k}" does not contain a valid stringified JSON (${cfg[k]})` + `the key "${k}" does not contain a valid stringified JSON (${cfg[k]})`, ); } } else if (/^(-|\+)?([0-9]+)$/.test(cfg[k])) { @@ -160,7 +160,7 @@ function checkLimitsConfig(cfg) { throw kerror.get( "out_of_range", "limits.concurrentRequests", - 'lower than "limits.requestsBufferSize"' + 'lower than "limits.requestsBufferSize"', ); } @@ -171,7 +171,7 @@ function checkLimitsConfig(cfg) { throw kerror.get( "out_of_range", "limits.requestsBufferWarningThreshold", - "[limits.concurrentRequests, limits.requestsBufferSize]" + "[limits.concurrentRequests, limits.requestsBufferSize]", ); } } @@ -185,27 +185,27 @@ function checkWebSocketOptions(config) { assert( typeof cfg.enabled === "boolean", - `[websocket] "enabled" parameter: invalid value "${cfg.enabled}" (boolean expected)` + `[websocket] "enabled" parameter: invalid value "${cfg.enabled}" (boolean expected)`, ); assert( Number.isInteger(cfg.idleTimeout) && cfg.idleTimeout >= 0, - `[websocket] "idleTimeout" parameter: invalid value "${cfg.idleTimeout}" (integer >= 1000 expected)` + `[websocket] "idleTimeout" parameter: invalid value "${cfg.idleTimeout}" (integer >= 1000 expected)`, ); assert( Number.isInteger(cfg.rateLimit) && cfg.rateLimit >= 0, - `[websocket] "rateLimit" parameter: invalid value "${cfg.rateLimit}" (integer >= 0 expected)` + `[websocket] "rateLimit" parameter: invalid value "${cfg.rateLimit}" (integer >= 0 expected)`, ); assert( typeof cfg.compression === "boolean", - `[websocket] "compression" parameter: invalid value "${cfg.compression}" (boolean expected)` + `[websocket] "compression" parameter: invalid value "${cfg.compression}" (boolean expected)`, ); assert( typeof cfg.sendPingsAutomatically === "boolean", - `[websocket] "sendPingsAutomatically" parameter: invalid value "${cfg.sendPingsAutomatically}" (boolean expected)` + `[websocket] "sendPingsAutomatically" parameter: invalid value "${cfg.sendPingsAutomatically}" (boolean expected)`, ); assert( typeof cfg.resetIdleTimeoutOnSend === "boolean", - `[websocket] "resetIdleTimeoutOnSend" parameter: invalid value "${cfg.resetIdleTimeoutOnSend}" (boolean expected)` + `[websocket] "resetIdleTimeoutOnSend" parameter: invalid value "${cfg.resetIdleTimeoutOnSend}" (boolean expected)`, ); } @@ -219,40 +219,40 @@ function checkHttpOptions(config) { assert( typeof config.http.accessControlAllowOrigin === "string" || Array.isArray(config.http.accessControlAllowOrigin), - `[http] "accessControlAllowOrigin" parameter: invalid value "${config.http.accessControlAllowOrigin}" (array or string expected)` + `[http] "accessControlAllowOrigin" parameter: invalid value "${config.http.accessControlAllowOrigin}" (array or string expected)`, ); assert( typeof config.http.accessControlAllowOriginUseRegExp === "boolean", - `[http] "accessControlAllowOriginUseRegExp" parameter: invalid value "${cfg.accessControlAllowOriginUseRegExp}" (boolean expected)` + `[http] "accessControlAllowOriginUseRegExp" parameter: invalid value "${cfg.accessControlAllowOriginUseRegExp}" (boolean expected)`, ); assert( typeof cfg.enabled === "boolean", - `[http] "enabled" parameter: invalid value "${cfg.enabled}" (boolean expected)` + `[http] "enabled" parameter: invalid value "${cfg.enabled}" (boolean expected)`, ); assert( typeof cfg.allowCompression === "boolean", - `[http] "allowCompression" parameter: invalid value "${cfg.allowCompression}" (boolean expected)` + `[http] "allowCompression" parameter: invalid value "${cfg.allowCompression}" (boolean expected)`, ); assert( Number.isInteger(cfg.maxEncodingLayers) && cfg.maxEncodingLayers >= 1, - `[http] "maxEncodingLayers" parameter: invalid value "${cfg.maxEncodingLayers}" (integer >= 1 expected)` + `[http] "maxEncodingLayers" parameter: invalid value "${cfg.maxEncodingLayers}" (integer >= 1 expected)`, ); const maxFormFileSize = bytes(cfg.maxFormFileSize); assert( Number.isInteger(maxFormFileSize) && maxFormFileSize >= 0, - `[http] "maxFormFileSize" parameter: cannot parse "${cfg.maxFormFileSize}"` + `[http] "maxFormFileSize" parameter: cannot parse "${cfg.maxFormFileSize}"`, ); cfg.maxFormFileSize = maxFormFileSize; assert( typeof config.http.cookieAuthentication === "boolean", - `[http] "cookieAuthentication" parameter: invalid value "${config.http.cookieAuthentication}" (boolean expected)` + `[http] "cookieAuthentication" parameter: invalid value "${config.http.cookieAuthentication}" (boolean expected)`, ); assert( Array.isArray(cfg.additionalContentTypes) && cfg.additionalContentTypes.every((ct) => typeof ct === "string"), - `[http] "additionalContentTypes" parameter: invalid value "${cfg.additionalContentTypes}" (array of strings expected)` + `[http] "additionalContentTypes" parameter: invalid value "${cfg.additionalContentTypes}" (array of strings expected)`, ); } @@ -268,25 +268,25 @@ function checkClusterOptions(config) { ]) { assert( typeof cfg[prop] === "number" && cfg[prop] > 0, - `[CONFIG] kuzzlerc.cluster.${prop}: value must be a number greater than 0` + `[CONFIG] kuzzlerc.cluster.${prop}: value must be a number greater than 0`, ); } assert( cfg.syncTimeout < cfg.joinTimeout, - "[CONFIG] kuzzlerc.cluster.syncTimeout: value must be lower than kuzzlerc.cluster.joinTimeout" + "[CONFIG] kuzzlerc.cluster.syncTimeout: value must be lower than kuzzlerc.cluster.joinTimeout", ); for (const prop of ["command", "sync"]) { assert( typeof cfg.ports[prop] === "number" && cfg.ports[prop] > 0, - `[CONFIG] kuzzlerc.cluster.ports.${prop}: value must be a number greater than 0` + `[CONFIG] kuzzlerc.cluster.ports.${prop}: value must be a number greater than 0`, ); } assert( typeof cfg.ipv6 === "boolean", - "[CONFIG] kuzzlerc.cluster.ipv6: boolean expected" + "[CONFIG] kuzzlerc.cluster.ipv6: boolean expected", ); // If config is passed with env variable, ip cannot be the value null // but only blank string or the string "null" @@ -295,12 +295,12 @@ function checkClusterOptions(config) { } assert( !cfg.ip || ["private", "public"].includes(cfg.ip), - "[CONFIG] kuzzlerc.cluster.ip: invalid value (accepted values: public, private)" + "[CONFIG] kuzzlerc.cluster.ip: invalid value (accepted values: public, private)", ); assert( !cfg.interface || typeof cfg.interface === "string", - "[CONFIG] kuzzlerc.cluster.interface: value must be either null, or a string" + "[CONFIG] kuzzlerc.cluster.interface: value must be either null, or a string", ); } diff --git a/lib/core/auth/passportWrapper.js b/lib/core/auth/passportWrapper.js index e28a2fc63f..5ff01bd723 100644 --- a/lib/core/auth/passportWrapper.js +++ b/lib/core/auth/passportWrapper.js @@ -63,13 +63,13 @@ class PassportWrapper { "plugin", "runtime", "unexpected_error", - err.message - ) + err.message, + ), ); } } else if (!user) { reject( - kerror.get("plugin", "strategy", "missing_user", info.message) + kerror.get("plugin", "strategy", "missing_user", info.message), ); } else { resolve(user); @@ -80,7 +80,7 @@ class PassportWrapper { passport.authenticate( strategyName, this.options[strategyName] || {}, - authCB + authCB, )(request, response); } catch (e) { if (e instanceof KuzzleError) { @@ -92,8 +92,8 @@ class PassportWrapper { "plugin", "runtime", "unexpected_error", - e.message - ) + e.message, + ), ); } } diff --git a/lib/core/auth/tokenManager.ts b/lib/core/auth/tokenManager.ts index dbb85d69d4..742188f361 100644 --- a/lib/core/auth/tokenManager.ts +++ b/lib/core/auth/tokenManager.ts @@ -118,13 +118,13 @@ export class TokenManager { async init() { const anonymous = await global.kuzzle.ask( - "core:security:user:anonymous:get" + "core:security:user:anonymous:get", ); this.anonymousUserId = anonymous._id; global.kuzzle.on("connection:remove", (connection) => { this.removeConnection(connection.id).catch((err) => - global.kuzzle.log.info(err) + global.kuzzle.log.info(err), ); }); } @@ -133,7 +133,7 @@ export class TokenManager { if (this.tokens.array.length > 0) { const delay = Math.min( this.tokens.array[0].expiresAt - Date.now(), - TIMEOUT_MAX + TIMEOUT_MAX, ); if (this.timer) { @@ -239,7 +239,7 @@ export class TokenManager { this.tokensByConnection.delete(connectionId); await global.kuzzle.ask( "core:realtime:connection:remove", - connectionId + connectionId, ); } @@ -290,7 +290,7 @@ export class TokenManager { for (const connectionId of managedToken.connectionIds) { await global.kuzzle.ask( "core:realtime:tokenExpired:notify", - connectionId + connectionId, ); this.tokensByConnection.delete(connectionId); } @@ -351,7 +351,7 @@ export class TokenManager { private removeConnectionLinkedToToken( connectionId: string, - managedToken: ManagedToken + managedToken: ManagedToken, ) { managedToken.connectionIds.delete(connectionId); diff --git a/lib/core/backend/backend.ts b/lib/core/backend/backend.ts index 9f91e0e97b..a2717de347 100644 --- a/lib/core/backend/backend.ts +++ b/lib/core/backend/backend.ts @@ -55,7 +55,7 @@ Reflect.defineProperty(global, "app", { get() { if (_app === null) { throw new Error( - "App instance not found. Are you sure you have already started your application?" + "App instance not found. Are you sure you have already started your application?", ); } @@ -64,7 +64,7 @@ Reflect.defineProperty(global, "app", { set(value) { if (_app !== null) { throw new Error( - "Cannot build an App instance: another one already exists" + "Cannot build an App instance: another one already exists", ); } @@ -368,7 +368,7 @@ export class Backend { install( id: string, handler: () => Promise, - description?: string + description?: string, ): void { if (this.started) { throw runtimeError.get("already_started", "install"); @@ -382,7 +382,7 @@ export class Backend { "assert", "invalid_type", "handler", - "function" + "function", ); } if (description && typeof description !== "string") { diff --git a/lib/core/backend/backendCluster.ts b/lib/core/backend/backendCluster.ts index 06b543cb42..0e062d586d 100644 --- a/lib/core/backend/backendCluster.ts +++ b/lib/core/backend/backendCluster.ts @@ -31,7 +31,7 @@ export class BackendCluster { */ async broadcast( event: TEventDefinition["name"], - payload: TEventDefinition["args"][0] + payload: TEventDefinition["args"][0], ): Promise { await global.kuzzle.ask("cluster:event:broadcast", event, payload); } @@ -45,7 +45,7 @@ export class BackendCluster { */ async on( event: TEventDefinition["name"], - listener: ClusterEventHandler + listener: ClusterEventHandler, ): Promise { await global.kuzzle.ask("cluster:event:on", event, listener); } @@ -60,7 +60,7 @@ export class BackendCluster { */ async once( event: TEventDefinition["name"], - listener: ClusterEventHandler + listener: ClusterEventHandler, ): Promise { await global.kuzzle.ask("cluster:event:once", event, listener); } @@ -76,7 +76,7 @@ export class BackendCluster { */ async off( event: TEventDefinition["name"], - listener: ClusterEventHandler + listener: ClusterEventHandler, ): Promise { await global.kuzzle.ask("cluster:event:off", event, listener); } diff --git a/lib/core/backend/backendController.ts b/lib/core/backend/backendController.ts index ab068d6e7c..e4d4c1ef25 100644 --- a/lib/core/backend/backendController.ts +++ b/lib/core/backend/backendController.ts @@ -129,20 +129,20 @@ export class BackendController extends ApplicationManager { if (!controller.name) { controller.name = Inflector.kebabCase( - controller.constructor.name + controller.constructor.name, ).replace("-controller", ""); } Plugin.checkControllerDefinition(controller.name, controller.definition); for (const [action, definition] of Object.entries( - controller.definition.actions + controller.definition.actions, )) { if (typeof definition.handler !== "function") { throw assertionError.get( "invalid_controller_definition", controller.name, - `Handler for action "${action}" is not a function.` + `Handler for action "${action}" is not a function.`, ); } @@ -168,7 +168,7 @@ export class BackendController extends ApplicationManager { throw assertionError.get( "invalid_controller_definition", name, - "A controller with this name already exists" + "A controller with this name already exists", ); } diff --git a/lib/core/backend/backendErrors.ts b/lib/core/backend/backendErrors.ts index fe982d07db..02d53aa11f 100644 --- a/lib/core/backend/backendErrors.ts +++ b/lib/core/backend/backendErrors.ts @@ -52,7 +52,7 @@ export class BackendErrors extends ApplicationManager { domain: string, subDomain: string, name: string, - definition: CustomErrorDefinition + definition: CustomErrorDefinition, ) { if (!this.domains[domain]) { this.domains[domain] = { @@ -98,7 +98,7 @@ export class BackendErrors extends ApplicationManager { domain, subDomain, name, - ...placeholders + ...placeholders, ); } @@ -126,7 +126,7 @@ export class BackendErrors extends ApplicationManager { domain, subDomain, name, - ...placeholders + ...placeholders, ); } diff --git a/lib/core/backend/backendHook.ts b/lib/core/backend/backendHook.ts index 5fa6096b05..5ec09d17ad 100644 --- a/lib/core/backend/backendHook.ts +++ b/lib/core/backend/backendHook.ts @@ -36,7 +36,7 @@ export class BackendHook extends ApplicationManager { */ register( event: TEventDefinition["name"], - handler: HookEventHandler + handler: HookEventHandler, ): void { if (this._application.started) { throw runtimeError.get("already_started", "hook"); diff --git a/lib/core/backend/backendImport.ts b/lib/core/backend/backendImport.ts index 9273ab16e4..cd4f7348e3 100644 --- a/lib/core/backend/backendImport.ts +++ b/lib/core/backend/backendImport.ts @@ -68,7 +68,7 @@ export class BackendImport extends ApplicationManager { this._application._import.mappings[index] = Object.assign( {}, this._application._import.mappings[index], - mappings[index] + mappings[index], ); } } @@ -96,7 +96,7 @@ export class BackendImport extends ApplicationManager { this._application._import.profiles = Object.assign( {}, this._application._import.profiles, - profiles + profiles, ); } @@ -123,7 +123,7 @@ export class BackendImport extends ApplicationManager { this._application._import.roles = Object.assign( {}, this._application._import.roles, - roles + roles, ); } @@ -165,7 +165,7 @@ export class BackendImport extends ApplicationManager { */ users( users: JSONObject, - options: { onExistingUsers?: "overwrite" | "skip" } = {} + options: { onExistingUsers?: "overwrite" | "skip" } = {}, ): void { if (this._application.started) { throw runtimeError.get("already_started", "import"); @@ -190,7 +190,7 @@ export class BackendImport extends ApplicationManager { this._application._import.users = Object.assign( {}, this._application._import.users, - users + users, ); } } diff --git a/lib/core/backend/backendPipe.ts b/lib/core/backend/backendPipe.ts index 8e30ff20f4..20f97bc8d2 100644 --- a/lib/core/backend/backendPipe.ts +++ b/lib/core/backend/backendPipe.ts @@ -36,7 +36,7 @@ export class BackendPipe extends ApplicationManager { register( event: TEventDefinition["name"], handler: PipeEventHandler, - options: any = {} + options: any = {}, ): string | void { if (this._application.started && options.dynamic !== true) { throw runtimeError.get("already_started", "pipe.register"); @@ -50,7 +50,7 @@ export class BackendPipe extends ApplicationManager { return global.kuzzle.pluginsManager.registerPipe( global.kuzzle.pluginsManager.application, event, - handler + handler, ); } diff --git a/lib/core/backend/backendPlugin.ts b/lib/core/backend/backendPlugin.ts index 580a870e57..a695f56f8a 100644 --- a/lib/core/backend/backendPlugin.ts +++ b/lib/core/backend/backendPlugin.ts @@ -48,7 +48,7 @@ export class BackendPlugin extends ApplicationManager { name?: string; manifest?: JSONObject; deprecationWarning?: boolean; - } = {} + } = {}, ): void { if (this._application.started) { throw runtimeError.get("already_started", "plugin"); @@ -92,7 +92,7 @@ export class BackendPlugin extends ApplicationManager { throw assertionError.get( "plugin_not_found", name, - didYouMean(name, this.list()) + didYouMean(name, this.list()), ); } diff --git a/lib/core/backend/backendStorage.ts b/lib/core/backend/backendStorage.ts index 294de544c7..649876bc92 100644 --- a/lib/core/backend/backendStorage.ts +++ b/lib/core/backend/backendStorage.ts @@ -61,7 +61,7 @@ export class BackendStorage extends ApplicationManager { get storageClient(): Client { if (!this._client) { this._client = Elasticsearch.buildClient( - this._kuzzle.config.services.storageEngine.client + this._kuzzle.config.services.storageEngine.client, ); } diff --git a/lib/core/backend/backendSubscription.ts b/lib/core/backend/backendSubscription.ts index f2a53e9ea0..42484a7a92 100644 --- a/lib/core/backend/backendSubscription.ts +++ b/lib/core/backend/backendSubscription.ts @@ -51,7 +51,7 @@ export class BackendSubscription extends ApplicationManager { volatile?: JSONObject; scope?: "in" | "out" | "all" | "none"; users?: "in" | "out" | "all" | "none"; - } = {} + } = {}, ): Promise<{ roomId: string; channel: string }> { if (!this._application.started) { throw runtimeError.get("unavailable_before_start", "subscriptions.add"); @@ -70,12 +70,12 @@ export class BackendSubscription extends ApplicationManager { { connectionId: connection.id, volatile, - } + }, ); const { channel, roomId } = await global.kuzzle.ask( "core:realtime:subscribe", - subscriptionRequest + subscriptionRequest, ); return { channel, roomId }; @@ -85,7 +85,7 @@ export class BackendSubscription extends ApplicationManager { if (!this._application.started) { throw runtimeError.get( "unavailable_before_start", - "subscriptions.remove" + "subscriptions.remove", ); } diff --git a/lib/core/backend/backendVault.ts b/lib/core/backend/backendVault.ts index 44592b0735..b6b76109fa 100644 --- a/lib/core/backend/backendVault.ts +++ b/lib/core/backend/backendVault.ts @@ -61,7 +61,7 @@ export class BackendVault extends ApplicationManager { if (!this._application.started && !this.decrypted) { const kuzzleVault = vault.load( this._application._vaultKey, - this._application._secretsFile + this._application._secretsFile, ); this._secrets = kuzzleVault.secrets; } diff --git a/lib/core/cache/cacheEngine.js b/lib/core/cache/cacheEngine.js index acd62233aa..f8ab6246c9 100644 --- a/lib/core/cache/cacheEngine.js +++ b/lib/core/cache/cacheEngine.js @@ -53,7 +53,7 @@ class CacheEngine { * @param {string|Array.} keys */ global.kuzzle.onAsk("core:cache:internal:del", (keys) => - this.internal.commands.del(keys) + this.internal.commands.del(keys), ); /** @@ -62,14 +62,14 @@ class CacheEngine { * @param {number} ttl (in seconds) */ global.kuzzle.onAsk("core:cache:internal:expire", (key, ttl) => - this.internal.commands.expire(key, ttl) + this.internal.commands.expire(key, ttl), ); /** * Wipes the database clean */ global.kuzzle.onAsk("core:cache:internal:flushdb", () => - this.internal.commands.flushdb() + this.internal.commands.flushdb(), ); /** @@ -77,7 +77,7 @@ class CacheEngine { * @returns {Promise.} */ global.kuzzle.onAsk("core:cache:internal:info:get", () => - this.internal.info() + this.internal.info(), ); /** @@ -86,7 +86,7 @@ class CacheEngine { * @return {string} */ global.kuzzle.onAsk("core:cache:internal:get", (key) => - this.internal.commands.get(key) + this.internal.commands.get(key), ); /** @@ -108,7 +108,7 @@ class CacheEngine { * @param {string} key */ global.kuzzle.onAsk("core:cache:internal:persist", (key) => - this.internal.commands.persist(key) + this.internal.commands.persist(key), ); /** @@ -117,7 +117,7 @@ class CacheEngine { * @param {number} ttl (in milliseconds) */ global.kuzzle.onAsk("core:cache:internal:pexpire", (key, ttl) => - this.internal.commands.pexpire(key, ttl) + this.internal.commands.pexpire(key, ttl), ); /** @@ -125,7 +125,7 @@ class CacheEngine { * @param {string} pattern */ global.kuzzle.onAsk("core:cache:internal:searchKeys", (pattern) => - this.internal.searchKeys(pattern) + this.internal.searchKeys(pattern), ); /** @@ -144,7 +144,7 @@ class CacheEngine { lua: script, numberOfKeys: keys, }); - } + }, ); /** @@ -155,7 +155,7 @@ class CacheEngine { * @return {*} script result (if any) */ global.kuzzle.onAsk("core:cache:internal:script:execute", (name, ...args) => - this.internal.client[name](...args) + this.internal.client[name](...args), ); /** @@ -174,7 +174,7 @@ class CacheEngine { * @returns {Promise.} true if the key was set, false otherwise */ global.kuzzle.onAsk("core:cache:internal:store", (key, value, opts) => - this.internal.store(key, value, opts) + this.internal.store(key, value, opts), ); /** @@ -183,7 +183,7 @@ class CacheEngine { * @param {Array} args -- command arguments */ global.kuzzle.onAsk("core:cache:internal:execute", (command, ...args) => - this.internal.exec(command, ...args) + this.internal.exec(command, ...args), ); } @@ -193,7 +193,7 @@ class CacheEngine { * @param {string|Array.} keys */ global.kuzzle.onAsk("core:cache:public:del", (keys) => - this.public.commands.del(keys) + this.public.commands.del(keys), ); /** @@ -202,7 +202,7 @@ class CacheEngine { * @param {Array} args -- command arguments */ global.kuzzle.onAsk("core:cache:public:execute", (command, ...args) => - this.public.exec(command, ...args) + this.public.exec(command, ...args), ); /** @@ -211,14 +211,14 @@ class CacheEngine { * @param {number} ttl (in seconds) */ global.kuzzle.onAsk("core:cache:public:expire", (key, ttl) => - this.public.commands.expire(key, ttl) + this.public.commands.expire(key, ttl), ); /** * Wipes the database clean */ global.kuzzle.onAsk("core:cache:public:flushdb", () => - this.public.commands.flushdb() + this.public.commands.flushdb(), ); /** @@ -233,7 +233,7 @@ class CacheEngine { * @return {string} */ global.kuzzle.onAsk("core:cache:public:get", (key) => - this.public.commands.get(key) + this.public.commands.get(key), ); /** @@ -241,7 +241,7 @@ class CacheEngine { * @param {Array} commands to execute */ global.kuzzle.onAsk("core:cache:public:mExecute", (commands) => - this.public.mExecute(commands) + this.public.mExecute(commands), ); /** @@ -249,7 +249,7 @@ class CacheEngine { * @param {string} key */ global.kuzzle.onAsk("core:cache:public:persist", (key) => - this.public.commands.persist(key) + this.public.commands.persist(key), ); /** @@ -268,7 +268,7 @@ class CacheEngine { * @returns {Promise.} true if the key was set, false otherwise */ global.kuzzle.onAsk("core:cache:public:store", (key, value, opts) => - this.public.store(key, value, opts) + this.public.store(key, value, opts), ); } } diff --git a/lib/core/debug/kuzzleDebugger.ts b/lib/core/debug/kuzzleDebugger.ts index c03d3f0075..2aab33b351 100644 --- a/lib/core/debug/kuzzleDebugger.ts +++ b/lib/core/debug/kuzzleDebugger.ts @@ -51,7 +51,7 @@ export class KuzzleDebugger { this.notifyConnection(connectionId, DEBUGGER_EVENT, { event: payload.method, result: payload, - }) + }), ); } @@ -66,14 +66,14 @@ export class KuzzleDebugger { global.kuzzle.onAsk("core:debugger:enable", () => this.enable()); global.kuzzle.onAsk("core:debugger:disable", () => this.disable()); global.kuzzle.onAsk("core:debugger:post", (method, params) => - this.post(method, params) + this.post(method, params), ); global.kuzzle.onAsk("core:debugger:isEnabled", () => this.debuggerStatus); global.kuzzle.onAsk("core:debugger:removeListener", (event, connectionId) => - this.removeListener(event, connectionId) + this.removeListener(event, connectionId), ); global.kuzzle.onAsk("core:debugger:addListener", (event, connectionId) => - this.addListener(event, connectionId) + this.addListener(event, connectionId), ); } @@ -237,7 +237,7 @@ export class KuzzleDebugger { */ private async inspectorPost( method: string, - params: JSONObject + params: JSONObject, ): Promise { if (!this.debuggerStatus) { throw kerror.get("core", "debugger", "not_enabled"); @@ -268,7 +268,7 @@ export class KuzzleDebugger { private async notifyConnection( connectionId: string, event: string, - payload: JSONObject + payload: JSONObject, ) { global.kuzzle.entryPoint._notify({ channels: [event], @@ -290,7 +290,7 @@ export class KuzzleDebugger { this.notifyConnection(connectionId, DEBUGGER_EVENT, { event, result: payload, - }) + }), ); } diff --git a/lib/core/network/accessLogger.js b/lib/core/network/accessLogger.js index a1a2e268c5..e3334fc4e8 100644 --- a/lib/core/network/accessLogger.js +++ b/lib/core/network/accessLogger.js @@ -51,7 +51,7 @@ class AccessLogger { for (const out of config.logs.transports) { if (out.transport && !ALLOWED_TRANSPORTS.includes(out.transport)) { global.kuzzle.log.error( - `Failed to initialize logger transport "${out.transport}": unsupported transport. Skipped.` + `Failed to initialize logger transport "${out.transport}": unsupported transport. Skipped.`, ); } else { this.isActive = this.isActive || !out.silent; @@ -63,7 +63,7 @@ class AccessLogger { } const anonymous = await global.kuzzle.ask( - "core:security:user:anonymous:get" + "core:security:user:anonymous:get", ); this.worker = new Worker(__filename, { @@ -103,7 +103,7 @@ class AccessLogger { }); } catch (error) { global.kuzzle.log.error( - `Failed to write access log for request "${request.id}": ${error.message}` + `Failed to write access log for request "${request.id}": ${error.message}`, ); } } @@ -124,7 +124,7 @@ class AccessLoggerWorker { connection, new KuzzleRequest(request.data, request.options), size, - extra + extra, ); }); } @@ -154,8 +154,8 @@ class AccessLoggerWorker { humanReadableUnhandledException: conf.humanReadableUnhandledException || true, stderrLevels: conf.stderrLevels || ["error", "debug"], - }) - ) + }), + ), ); break; case "elasticsearch": @@ -171,8 +171,8 @@ class AccessLoggerWorker { mappingTemplate: conf.mappingTemplate || "access.log.mapping.json", messageType: conf.messageType || "access", - }) - ) + }), + ), ); break; case "file": @@ -187,8 +187,8 @@ class AccessLoggerWorker { maxSize: conf.maxSize, tailable: conf.tailable, zippedArchive: conf.zippedArchive || false, - }) - ) + }), + ), ); break; case "syslog": @@ -205,8 +205,8 @@ class AccessLoggerWorker { port: conf.port || 514, protocol: conf.protocol || "udp4", type: conf.type || "BSD", - }) - ) + }), + ), ); break; default: @@ -312,7 +312,7 @@ class AccessLoggerWorker { : "-"; this.logger.info( - `${ip} - ${user} [${when}] "${verb} ${url} ${protocol}" ${status} ${size} ${referer} ${agent}` + `${ip} - ${user} [${when}] "${verb} ${url} ${protocol}" ${status} ${size} ${referer} ${agent}`, ); } @@ -328,7 +328,7 @@ class AccessLoggerWorker { const idx = Math.max( 0, - ips.length - 1 - this.config.logs.accessLogIpOffset + ips.length - 1 - this.config.logs.accessLogIpOffset, ); return ips[idx]; @@ -341,7 +341,7 @@ if (!isMainThread) { const worker = new AccessLoggerWorker( workerData.config, - workerData.anonymousUserId + workerData.anonymousUserId, ); worker.init(); diff --git a/lib/core/network/entryPoint.js b/lib/core/network/entryPoint.js index 69b3910169..36fca86c33 100644 --- a/lib/core/network/entryPoint.js +++ b/lib/core/network/entryPoint.js @@ -114,7 +114,7 @@ class EntryPoint { if (!enabled) { this.protocols.delete(protocol.name); } - }) + }), ); } @@ -143,7 +143,7 @@ class EntryPoint { this.protocols.get(client.protocol).joinChannel(channel, connectionId); } catch (e) { global.kuzzle.log.error( - `[join] protocol ${client && client.protocol} failed: ${e.message}` + `[join] protocol ${client && client.protocol} failed: ${e.message}`, ); } } @@ -152,7 +152,7 @@ class EntryPoint { debug( '[server] connection "%s" leaving channel "%s"', connectionId, - channel + channel, ); const client = this._clients.get(connectionId); @@ -167,7 +167,7 @@ class EntryPoint { global.kuzzle.log.error( `[leave channel] protocol ${client && client.protocol} failed: ${ e.message - }` + }`, ); } } @@ -203,13 +203,13 @@ class EntryPoint { .then(() => protocol.init(this, new Context())) .catch((error) => { global.kuzzle.log.error( - `Error during "${manifest.name}" protocol init:` + `Error during "${manifest.name}" protocol init:`, ); throw error; }) .timeout( initTimeout, - `Protocol "${manifest.name}" initialization timed out after ${initTimeout}ms. Try to increase the configuration "services.common.defaultInitTimeout".` + `Protocol "${manifest.name}" initialization timed out after ${initTimeout}ms. Try to increase the configuration "services.common.defaultInitTimeout".`, ) .then(() => { if (this.protocols.has(manifest.name)) { @@ -217,7 +217,7 @@ class EntryPoint { "protocol", "runtime", "already_exists", - manifest.name + manifest.name, ); } @@ -282,7 +282,7 @@ class EntryPoint { debug( "New connection created: %s (protocol: %s)", connection.id, - connection.protocol + connection.protocol, ); } @@ -302,7 +302,7 @@ class EntryPoint { debug( "Removed connection: %s (protocol: %s)", connection.id, - connection.protocol + connection.protocol, ); } } @@ -319,7 +319,7 @@ class EntryPoint { protocol.broadcast(sanitized); } catch (e) { global.kuzzle.log.error( - `[broadcast] protocol ${name} failed: ${e.message}\n${e.stack}` + `[broadcast] protocol ${name} failed: ${e.message}\n${e.stack}`, ); } } @@ -336,7 +336,7 @@ class EntryPoint { debug( '[server] sending notification to client with connection id "%s": %a', data.connectionId, - data + data, ); const client = this._clients.get(data.connectionId); @@ -349,7 +349,7 @@ class EntryPoint { this.protocols.get(client.protocol).notify(removeStacktrace(data)); } catch (e) { global.kuzzle.log.error( - `[notify] protocol ${client.protocol} failed: ${e.message}` + `[notify] protocol ${client.protocol} failed: ${e.message}`, ); } } diff --git a/lib/core/network/httpRouter/index.js b/lib/core/network/httpRouter/index.js index a51cf6c67b..a6e19d6c89 100644 --- a/lib/core/network/httpRouter/index.js +++ b/lib/core/network/httpRouter/index.js @@ -75,7 +75,7 @@ class Router { request.setResult({}, 200); cb(request); }, - this.routes.HEAD + this.routes.HEAD, ); } @@ -197,11 +197,11 @@ class Router { */ routeUnhandledHttpMethod(message, cb) { const requestContext = global.kuzzle.router.connections.get( - message.connection.id + message.connection.id, ), request = new Request( { requestId: message.requestId }, - requestContext && requestContext.toJSON() + requestContext && requestContext.toJSON(), ); // Set Headers if not present @@ -241,7 +241,7 @@ function applyACAOHeader(message, request) { "Access-Control-Allow-Origin": message.headers.origin, Vary: "Origin", }, - true + true, ); } } diff --git a/lib/core/network/httpRouter/routePart.js b/lib/core/network/httpRouter/routePart.js index 0433824ed7..b7651492fc 100644 --- a/lib/core/network/httpRouter/routePart.js +++ b/lib/core/network/httpRouter/routePart.js @@ -124,7 +124,7 @@ function getHandlerPart(routePart, parts, routeHandler, placeholders = []) { routePart.subparts[part], parts, routeHandler, - placeholders + placeholders, ); } @@ -134,7 +134,7 @@ function getHandlerPart(routePart, parts, routeHandler, placeholders = []) { routePart.subparts["*"], parts, routeHandler, - placeholders + placeholders, ); } diff --git a/lib/core/network/protocols/httpwsProtocol.js b/lib/core/network/protocols/httpwsProtocol.js index cefdd5bf5c..318f4b2c51 100644 --- a/lib/core/network/protocols/httpwsProtocol.js +++ b/lib/core/network/protocols/httpwsProtocol.js @@ -66,10 +66,10 @@ const JSON_ENDER = '"}'; // Pre-computed messages & errors const WS_FORCED_TERMINATION_CODE = 1011; const WS_BACKPRESSURE_MESSAGE = Buffer.from( - "too much backpressure: client is too slow" + "too much backpressure: client is too slow", ); const WS_GENERIC_CLOSE_MESSAGE = Buffer.from( - "Connection closed by remote host" + "Connection closed by remote host", ); const WS_RATE_LIMIT_EXCEEDED_ERROR = kerrorWS.get("ratelimit_exceeded"); const HTTP_REQUEST_TOO_LARGE_ERROR = kerrorHTTP.get("request_too_large"); @@ -84,7 +84,7 @@ const HTTP_ALLOWED_CONTENT_TYPES = [ const HTTP_SKIPPED_HEADERS = ["content-length", "set-cookie"]; const HTTP_HEADER_CONNECTION = Buffer.from("Connection"); const HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = Buffer.from( - "Access-Control-Allow-Origin" + "Access-Control-Allow-Origin", ); const HTTP_HEADER_SET_COOKIE = Buffer.from("Set-Cookie"); const HTTP_HEADER_VARY = Buffer.from("Vary"); @@ -148,7 +148,7 @@ class HttpWsProtocol extends Protocol { this.server.listen(entrypoint.config.port, (socket) => { if (!socket) { throw new Error( - `[http/websocket] fatal: unable to listen to port ${entrypoint.config.port}` + `[http/websocket] fatal: unable to listen to port ${entrypoint.config.port}`, ); } }); @@ -204,7 +204,7 @@ class HttpWsProtocol extends Protocol { debugWS( 'Publishing to channel "realtime/%s": %s', channel, - payloadSafeCopy + payloadSafeCopy, ); this.server.publish(`realtime/${channel}`, payloadSafeCopy, false); } @@ -236,7 +236,7 @@ class HttpWsProtocol extends Protocol { debugWS( 'Subscribing connection ID "%s" to channel "realtime/%s"', connectionId, - channel + channel, ); socket.subscribe(`realtime/${channel}`); } @@ -251,7 +251,7 @@ class HttpWsProtocol extends Protocol { debugWS( 'Removing connection ID "%s" from channel "realtime/%s"', connectionId, - channel + channel, ); socket.unsubscribe(`realtime/${channel}`); @@ -268,7 +268,7 @@ class HttpWsProtocol extends Protocol { socket.end( WS_FORCED_TERMINATION_CODE, - message ? Buffer.from(message) : WS_GENERIC_CLOSE_MESSAGE + message ? Buffer.from(message) : WS_GENERIC_CLOSE_MESSAGE, ); } @@ -287,7 +287,7 @@ class HttpWsProtocol extends Protocol { req.getHeader("sec-websocket-key"), req.getHeader("sec-websocket-protocol"), req.getHeader("sec-websocket-extensions"), - context + context, ); } @@ -297,7 +297,7 @@ class HttpWsProtocol extends Protocol { this.name, [ip], socket.headers, - socket.internal + socket.internal, ); this.entryPoint.newConnection(connection); @@ -318,7 +318,7 @@ class HttpWsProtocol extends Protocol { "[%s] received a `close` event (CODE: %d, REASON: %s)", connection.id, code, - Buffer.from(message || "").toString() + Buffer.from(message || "").toString(), ); } this.entryPoint.removeConnection(connection.id); @@ -356,13 +356,13 @@ class HttpWsProtocol extends Protocol { ({ payload: message } = await global.kuzzle.pipe( "protocol:websocket:beforeParsingPayload", - { connection, payload: message } + { connection, payload: message }, )); try { ({ payload: parsed } = await global.kuzzle.pipe( "protocol:websocket:afterParsingPayload", - { connection, payload: JSON.parse(message) } + { connection, payload: JSON.parse(message) }, )); } catch (e) { /* @@ -375,7 +375,7 @@ class HttpWsProtocol extends Protocol { this.wsSendError( socket, connection, - kerrorWS.getFrom(e, "unexpected_error", e.message) + kerrorWS.getFrom(e, "unexpected_error", e.message), ); return; } @@ -487,7 +487,7 @@ class HttpWsProtocol extends Protocol { const connection = new ClientConnection( "HTTP/1.1", getHttpIps(response, request), - request.headers + request.headers, ); const message = new HttpMessage(connection, request); @@ -509,13 +509,13 @@ class HttpWsProtocol extends Protocol { if ( !this.httpConfig.opts.allowedContentTypes.some( - (allowed) => contentType === allowed + (allowed) => contentType === allowed, ) ) { this.httpSendError( message, response, - kerrorHTTP.get("unsupported_content", contentType) + kerrorHTTP.get("unsupported_content", contentType), ); return; } @@ -527,7 +527,7 @@ class HttpWsProtocol extends Protocol { this.httpSendError( message, response, - kerrorHTTP.get("unsupported_charset", encoding[1].toLowerCase()) + kerrorHTTP.get("unsupported_charset", encoding[1].toLowerCase()), ); return; } @@ -591,7 +591,7 @@ class HttpWsProtocol extends Protocol { const { payload: newPayload } = await global.kuzzle.pipe( "protocol:http:beforeParsingPayload", - { message, payload: inflated } + { message, payload: inflated }, ); await this.httpParseContent(message, newPayload, cb); resolve(); @@ -641,12 +641,12 @@ class HttpWsProtocol extends Protocol { try { const { payload } = await global.kuzzle.pipe( "protocol:http:afterParsingPayload", - { message, payload: JSON.parse(content.toString()) } + { message, payload: JSON.parse(content.toString()) }, ); message.content = payload; } catch (e) { cb( - kerrorHTTP.get("body_parse_failed", content.toString().slice(0, 50)) + kerrorHTTP.get("body_parse_failed", content.toString().slice(0, 50)), ); return; } @@ -693,7 +693,7 @@ class HttpWsProtocol extends Protocol { const [success] = response.tryEnd( result.compressed, - result.compressed.length + result.compressed.length, ); if (!success) { @@ -701,7 +701,7 @@ class HttpWsProtocol extends Protocol { const retryData = result.compressed.subarray(offset); const [retrySuccess] = response.tryEnd( retryData, - retryData.length + retryData.length, ); return retrySuccess; @@ -739,7 +739,7 @@ class HttpWsProtocol extends Protocol { ) { response.writeHeader( HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, - Buffer.from(message.headers.origin) + Buffer.from(message.headers.origin), ); response.writeHeader(HTTP_HEADER_VARY, ORIGIN); @@ -780,8 +780,8 @@ class HttpWsProtocol extends Protocol { "network", "http", "stream_errored", - httpStream.error.message - ) + httpStream.error.message, + ), ); return; } @@ -790,7 +790,7 @@ class HttpWsProtocol extends Protocol { this.httpSendError( message, response, - kerror.get("network", "http", "stream_closed") + kerror.get("network", "http", "stream_closed"), ); return; } @@ -807,7 +807,7 @@ class HttpWsProtocol extends Protocol { // Make a copy of the array buffer const arrayBuffer = chunk.buffer.slice( chunk.byteOffset, - chunk.byteOffset + chunk.byteLength + chunk.byteOffset + chunk.byteLength, ); const arrayBufferOffset = response.getWriteOffset(); @@ -822,7 +822,7 @@ class HttpWsProtocol extends Protocol { if (streamSizeFixed) { const [success, done] = response.tryEnd( arrayBuffer, - httpStream.totalBytes + httpStream.totalBytes, ); backpressure = !success; @@ -854,13 +854,13 @@ class HttpWsProtocol extends Protocol { let retryBackpressure = false; const remainingChunkData = response.arrayBuffer.slice( - offset - response.arrayBufferOffset + offset - response.arrayBufferOffset, ); if (streamSizeFixed) { const [success] = response.tryEnd( remainingChunkData, - httpStream.totalBytes + httpStream.totalBytes, ); retryBackpressure = !success; @@ -899,7 +899,7 @@ class HttpWsProtocol extends Protocol { debugHTTP( "[%s] httpSendStream: %s", httpStream.connection.id, - err.message + err.message, ); }); @@ -931,7 +931,7 @@ class HttpWsProtocol extends Protocol { connectionId: message.connection.id, error: kerr, }), - message + message, ); this.entryPoint.removeConnection(message.connection.id); @@ -951,12 +951,12 @@ class HttpWsProtocol extends Protocol { if (global.kuzzle.config.internal.allowAllOrigins) { response.writeHeader( HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, - WILDCARD + WILDCARD, ); } else { response.writeHeader( HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, - Buffer.from(message.headers.origin) + Buffer.from(message.headers.origin), ); response.writeHeader(HTTP_HEADER_VARY, ORIGIN); } @@ -1064,7 +1064,7 @@ class HttpWsProtocol extends Protocol { callback({ compressed: !err ? compressed : data, encoding: !err ? "gzip" : "identity", - }) + }), ); return; } else if (algorithm === "deflate") { @@ -1072,7 +1072,7 @@ class HttpWsProtocol extends Protocol { callback({ compressed: !err ? compressed : data, encoding: !err ? "deflate" : "identity", - }) + }), ); return; } @@ -1137,7 +1137,7 @@ class HttpWsProtocol extends Protocol { if (cfg === undefined) { global.kuzzle.log.warn( - "[websocket] no configuration found for websocket: disabling it" + "[websocket] no configuration found for websocket: disabling it", ); return { enabled: false }; } @@ -1148,7 +1148,7 @@ class HttpWsProtocol extends Protocol { if (idleTimeout === 0 || idleTimeout < 1000) { idleTimeout = DEFAULT_IDLE_TIMEOUT; global.kuzzle.log.warn( - `[websocket] The "idleTimeout" parameter can neither be deactivated or be set with a value lower than 1000. Defaulted to ${DEFAULT_IDLE_TIMEOUT}.` + `[websocket] The "idleTimeout" parameter can neither be deactivated or be set with a value lower than 1000. Defaulted to ${DEFAULT_IDLE_TIMEOUT}.`, ); } @@ -1159,7 +1159,7 @@ class HttpWsProtocol extends Protocol { */ if (cfg.heartbeat) { global.kuzzle.log.warn( - '[websocket] The "heartbeat" parameter has been deprecated and is now ignored. The "idleTimeout" parameter should now be configured instead.' + '[websocket] The "heartbeat" parameter has been deprecated and is now ignored. The "idleTimeout" parameter should now be configured instead.', ); } @@ -1181,7 +1181,7 @@ class HttpWsProtocol extends Protocol { if (cfg === undefined) { global.kuzzle.log.warn( - "[http] no configuration found for http: disabling it" + "[http] no configuration found for http: disabling it", ); return { enabled: false }; } diff --git a/lib/core/network/protocols/internalProtocol.js b/lib/core/network/protocols/internalProtocol.js index df1998f18a..0748b517c2 100644 --- a/lib/core/network/protocols/internalProtocol.js +++ b/lib/core/network/protocols/internalProtocol.js @@ -25,7 +25,7 @@ const Protocol = require("./protocol"); const ClientConnection = require("../clientConnection"); const debug = require("../../../util/debug")( - "kuzzle:network:protocols:internal" + "kuzzle:network:protocols:internal", ); /** @@ -63,7 +63,7 @@ class InternalProtocol extends Protocol { */ global.kuzzle.onAsk( "core:network:internal:connectionId:get", - () => this.connection.id + () => this.connection.id, ); } diff --git a/lib/core/network/protocols/mqttProtocol.js b/lib/core/network/protocols/mqttProtocol.js index 13086ffafb..95562d130f 100644 --- a/lib/core/network/protocols/mqttProtocol.js +++ b/lib/core/network/protocols/mqttProtocol.js @@ -73,7 +73,7 @@ class MqttProtocol extends Protocol { port: 1883, }, }, - this.config + this.config, ); /* @@ -93,7 +93,7 @@ class MqttProtocol extends Protocol { this.aedes.on("publish", this.onMessage.bind(this)); await new Promise((res) => - this.server.listen(this.config.server.port, res) + this.server.listen(this.config.server.port, res), ); return true; @@ -152,7 +152,7 @@ class MqttProtocol extends Protocol { const connection = new ClientConnection( this.name, [client.conn.remoteAddress], - {} + {}, ); this.entryPoint.newConnection(connection); @@ -198,10 +198,10 @@ class MqttProtocol extends Protocol { debug( "no connection id for client id %s - packet: %o", client.id, - packet + packet, ); global.kuzzle.log.error( - `[MQTT] Received a packet from an unregistered client: ${client.id}` + `[MQTT] Received a packet from an unregistered client: ${client.id}`, ); return; } @@ -214,7 +214,7 @@ class MqttProtocol extends Protocol { const request = new Request(payload, { connection }); this.entryPoint.execute(connection, request, (response) => - this._respond(client, response) + this._respond(client, response), ); } catch (error) { this._respondError(client, error); @@ -238,7 +238,7 @@ class MqttProtocol extends Protocol { payload: Buffer.from(JSON.stringify(response.content)), topic: this.config.responseTopic, }, - this.publishCallback + this.publishCallback, ); } @@ -250,7 +250,7 @@ class MqttProtocol extends Protocol { { connection, error: kerror.getFrom(error, "unexpected_error", error.message), - } + }, ); this._respond(client, removeStacktrace(errReq.response.toJSON())); } @@ -270,7 +270,7 @@ class MqttProtocol extends Protocol { callback( topic === this.config.requestTopic ? null - : new Error("Cannot publish on this topic: unauthorized") + : new Error("Cannot publish on this topic: unauthorized"), ); } } diff --git a/lib/core/network/protocols/protocol.js b/lib/core/network/protocols/protocol.js index b64ca528a8..cc6bcafb01 100644 --- a/lib/core/network/protocols/protocol.js +++ b/lib/core/network/protocols/protocol.js @@ -52,7 +52,7 @@ class Protocol { // name should be passed in the constructor assert( this.name && !name, - "A name has been given in the constructor and init method. Passing the name in the init method is deprecated." + "A name has been given in the constructor and init method. Passing the name in the init method is deprecated.", ); if (!this.name) { @@ -63,7 +63,7 @@ class Protocol { assert( typeof this.name === "string" && this.name.length > 0, - 'Invalid "name" parameter value: expected a non empty string value' + 'Invalid "name" parameter value: expected a non empty string value', ); if (entryPoint.config.protocols && entryPoint.config.protocols[this.name]) { @@ -72,7 +72,7 @@ class Protocol { assert( Number.isInteger(this.maxRequestSize), - 'Invalid "maxRequestSize" parameter value: expected a numeric value' + 'Invalid "maxRequestSize" parameter value: expected a numeric value', ); this.initCalled = true; diff --git a/lib/core/network/router.js b/lib/core/network/router.js index bb038aaf90..f8d28a2cf0 100644 --- a/lib/core/network/router.js +++ b/lib/core/network/router.js @@ -49,8 +49,8 @@ class Router { "protocol", "runtime", "invalid_connection", - JSON.stringify(requestContext) - ) + JSON.stringify(requestContext), + ), ); } else { this.connections.set(requestContext.connection.id, requestContext); @@ -72,8 +72,8 @@ class Router { "protocol", "runtime", "invalid_connection", - JSON.stringify(requestContext.context) - ) + JSON.stringify(requestContext.context), + ), ); return; } @@ -84,8 +84,8 @@ class Router { "protocol", "runtime", "unknown_connection", - JSON.stringify(connId) - ) + JSON.stringify(connId), + ), ); return; } @@ -130,7 +130,7 @@ class Router { const apiRequest = new Request( requestPayload, - request.serialize().options + request.serialize().options, ); this._executeFromHttp("post", apiRequest, cb); diff --git a/lib/core/plugin/plugin.js b/lib/core/plugin/plugin.js index 778e252493..f604723e99 100644 --- a/lib/core/plugin/plugin.js +++ b/lib/core/plugin/plugin.js @@ -41,7 +41,7 @@ const HTTP_VERBS = ["get", "head", "post", "put", "delete", "patch", "options"]; class Plugin { constructor( instance, - { name, application = false, deprecationWarning = true } = {} + { name, application = false, deprecationWarning = true } = {}, ) { this._instance = instance; @@ -65,7 +65,7 @@ class Plugin { if (global.kuzzle.config.plugins[this.name]) { this.config = JSON.parse( - JSON.stringify(global.kuzzle.config.plugins[this.name]) + JSON.stringify(global.kuzzle.config.plugins[this.name]), ); } @@ -83,7 +83,7 @@ class Plugin { if ( !semver.satisfies( global.kuzzle.config.version, - this.manifest.kuzzleVersion + this.manifest.kuzzleVersion, ) ) { throw kerror.get( @@ -92,7 +92,7 @@ class Plugin { "version_mismatch", this.name, global.kuzzle.config.version, - this.manifest.kuzzleVersion + this.manifest.kuzzleVersion, ); } } @@ -141,7 +141,7 @@ class Plugin { if (has(this.instance, "controllers")) { description.controllers = Object.keys(this.instance.controllers).map( - (controller) => `${this.name}/${controller}` + (controller) => `${this.name}/${controller}`, ); } @@ -207,7 +207,7 @@ class Plugin { set name(name) { if (!this.constructor.checkName(name)) { this.printDeprecation( - "Plugin names should be in kebab-case. This behavior will be enforced in futur versions of Kuzzle." + "Plugin names should be in kebab-case. This behavior will be enforced in futur versions of Kuzzle.", ); } @@ -268,7 +268,7 @@ class Plugin { errorCodes.loadPluginsErrors(plugin.manifest.raw, pluginCode); global.kuzzle.log.info( - `${plugin.logPrefix} Custom errors successfully loaded.` + `${plugin.logPrefix} Custom errors successfully loaded.`, ); } catch (err) { if ( @@ -281,7 +281,7 @@ class Plugin { "manifest", "invalid_errors", plugin.manifest.name, - err.message + err.message, ); } @@ -304,12 +304,12 @@ class Plugin { static checkControllerDefinition( name, definition, - { application = false } = {} + { application = false } = {}, ) { if (typeof name !== "string") { throw assertionError.get( "invalid_controller_definition", - "Controller name must be a string" + "Controller name must be a string", ); } @@ -317,7 +317,7 @@ class Plugin { throw assertionError.get( "invalid_controller_definition", name, - "Controller definition must be an object" + "Controller definition must be an object", ); } @@ -325,12 +325,12 @@ class Plugin { throw assertionError.get( "invalid_controller_definition", name, - 'Controller definition "actions" property must be an object' + 'Controller definition "actions" property must be an object', ); } for (const [action, actionDefinition] of Object.entries( - definition.actions + definition.actions, )) { const actionProperties = Object.keys(actionDefinition); @@ -342,8 +342,8 @@ class Plugin { "invalid_controller_definition", name, `action "${action}" has invalid properties: ${actionProperties.join( - ", " - )}` + ", ", + )}`, ); } @@ -351,7 +351,7 @@ class Plugin { throw assertionError.get( "invalid_controller_definition", name, - "action names must be strings" + "action names must be strings", ); } @@ -359,7 +359,7 @@ class Plugin { throw assertionError.get( "invalid_controller_definition", name, - `action "${action}" handler must be a function` + `action "${action}" handler must be a function`, ); } @@ -368,7 +368,7 @@ class Plugin { throw assertionError.get( "invalid_controller_definition", name, - `action "${action}" http definition must be an array` + `action "${action}" http definition must be an array`, ); } @@ -377,7 +377,7 @@ class Plugin { throw assertionError.get( "invalid_controller_definition", name, - `action "${action}" http "verb" property must be a non-empty string` + `action "${action}" http "verb" property must be a non-empty string`, ); } @@ -385,7 +385,7 @@ class Plugin { throw assertionError.get( "invalid_controller_definition", name, - `action "${action}" http verb "${route.verb}" is not a valid http verb` + `action "${action}" http verb "${route.verb}" is not a valid http verb`, ); } @@ -402,8 +402,8 @@ class Plugin { "invalid_controller_definition", name, `action "${action}" has invalid http properties: ${routeProperties.join( - ", " - )}` + ", ", + )}`, ); } } @@ -421,7 +421,7 @@ function checkHttpRouteProperties(route, action, name, application) { throw assertionError.get( "invalid_controller_definition", name, - `action "${action}" http "path" property must be a non-empty string` + `action "${action}" http "path" property must be a non-empty string`, ); } } diff --git a/lib/core/plugin/pluginContext.ts b/lib/core/plugin/pluginContext.ts index 3e112990d4..a14e4b7dca 100644 --- a/lib/core/plugin/pluginContext.ts +++ b/lib/core/plugin/pluginContext.ts @@ -130,7 +130,7 @@ export class PluginContext { connectionId: string, index: string, collection: string, - filters: JSONObject + filters: JSONObject, ) => Promise<{ roomId: string }>; /** @@ -139,7 +139,7 @@ export class PluginContext { unregister: ( connectionId: string, roomId: string, - notify: boolean + notify: boolean, ) => Promise; }; @@ -283,7 +283,7 @@ export class PluginContext { // eslint-disable-next-line no-inner-declarations function PluginContextRepository( collection: string, - ObjectConstructor: any = null + ObjectConstructor: any = null, ) { if (!collection) { throw contextError.get("missing_collection"); @@ -308,7 +308,7 @@ export class PluginContext { // eslint-disable-next-line no-inner-declarations function PluginContextESClient(): Client { return Elasticsearch.buildClient( - global.kuzzle.config.services.storageEngine.client + global.kuzzle.config.services.storageEngine.client, ); } @@ -319,7 +319,7 @@ export class PluginContext { Mutex: Mutex, Repository: PluginContextRepository as unknown as new ( collection: string, - objectConstructor: any + objectConstructor: any, ) => Repository, Request: instantiateRequest as any, RequestContext: RequestContext as any, @@ -369,7 +369,7 @@ export class PluginContext { }, { connectionId: connectionId, - } + }, ); return global.kuzzle.ask("core:realtime:subscribe", request); }, @@ -378,17 +378,17 @@ export class PluginContext { "core:realtime:unsubscribe", connectionId, roomId, - notify + notify, ), }, trigger: (eventName, payload) => global.kuzzle.pipe(`plugin-${pluginName}:${eventName}`, payload), validation: { addType: global.kuzzle.validation.addType.bind( - global.kuzzle.validation + global.kuzzle.validation, ), validate: global.kuzzle.validation.validate.bind( - global.kuzzle.validation + global.kuzzle.validation, ), }, }; @@ -423,7 +423,7 @@ function execute(request, callback) { ["subscribe", "unsubscribe"].includes(request.input.action) ) { return promback.reject( - contextError.get("unavailable_realtime", request.input.action) + contextError.get("unavailable_realtime", request.input.action), ); } @@ -500,7 +500,7 @@ function instantiateRequest(request, data, options = {}) { target.input.volatile = Object.assign( {}, _request.input.volatile, - _data.volatile + _data.volatile, ); } else { target.input.volatile = _request.input.volatile; diff --git a/lib/core/plugin/pluginManifest.js b/lib/core/plugin/pluginManifest.js index a3d27963d2..774f62d05e 100644 --- a/lib/core/plugin/pluginManifest.js +++ b/lib/core/plugin/pluginManifest.js @@ -45,7 +45,7 @@ class PluginManifest extends AbstractManifest { throw kerror.get( "invalid_privileged", this.path, - typeof this.raw.privileged + typeof this.raw.privileged, ); } this.privileged = this.raw.privileged; diff --git a/lib/core/plugin/pluginsManager.js b/lib/core/plugin/pluginsManager.js index d138fe1b79..a10c976074 100644 --- a/lib/core/plugin/pluginsManager.js +++ b/lib/core/plugin/pluginsManager.js @@ -67,10 +67,10 @@ class PluginsManager { this.routes = []; this.pluginsEnabledDir = path.resolve( - path.join(global.kuzzle.rootPath, "plugins", "enabled") + path.join(global.kuzzle.rootPath, "plugins", "enabled"), ); this.pluginsAvailableDir = path.resolve( - path.join(global.kuzzle.rootPath, "plugins", "available") + path.join(global.kuzzle.rootPath, "plugins", "available"), ); /** @@ -96,7 +96,7 @@ class PluginsManager { // @deprecated - Warn about the pipeTimeout configuration being obsolete if (this.config.common.pipeTimeout) { global.kuzzle.log.warn( - 'The configuration "plugins.common.pipeTimeout" has been deprecated and is now unused. It can be safely removed from configuration files' + 'The configuration "plugins.common.pipeTimeout" has been deprecated and is now unused. It can be safely removed from configuration files', ); } @@ -106,11 +106,11 @@ class PluginsManager { set application(plugin) { assert( this._plugins.size === 0, - "The application plugin can only be set before every other plugins are loaded" + "The application plugin can only be set before every other plugins are loaded", ); assert( plugin.application, - 'The application plugin must have the "application" property equals to true' + 'The application plugin must have the "application" property equals to true', ); this._plugins.set(plugin.name, plugin); @@ -118,13 +118,13 @@ class PluginsManager { get plugins() { return Array.from(this._plugins.values()).filter( - (plugin) => !plugin.application + (plugin) => !plugin.application, ); } get application() { return Array.from(this._plugins.values()).find( - (plugin) => plugin.application + (plugin) => plugin.application, ); } @@ -193,7 +193,7 @@ class PluginsManager { debug( "[%s] reading plugin configuration: %a", plugin, - pluginsDescription[plugin.name] + pluginsDescription[plugin.name], ); } @@ -212,13 +212,13 @@ class PluginsManager { global.kuzzle.on("plugin:hook:loop-error", ({ error, pluginName }) => { global.kuzzle.log.error( - `[${pluginName}] Infinite loop detected on event "hook:onError": ${error}` + `[${pluginName}] Infinite loop detected on event "hook:onError": ${error}`, ); }); global.kuzzle.on("hook:onError", ({ error, event, pluginName }) => { global.kuzzle.log.error( - `[${pluginName}] Error executing hook on "${event}": ${error}${error.stack}` + `[${pluginName}] Error executing hook on "${event}": ${error}${error.stack}`, ); }); @@ -232,7 +232,7 @@ class PluginsManager { !CORE_PLUGINS.includes(plugin.name) ) { global.kuzzle.log.info( - `Failsafe mode activated, skipping plugin "${plugin.name}"` + `Failsafe mode activated, skipping plugin "${plugin.name}"`, ); continue; } @@ -246,7 +246,7 @@ class PluginsManager { debug( '[%s] starting plugin in "%s" mode', plugin.name, - plugin.config.privileged ? "privileged" : "standard" + plugin.config.privileged ? "privileged" : "standard", ); const promise = Bluebird.resolve( @@ -256,11 +256,11 @@ class PluginsManager { } catch (error) { throw runtimeError.get("failed_init", plugin.name, error); } - })() + })(), ) .timeout( initTimeout, - `${plugin.logPrefix} Initialization timed out after ${initTimeout}ms. Try to increase the configuration "plugins.common.initTimeout".` + `${plugin.logPrefix} Initialization timed out after ${initTimeout}ms. Try to increase the configuration "plugins.common.initTimeout".`, ) .then(async () => { plugin.initCalled = true; @@ -381,7 +381,7 @@ class PluginsManager { "invalid_method_type", errorPrefix, methodName, - strategy.methods[methodName] + strategy.methods[methodName], ); } @@ -389,10 +389,10 @@ class PluginsManager { throw strategyError.get( "missing_method_function", errorPrefix, - strategy.methods[methodName] + strategy.methods[methodName], ); } - } + }, ); // optional methods check @@ -405,7 +405,7 @@ class PluginsManager { "invalid_method_type", errorPrefix, name, - optionalMethodName + optionalMethodName, ); } @@ -413,7 +413,7 @@ class PluginsManager { throw strategyError.get( "missing_method_function", errorPrefix, - optionalMethodName + optionalMethodName, ); } } @@ -427,7 +427,7 @@ class PluginsManager { throw strategyError.get( "invalid_authenticator", errorPrefix, - strategy.config.authenticator + strategy.config.authenticator, ); } else if ( !this.authenticators[pluginName] || @@ -436,7 +436,7 @@ class PluginsManager { throw strategyError.get( "unknown_authenticator", errorPrefix, - strategy.config.authenticator + strategy.config.authenticator, ); } @@ -448,7 +448,7 @@ class PluginsManager { "invalid_option", errorPrefix, optionName, - options + options, ); } } @@ -460,7 +460,7 @@ class PluginsManager { throw strategyError.get( "invalid_fields", errorPrefix, - strategy.config.fields + strategy.config.fields, ); } } @@ -493,7 +493,7 @@ class PluginsManager { if (elapsed > warnDelay) { global.kuzzle.log.warn( - `${plugin.logPrefix} pipe for event '${event}' is slow (${elapsed}ms)` + `${plugin.logPrefix} pipe for event '${event}' is slow (${elapsed}ms)`, ); } } @@ -522,7 +522,7 @@ class PluginsManager { cb( error instanceof KuzzleError ? error - : runtimeError.getFrom(error, "unexpected_error", error.message) + : runtimeError.getFrom(error, "unexpected_error", error.message), ); } }; @@ -570,7 +570,7 @@ class PluginsManager { // convert uncaught exception into PluginImplementationError // promise rejections for (const methodName of Object.keys(strategy.methods).filter( - (name) => name !== "verify" + (name) => name !== "verify", )) { methods[methodName] = async (...args) => { try { @@ -597,7 +597,7 @@ class PluginsManager { const verifyAdapter = this.wrapStrategyVerify( plugin.logPrefix, strategyName, - plugin.instance[strategy.methods.verify].bind(plugin.instance) + plugin.instance[strategy.methods.verify].bind(plugin.instance), ); try { @@ -609,7 +609,7 @@ class PluginsManager { global.kuzzle.passport.use( strategyName, instance, - strategy.config.authenticateOptions + strategy.config.authenticateOptions, ); if (methods.afterRegister) { @@ -620,7 +620,7 @@ class PluginsManager { e, "failed_registration", strategyName, - e.message + e.message, ); } } @@ -673,7 +673,7 @@ class PluginsManager { if (typeof target === "string") { // @deprecated - warn about using a string representing an instance method plugin.printDeprecation( - "Defining pipe handler using a string is deprecated. Pass a function instead." + "Defining pipe handler using a string is deprecated. Pass a function instead.", ); handler = plugin.instance[target].bind(plugin.instance); @@ -717,7 +717,7 @@ class PluginsManager { // @deprecated - warn about using a string representing an instance method if (typeof target === "string") { plugin.printDeprecation( - "Defining hook handler using a string is deprecated. Pass a function instead." + "Defining hook handler using a string is deprecated. Pass a function instead.", ); handler = plugin.instance[target].bind(plugin.instance); @@ -736,31 +736,31 @@ class PluginsManager { async _initApi(plugin) { for (const [controller, definition] of Object.entries( - plugin.instance.api + plugin.instance.api, )) { debug( "[%s][%s] starting api controller registration", plugin.name, - controller + controller, ); if ( await global.kuzzle.ask( "kuzzle:api:funnel:controller:isNative", - controller + controller, ) ) { throw assertionError.get( "invalid_controller_definition", controller, - "Native controllers cannot be overriden" + "Native controllers cannot be overriden", ); } Plugin.checkControllerDefinition(controller, definition); for (const [action, actionDefinition] of Object.entries( - definition.actions + definition.actions, )) { let apiController = this.controllers.get(controller); @@ -788,7 +788,7 @@ class PluginsManager { if (httpRoutes.length === 0) { httpRoutes.push({ path: `${Inflector.kebabCase(controller)}/${Inflector.kebabCase( - action + action, )}`, verb: "get", }); @@ -799,7 +799,7 @@ class PluginsManager { '[%s] binding HTTP route "%s" to controller "%s"', plugin.name, httpRoute.path, - controller + controller, ); const routePath = @@ -829,7 +829,7 @@ class PluginsManager { // @deprecated - warn about using the obsolete "controllers" object if (!_.isEmpty(plugin.instance.controllers)) { plugin.printDeprecation( - 'Defining controllers using the "controllers" object is deprecated. You should use the "api" object instead.' + 'Defining controllers using the "controllers" object is deprecated. You should use the "api" object instead.', ); } @@ -837,7 +837,7 @@ class PluginsManager { debug( "[%s][%s] starting controller registration", plugin.name, - controller + controller, ); const methodsList = getMethods(plugin.instance); @@ -850,7 +850,7 @@ class PluginsManager { throw controllerError.get( "invalid_description", errorControllerPrefix, - typeof definition + typeof definition, ); } @@ -859,7 +859,7 @@ class PluginsManager { "[%s][%s][%s] starting action controller registration", plugin.name, controller, - action + action, ); if ( @@ -876,7 +876,7 @@ class PluginsManager { errorControllerPrefix, controller, action, - suggestion + suggestion, ); } @@ -892,7 +892,7 @@ class PluginsManager { } else { apiController._addAction( action, - plugin.instance[definition[action]].bind(plugin.instance) + plugin.instance[definition[action]].bind(plugin.instance), ); } } @@ -913,14 +913,14 @@ class PluginsManager { // @deprecated - warn about using the obsolete "routes" object if (!_.isEmpty(plugin.instance.routes)) { plugin.printDeprecation( - 'Defining routes using the "routes" object is deprecated. You should use the "api" object instead.' + 'Defining routes using the "routes" object is deprecated. You should use the "api" object instead.', ); } for (const route of plugin.instance.routes || []) { const controller = `${plugin.name}/${route.controller}`; const errorRoutePrefix = `Unable to inject API route "${JSON.stringify( - route + route, )}" from plugin "${plugin.name}":`; for (const key of Object.keys(route)) { @@ -929,7 +929,7 @@ class PluginsManager { "unexpected_route_property", errorRoutePrefix, key, - didYouMean(key, routeProperties) + didYouMean(key, routeProperties), ); } @@ -940,7 +940,7 @@ class PluginsManager { throw controllerError.get( "invalid_route_property", errorRoutePrefix, - key + key, ); } } @@ -952,7 +952,7 @@ class PluginsManager { "undefined_controller", errorRoutePrefix, route.controller, - didYouMean(route.controller, controllerNames) + didYouMean(route.controller, controllerNames), ); } @@ -962,7 +962,7 @@ class PluginsManager { "undefined_action", errorRoutePrefix, route.action, - didYouMean(route.action, actionNames) + didYouMean(route.action, actionNames), ); } @@ -971,14 +971,14 @@ class PluginsManager { "unsupported_verb", errorRoutePrefix, httpVerbs.join(", "), - didYouMean(route.verb, httpVerbs) + didYouMean(route.verb, httpVerbs), ); } // @deprecated route.url is deprecated if (route.url) { plugin.printDeprecation( - 'Usage of "url" property for routes is deprecated. Use "path" instead.' + 'Usage of "url" property for routes is deprecated. Use "path" instead.', ); } route.path = route.path || route.url; @@ -987,7 +987,7 @@ class PluginsManager { '[%s] binding HTTP route "%s" to controller "%s"', plugin.name, route.path, - route.controller + route.controller, ); // @deprecated "/_plugin" prefix is deprecated for plugin routes @@ -1028,7 +1028,7 @@ class PluginsManager { this.registerStrategy( plugin.name, name, - plugin.instance.strategies[name] + plugin.instance.strategies[name], ); } } @@ -1043,7 +1043,7 @@ class PluginsManager { "plugin", "authenticators", "not_an_object", - plugin.logPrefix + plugin.logPrefix, ); } @@ -1054,14 +1054,14 @@ class PluginsManager { "authenticators", "invalid_authenticator", plugin.logPrefix, - authenticator + authenticator, ); } } this.authenticators[plugin.name] = Object.assign( {}, - plugin.instance.authenticators + plugin.instance.authenticators, ); } @@ -1075,7 +1075,7 @@ class PluginsManager { // first load plugins from Backend.plugin.use for (const [name, { plugin: instance, options }] of Object.entries( - plugins + plugins, )) { const plugin = new Plugin(instance, { name, ...options }); @@ -1108,7 +1108,7 @@ class PluginsManager { throw assertionError.get( "invalid_plugins_dir", this.pluginsEnabledDir, - e.message + e.message, ); } @@ -1175,7 +1175,7 @@ class PluginsManager { try { const user = await global.kuzzle.ask( "core:security:user:get", - result.kuid + result.kuid, ); callback(null, user); @@ -1226,11 +1226,11 @@ function getMethods(object) { const prototype = Object.getPrototypeOf(object); const instanceMethods = Object.getOwnPropertyNames(prototype).filter( - (method) => ["init", "constructor"].indexOf(method) === -1 + (method) => ["init", "constructor"].indexOf(method) === -1, ); const objectMethods = Object.getOwnPropertyNames(object).filter( - (key) => typeof object[key] === "function" + (key) => typeof object[key] === "function", ); return [...instanceMethods, ...objectMethods]; diff --git a/lib/core/realtime/channel.ts b/lib/core/realtime/channel.ts index f806d94ea0..67f094c5af 100644 --- a/lib/core/realtime/channel.ts +++ b/lib/core/realtime/channel.ts @@ -138,7 +138,7 @@ export class Channel { scope?: RealtimeScope; users?: RealtimeUsers; propagate?: boolean; - } = {} + } = {}, ) { this.scope = scope; this.users = users; diff --git a/lib/core/realtime/hotelClerk.ts b/lib/core/realtime/hotelClerk.ts index 99f904bc7c..d92d7f53fc 100644 --- a/lib/core/realtime/hotelClerk.ts +++ b/lib/core/realtime/hotelClerk.ts @@ -111,7 +111,7 @@ export class HotelClerk { */ global.kuzzle.onAsk( "core:realtime:room:create", - (index, collection, roomId) => this.newRoom(index, collection, roomId) + (index, collection, roomId) => this.newRoom(index, collection, roomId), ); /** @@ -139,7 +139,7 @@ export class HotelClerk { * @return {Array.} */ global.kuzzle.onAsk("core:realtime:collections:get", (index) => - this.listCollections(index) + this.listCollections(index), ); /** @@ -147,7 +147,7 @@ export class HotelClerk { * @param {string} connectionId */ global.kuzzle.onAsk("core:realtime:connection:remove", (connectionId) => - this.removeConnection(connectionId) + this.removeConnection(connectionId), ); /** @@ -156,7 +156,7 @@ export class HotelClerk { * @return {Object|null} */ global.kuzzle.onAsk("core:realtime:subscribe", (request) => - this.subscribe(request) + this.subscribe(request), ); /** @@ -170,7 +170,7 @@ export class HotelClerk { "core:realtime:unsubscribe", (connectionId, roomId, notify) => { return this.unsubscribe(connectionId, roomId, notify); - } + }, ); /** @@ -178,7 +178,7 @@ export class HotelClerk { * @return {{rooms: number, subscriptions: number}} */ global.kuzzle.onAsk("core:realtime:hotelClerk:metrics", () => - this.metrics() + this.metrics(), ); /** @@ -191,7 +191,7 @@ export class HotelClerk { */ global.kuzzle.on("connection:remove", (connection) => { this.removeConnection(connection.id).catch((err) => - global.kuzzle.log.info(err) + global.kuzzle.log.info(err), ); }); } @@ -209,7 +209,7 @@ export class HotelClerk { * during room creation */ async subscribe( - request: KuzzleRequest + request: KuzzleRequest, ): Promise<{ channel: string; roomId: string }> { const { index, collection } = request.input.resource; @@ -241,7 +241,7 @@ export class HotelClerk { try { normalized = this.koncorde.normalize( request.input.body, - toKoncordeIndex(index, collection) + toKoncordeIndex(index, collection), ); } catch (e) { throw kerror.get("api", "assert", "koncorde_dsl_error", e.message); @@ -284,7 +284,7 @@ export class HotelClerk { const { channel } = await this.subscribeToRoom( normalized.id, request, - afterSubscribeCallback + afterSubscribeCallback, ); const subscription = new Subscription( @@ -293,7 +293,7 @@ export class HotelClerk { request.input.body, normalized.id, request.context.connection.id, - request.context.user + request.context.user, ); global.kuzzle.emit("core:realtime:user:subscribe:after", subscription); @@ -323,7 +323,7 @@ export class HotelClerk { if (!this.rooms.has(roomId)) { const normalized: NormalizedFilter = await global.kuzzle.ask( "cluster:realtime:filters:get", - roomId + roomId, ); if (!normalized) { @@ -357,7 +357,7 @@ export class HotelClerk { const { channel } = await this.subscribeToRoom( roomId, request, - afterSubscribeCallback + afterSubscribeCallback, ); return { @@ -376,7 +376,7 @@ export class HotelClerk { // in Koncorde: the latter also contains subscriptions created by the // framework (or by plugins), and we don't want those to appear in the API const fullStateRooms: RoomList = await global.kuzzle.ask( - "cluster:realtime:room:list" + "cluster:realtime:room:list", ); const isAllowedRequest = new KuzzleRequest( @@ -384,7 +384,7 @@ export class HotelClerk { action: "subscribe", controller: "realtime", }, - {} + {}, ); for (const [index, collections] of Object.entries(fullStateRooms)) { @@ -396,7 +396,7 @@ export class HotelClerk { isAllowedRequest.input.resource.collection = collection; return !user.isActionAllowed(isAllowedRequest); - } + }, ); for (const collection of toRemove) { @@ -422,8 +422,8 @@ export class HotelClerk { await Bluebird.map(connectionRooms.roomIds, (roomId: string) => this.unsubscribe(connectionId, roomId, notify).catch( - global.kuzzle.log.error - ) + global.kuzzle.log.error, + ), ); } @@ -434,7 +434,7 @@ export class HotelClerk { */ async clearConnections(): Promise { await Bluebird.map(this.subscriptions.keys(), (connectionId: string) => - this.removeConnection(connectionId, false) + this.removeConnection(connectionId, false), ); } @@ -446,7 +446,7 @@ export class HotelClerk { private registerSubscription( connectionId: string, roomId: string, - volatile: JSONObject + volatile: JSONObject, ): void { debug("Add room %s for connection %s", roomId, connectionId); @@ -562,7 +562,7 @@ export class HotelClerk { index: room.index, volatile, }, - requestContext + requestContext, ); // Do not send an unsubscription notification if the room has been destroyed @@ -598,7 +598,7 @@ export class HotelClerk { undefined, roomId, connectionId, - { _id: kuid } + { _id: kuid }, ); global.kuzzle.emit("core:realtime:user:unsubscribe:after", { @@ -658,8 +658,8 @@ export class HotelClerk { request: KuzzleRequest, afterSubscribeCallback: ( subscribed: boolean, - cluster: boolean - ) => Promise + cluster: boolean, + ) => Promise, ): Promise<{ channel: string; cluster: boolean; subscribed: boolean }> { let subscribed = false; let notifyPromise; diff --git a/lib/core/realtime/notifier.js b/lib/core/realtime/notifier.js index cb0e9bc7e8..c722963dcb 100644 --- a/lib/core/realtime/notifier.js +++ b/lib/core/realtime/notifier.js @@ -70,7 +70,7 @@ class NotifierController { "core:realtime:document:dispatch", (rooms, notification, opts) => { return this._notifyDocument(rooms, notification, opts); - } + }, ); /** @@ -84,7 +84,7 @@ class NotifierController { "core:realtime:user:sendMessage", (room, notification, opts) => { return this._notifyUser(room, notification, opts); - } + }, ); /** @@ -95,7 +95,7 @@ class NotifierController { */ global.kuzzle.onAsk( "core:realtime:document:mNotify", - (request, action, docs) => this.notifyDocuments(request, action, docs) + (request, action, docs) => this.notifyDocuments(request, action, docs), ); /** @@ -106,7 +106,7 @@ class NotifierController { */ global.kuzzle.onAsk( "core:realtime:document:notify", - (request, action, doc) => this.notifyDocuments(request, action, [doc]) + (request, action, doc) => this.notifyDocuments(request, action, [doc]), ); /** @@ -114,7 +114,7 @@ class NotifierController { * @param {string} connectionId */ global.kuzzle.onAsk("core:realtime:tokenExpired:notify", (connectionId) => - this.notifyTokenExpired(connectionId) + this.notifyTokenExpired(connectionId), ); /** @@ -122,7 +122,7 @@ class NotifierController { * @param {Request} request */ global.kuzzle.onAsk("core:realtime:publish", (request) => - this.publish(request) + this.publish(request), ); } @@ -146,7 +146,7 @@ class NotifierController { request, scope, action, - content + content, ); global.kuzzle.emit("core:notify:document", { @@ -194,7 +194,7 @@ class NotifierController { "notify:server", [KUZZLE_NOTIFICATION_CHANNEL], // Sending notification on Kuzzle notification channel new ServerNotification("TokenExpired", "Authentication Token Expired"), - connectionId + connectionId, ); await this.module.hotelClerk.removeConnection(connectionId); @@ -259,7 +259,7 @@ class NotifierController { request, "out", "replace", - document + document, ); } @@ -321,7 +321,7 @@ class NotifierController { "core", "fatal", "assertion_failed", - `unknown notify action "${doc.action}"` + `unknown notify action "${doc.action}"`, ); } }); @@ -334,7 +334,7 @@ class NotifierController { "core:cache:internal:store", cacheIds[index], JSON.stringify(rooms), - { ttl: this.ttl } + { ttl: this.ttl }, ); } @@ -369,7 +369,7 @@ class NotifierController { request, "out", "update", - document + document, ); } @@ -419,7 +419,7 @@ class NotifierController { channels: channels, connectionId: connectionId, notification: updated, - } + }, ); const action = updatedInfo.connectionId ? "notify" : "broadcast"; @@ -526,7 +526,7 @@ class NotifierController { request.input.args.index, request.input.args.collection, source || request.input.body || {}, - id || request.input.args._id + id || request.input.args._id, ); } } diff --git a/lib/core/realtime/room.ts b/lib/core/realtime/room.ts index 91d2679c49..440c1bc796 100644 --- a/lib/core/realtime/room.ts +++ b/lib/core/realtime/room.ts @@ -82,7 +82,7 @@ export class Room { index: string, collection: string, channels?: Map, - connections?: Set + connections?: Set, ) { this.id = id; this.index = index; diff --git a/lib/core/realtime/subscription.ts b/lib/core/realtime/subscription.ts index f3271eda82..ab49e5fed3 100644 --- a/lib/core/realtime/subscription.ts +++ b/lib/core/realtime/subscription.ts @@ -50,7 +50,7 @@ export class Subscription { filters: JSONObject, roomId: string, connectionId: string, - user: { _id: string } + user: { _id: string }, ) { this.connectionId = connectionId; this.roomId = roomId; diff --git a/lib/core/security/profileRepository.ts b/lib/core/security/profileRepository.ts index b602c321ff..e0ec51187d 100644 --- a/lib/core/security/profileRepository.ts +++ b/lib/core/security/profileRepository.ts @@ -87,7 +87,7 @@ export class ProfileRepository extends Repository { * @throws If already exists or if the policies are invalid */ global.kuzzle.onAsk("core:security:profile:create", (id, policies, opts) => - this.create(id, policies, opts) + this.create(id, policies, opts), ); /** @@ -100,7 +100,7 @@ export class ProfileRepository extends Repository { */ global.kuzzle.onAsk( "core:security:profile:createOrReplace", - (id, policies, opts) => this.createOrReplace(id, policies, opts) + (id, policies, opts) => this.createOrReplace(id, policies, opts), ); /** @@ -111,7 +111,7 @@ export class ProfileRepository extends Repository { * still in use */ global.kuzzle.onAsk("core:security:profile:delete", (id, opts) => - this.deleteById(id, opts) + this.deleteById(id, opts), ); /** @@ -129,7 +129,7 @@ export class ProfileRepository extends Repository { * @param {String} [id] - profile identifier */ global.kuzzle.onAsk("core:security:profile:invalidate", (id) => - this.invalidate(id) + this.invalidate(id), ); /** @@ -139,7 +139,7 @@ export class ProfileRepository extends Repository { * @throws If one or more profiles don't exist */ global.kuzzle.onAsk("core:security:profile:mGet", (ids) => - this.loadProfiles(ids) + this.loadProfiles(ids), ); /** @@ -149,7 +149,7 @@ export class ProfileRepository extends Repository { * @returns {Object} Search results */ global.kuzzle.onAsk("core:security:profile:scroll", (id, ttl) => - this.scroll(id, ttl) + this.scroll(id, ttl), ); /** @@ -161,7 +161,7 @@ export class ProfileRepository extends Repository { * @returns {Object} Search results */ global.kuzzle.onAsk("core:security:profile:search", (searchBody, opts) => - this.search(searchBody, opts) + this.search(searchBody, opts), ); /** @@ -169,7 +169,7 @@ export class ProfileRepository extends Repository { * @param {Object} opts (refresh) */ global.kuzzle.onAsk("core:security:profile:truncate", (opts) => - this.truncate(opts) + this.truncate(opts), ); /** @@ -180,7 +180,7 @@ export class ProfileRepository extends Repository { * @returns {Profile} Updated profile */ global.kuzzle.onAsk("core:security:profile:update", (id, content, opts) => - this.update(id, content, opts) + this.update(id, content, opts), ); } @@ -227,7 +227,7 @@ export class ProfileRepository extends Repository { "assert", "invalid_type", "profileIds", - "string[]" + "string[]", ); } @@ -278,7 +278,7 @@ export class ProfileRepository extends Repository { refresh = "false", strict, userId = null, - }: CreateOrReplaceOptions = {} + }: CreateOrReplaceOptions = {}, ) { const profile = await this.fromDTO({ // content should be first: ignores _id and _kuzzle_info in it @@ -306,7 +306,7 @@ export class ProfileRepository extends Repository { async create( id: string, content: JSONObject, - opts: JSONObject = {} + opts: JSONObject = {}, ): Promise { return this._createOrReplace(id, content, { method: "create", @@ -325,7 +325,7 @@ export class ProfileRepository extends Repository { async createOrReplace( id: string, content: JSONObject, - opts: JSONObject = {} + opts: JSONObject = {}, ): Promise { return this._createOrReplace(id, content, { method: "createOrReplace", @@ -343,7 +343,7 @@ export class ProfileRepository extends Repository { async update( id: string, content: JSONObject, - { refresh, retryOnConflict, strict, userId }: UpdateOptions = {} + { refresh, retryOnConflict, strict, userId }: UpdateOptions = {}, ) { const profile = await this.load(id); const pojo = super.toDTO(profile); @@ -384,7 +384,7 @@ export class ProfileRepository extends Repository { */ async delete( profile: Profile, - { refresh = "false", onAssignedUsers = "fail", userId = "-1" } = {} + { refresh = "false", onAssignedUsers = "fail", userId = "-1" } = {}, ) { if (["admin", "default", "anonymous"].includes(profile._id)) { throw kerror.get("security", "profile", "cannot_delete"); @@ -401,7 +401,7 @@ export class ProfileRepository extends Repository { let treated = 0; let userPage = await this.module.user.search( { query }, - { scroll: "1m", size: 100 } + { scroll: "1m", size: 100 }, ); while (treated < userPage.total) { @@ -418,7 +418,7 @@ export class ProfileRepository extends Repository { this.module.user.update(user._id, user.profileIds, user, { refresh, userId, - }) + }), ); } @@ -433,7 +433,7 @@ export class ProfileRepository extends Repository { } else { const hits = await this.module.user.search( { query }, - { from: 0, size: 1 } + { from: 0, size: 1 }, ); if (hits.total > 0) { @@ -478,7 +478,7 @@ export class ProfileRepository extends Repository { refresh, retryOnConflict, strict, - }: ValidateAndSaveProfileOptions = {} + }: ValidateAndSaveProfileOptions = {}, ) { const policiesRoles = profile.policies.map((p) => p.roleId); @@ -504,7 +504,7 @@ export class ProfileRepository extends Repository { const updatedProfile = await this.loadOneFromDatabase(profile._id); // Recompute optimized policies based on new policies updatedProfile.optimizedPolicies = this.optimizePolicies( - updatedProfile.policies + updatedProfile.policies, ); this.profiles.set(profile._id, updatedProfile); diff --git a/lib/core/security/roleRepository.js b/lib/core/security/roleRepository.js index c55ef0b032..fd71984c11 100644 --- a/lib/core/security/roleRepository.js +++ b/lib/core/security/roleRepository.js @@ -64,7 +64,7 @@ class RoleRepository extends Repository { * @throws If already exists or if the content is invalid */ global.kuzzle.onAsk("core:security:role:create", (id, content, opts) => - this.create(id, content, opts) + this.create(id, content, opts), ); /** @@ -77,7 +77,7 @@ class RoleRepository extends Repository { */ global.kuzzle.onAsk( "core:security:role:createOrReplace", - (id, content, opts) => this.createOrReplace(id, content, opts) + (id, content, opts) => this.createOrReplace(id, content, opts), ); /** @@ -88,7 +88,7 @@ class RoleRepository extends Repository { * still in use */ global.kuzzle.onAsk("core:security:role:delete", (id, opts) => - this.deleteById(id, opts) + this.deleteById(id, opts), ); /** @@ -106,7 +106,7 @@ class RoleRepository extends Repository { * @param {String} [id] - role identifier */ global.kuzzle.onAsk("core:security:role:invalidate", (id) => - this.invalidate(id) + this.invalidate(id), ); /** @@ -116,7 +116,7 @@ class RoleRepository extends Repository { * @throws If one or more roles don't exist */ global.kuzzle.onAsk("core:security:role:mGet", (ids) => - this.loadRoles(ids) + this.loadRoles(ids), ); /** @@ -127,7 +127,7 @@ class RoleRepository extends Repository { * @returns {Object} Search results */ global.kuzzle.onAsk("core:security:role:search", (controllers, opts) => - this.searchRole(controllers, opts) + this.searchRole(controllers, opts), ); /** @@ -135,7 +135,7 @@ class RoleRepository extends Repository { * @param {Object} opts (refresh) */ global.kuzzle.onAsk("core:security:role:truncate", (opts) => - this.truncate(opts) + this.truncate(opts), ); /** @@ -147,7 +147,7 @@ class RoleRepository extends Repository { * @returns {Role} Updated role */ global.kuzzle.onAsk("core:security:role:update", (id, content, opts) => - this.update(id, content, opts) + this.update(id, content, opts), ); /** @@ -195,7 +195,7 @@ class RoleRepository extends Repository { async _createOrReplace( id, content, - { force = false, method, refresh = "false", userId = null } = {} + { force = false, method, refresh = "false", userId = null } = {}, ) { const dto = { ...content, @@ -319,7 +319,7 @@ class RoleRepository extends Repository { const searchResults = await this.search( { query: {}, sort: [{ _id: { order: "asc" } }] }, - { from: 0, size: 9999 } + { from: 0, size: 9999 }, ); // /!\ NOT the options values const result = { @@ -330,8 +330,8 @@ class RoleRepository extends Repository { if (body.controllers.length > 0) { result.hits = searchResults.hits.filter((role) => Object.keys(role.controllers).some( - (key) => key === "*" || body.controllers.includes(key) - ) + (key) => key === "*" || body.controllers.includes(key), + ), ); result.total = result.hits.length; @@ -397,7 +397,7 @@ class RoleRepository extends Repository { role._id, action, roleController, - didYouMean(action, controller.__actions) + didYouMean(action, controller.__actions), ); } }); @@ -428,7 +428,7 @@ class RoleRepository extends Repository { "unknown_controller", role._id, roleController, - didYouMean(roleController, plugins.getControllerNames()) + didYouMean(roleController, plugins.getControllerNames()), ); } @@ -439,7 +439,7 @@ class RoleRepository extends Repository { // made after plugins controllers loading. if (global.kuzzle.state === kuzzleStateEnum.RUNNING || forceWarn) { global.kuzzle.log.warn( - `The role "${role._id}" gives access to the non-existing controller "${roleController}".` + `The role "${role._id}" gives access to the non-existing controller "${roleController}".`, ); } @@ -455,14 +455,14 @@ class RoleRepository extends Repository { role._id, action, roleController, - didYouMean(action, plugins.getActions(roleController)) + didYouMean(action, plugins.getActions(roleController)), ); } // see the other comment if (global.kuzzle.state === kuzzleStateEnum.RUNNING || forceWarn) { global.kuzzle.log.warn( - `The role "${role._id}" gives access to the non-existing action "${action}" for the controller "${roleController}".` + `The role "${role._id}" gives access to the non-existing action "${action}" for the controller "${roleController}".`, ); } } @@ -510,7 +510,7 @@ class RoleRepository extends Repository { { from: 0, size: 1, - } + }, ); if (response.total > 0) { diff --git a/lib/core/security/securityLoader.js b/lib/core/security/securityLoader.js index ea57c81393..11de0007fc 100644 --- a/lib/core/security/securityLoader.js +++ b/lib/core/security/securityLoader.js @@ -41,7 +41,7 @@ class SecurityLoader { * @param {Object} opts - force, onExistingUsers (fail), onExistingUsersWarning (false), user (null) */ global.kuzzle.onAsk("core:security:load", (json, opts) => - this.load(json, opts) + this.load(json, opts), ); } @@ -53,7 +53,7 @@ class SecurityLoader { onExistingUsersWarning = false, refresh = "false", user = null, - } = {} + } = {}, ) { assertIsObject(permissions); @@ -67,7 +67,7 @@ class SecurityLoader { "createOrReplaceProfile", permissions.profiles, "profiles", - { refresh, user } + { refresh, user }, ); const usersToLoad = await this._getUsersToLoad(permissions.users, { @@ -99,7 +99,7 @@ class SecurityLoader { force, refresh, }, - { user } + { user }, ); promises.push(global.kuzzle.funnel.processRequest(request)); @@ -135,7 +135,7 @@ class SecurityLoader { } else if (onExistingUsers === "skip") { if (warning) { global.kuzzle.log.info( - `Users skipped during import: ${existingUserIds}` + `Users skipped during import: ${existingUserIds}`, ); } return Object.entries(users).reduce((memo, [userId, content]) => { @@ -148,7 +148,7 @@ class SecurityLoader { } else if (onExistingUsers === "overwrite") { if (warning) { global.kuzzle.log.info( - `Users overwritten during import: ${existingUserIds}` + `Users overwritten during import: ${existingUserIds}`, ); } const mDeleteUsers = new Request({ @@ -167,7 +167,7 @@ class SecurityLoader { "assert", "unexpected_argument", "onExistingUsers", - ["skip", "overwrite", "fail"] + ["skip", "overwrite", "fail"], ); } } diff --git a/lib/core/security/tokenRepository.ts b/lib/core/security/tokenRepository.ts index 9b989ecf66..d0ccdd2754 100644 --- a/lib/core/security/tokenRepository.ts +++ b/lib/core/security/tokenRepository.ts @@ -54,7 +54,7 @@ export class TokenRepository extends Repository { } this.tokenGracePeriod = Math.floor( - global.kuzzle.config.security.jwt.gracePeriod + global.kuzzle.config.security.jwt.gracePeriod, ); this.anonymousToken = new Token({ userId: "-1" }); @@ -71,7 +71,7 @@ export class TokenRepository extends Repository { * @returns {Token} */ global.kuzzle.onAsk("core:security:token:assign", (hash, userId, ttl) => - this.persistForUser(hash, userId, { singleUse: false, ttl }) + this.persistForUser(hash, userId, { singleUse: false, ttl }), ); /** @@ -81,7 +81,7 @@ export class TokenRepository extends Repository { * @returns {Token} */ global.kuzzle.onAsk("core:security:token:create", (user, opts) => - this.generateToken(user, opts) + this.generateToken(user, opts), ); /** @@ -89,7 +89,7 @@ export class TokenRepository extends Repository { * @param {Token} token */ global.kuzzle.onAsk("core:security:token:delete", (token) => - this.expire(token) + this.expire(token), ); /** @@ -98,7 +98,7 @@ export class TokenRepository extends Repository { * @param {Objects} opts (keepApiKeys) */ global.kuzzle.onAsk("core:security:token:deleteByKuid", (kuid, opts) => - this.deleteByKuid(kuid, opts) + this.deleteByKuid(kuid, opts), ); /** @@ -108,7 +108,7 @@ export class TokenRepository extends Repository { * @returns {Token} */ global.kuzzle.onAsk("core:security:token:get", (userId, hash) => - this.loadForUser(userId, hash) + this.loadForUser(userId, hash), ); /** @@ -124,7 +124,7 @@ export class TokenRepository extends Repository { */ global.kuzzle.onAsk( "core:security:token:refresh", - (user, token, expiresIn) => this.refresh(user, token, expiresIn) + (user, token, expiresIn) => this.refresh(user, token, expiresIn), ); /** @@ -134,7 +134,7 @@ export class TokenRepository extends Repository { * @returns {Token} */ global.kuzzle.onAsk("core:security:token:verify", (hash) => - this.verifyToken(hash) + this.verifyToken(hash), ); } @@ -165,7 +165,7 @@ export class TokenRepository extends Repository { if (token.type === "apiKey" || token.ttl < 0) { throw securityError.get( "refresh_forbidden", - token.type === "apiKey" ? "API Key" : "Token with infinite TTL" + token.type === "apiKey" ? "API Key" : "Token with infinite TTL", ); } @@ -200,7 +200,7 @@ export class TokenRepository extends Repository { bypassMaxTTL?: boolean; type?: string; singleUse?: boolean; - } = {} + } = {}, ): Promise { if (!user || user._id === null) { throw securityError.get("unknown_user"); @@ -229,7 +229,7 @@ export class TokenRepository extends Repository { "assert", "invalid_argument", "expiresIn", - "a number of milliseconds, or a parsable timespan string" + "a number of milliseconds, or a parsable timespan string", ); } // -1 mean infite duration, so we don't pass the expiresIn option to @@ -243,7 +243,7 @@ export class TokenRepository extends Repository { encodedToken = jwt.sign( { _id: user._id }, global.kuzzle.secret, - signOptions + signOptions, ); } catch (err) { throw securityError.getFrom(err, "generation_failed", err.message); @@ -277,7 +277,7 @@ export class TokenRepository extends Repository { }: { ttl: number; singleUse: boolean; - } + }, ): Promise { const redisTTL = ttl === -1 ? 0 : ttl; const expiresAt = ttl === -1 ? -1 : Date.now() + ttl; @@ -298,7 +298,7 @@ export class TokenRepository extends Repository { "services", "cache", "write_failed", - err.message + err.message, ); } } @@ -389,7 +389,7 @@ export class TokenRepository extends Repository { const keys = await global.kuzzle.ask( "core:cache:internal:searchKeys", - userKey + userKey, ); /* @@ -450,7 +450,7 @@ export class TokenRepository extends Repository { try { const bootstrapped = await global.kuzzle.ask( "core:cache:internal:get", - BOOTSTRAP_DONE_KEY + BOOTSTRAP_DONE_KEY, ); if (bootstrapped) { @@ -468,7 +468,7 @@ export class TokenRepository extends Repository { this.persistForUser(_source.token, _source.userId, { singleUse: false, ttl: _source.ttl, - }) + }), ); } }); @@ -478,7 +478,7 @@ export class TokenRepository extends Repository { await global.kuzzle.ask( "core:cache:internal:store", BOOTSTRAP_DONE_KEY, - 1 + 1, ); } finally { await mutex.unlock(); diff --git a/lib/core/security/userRepository.js b/lib/core/security/userRepository.js index a5a1f2c90c..4bdc400d60 100644 --- a/lib/core/security/userRepository.js +++ b/lib/core/security/userRepository.js @@ -58,7 +58,7 @@ class UserRepository extends Repository { */ global.kuzzle.onAsk( "core:security:user:anonymous:get", - () => this.anonymousUser + () => this.anonymousUser, ); /** @@ -73,7 +73,7 @@ class UserRepository extends Repository { global.kuzzle.onAsk( "core:security:user:create", (id, profileIds, content, opts) => - this.create(id, profileIds, content, opts) + this.create(id, profileIds, content, opts), ); /** @@ -83,7 +83,7 @@ class UserRepository extends Repository { * @throws If the user doesn't exist */ global.kuzzle.onAsk("core:security:user:delete", (id, opts) => - this.deleteById(id, opts) + this.deleteById(id, opts), ); /** @@ -101,7 +101,7 @@ class UserRepository extends Repository { * @throws If one or more users don't exist */ global.kuzzle.onAsk("core:security:user:mGet", (ids) => - this.loadMultiFromDatabase(ids) + this.loadMultiFromDatabase(ids), ); /** @@ -114,7 +114,7 @@ class UserRepository extends Repository { global.kuzzle.onAsk( "core:security:user:replace", (id, profileIds, content, opts) => - this.replace(id, profileIds, content, opts) + this.replace(id, profileIds, content, opts), ); /** @@ -124,7 +124,7 @@ class UserRepository extends Repository { * @returns {Object} Search results */ global.kuzzle.onAsk("core:security:user:scroll", (id, ttl) => - this.scroll(id, ttl) + this.scroll(id, ttl), ); /** @@ -134,7 +134,7 @@ class UserRepository extends Repository { * @returns {Object} Search results */ global.kuzzle.onAsk("core:security:user:search", (searchBody, opts) => - this.search(searchBody, opts) + this.search(searchBody, opts), ); /** @@ -142,7 +142,7 @@ class UserRepository extends Repository { * @param {Object} opts (refresh) */ global.kuzzle.onAsk("core:security:user:truncate", (opts) => - this.truncate(opts) + this.truncate(opts), ); /** @@ -155,7 +155,7 @@ class UserRepository extends Repository { global.kuzzle.onAsk( "core:security:user:update", (id, profileIds, content, opts) => - this.update(id, profileIds, content, opts) + this.update(id, profileIds, content, opts), ); /** @@ -164,7 +164,7 @@ class UserRepository extends Repository { * @returns {Boolean} */ global.kuzzle.onAsk("core:security:user:admin:exist", () => - this.adminExists() + this.adminExists(), ); } @@ -216,7 +216,7 @@ class UserRepository extends Repository { id, profileIds, content, - { refresh = "false", retryOnConflict = 10, userId } = {} + { refresh = "false", retryOnConflict = 10, userId } = {}, ) { const user = await this.load(id); const pojo = this.toDTO(user); @@ -374,7 +374,7 @@ class UserRepository extends Repository { for (const strategy of availableStrategies) { const existStrategy = global.kuzzle.pluginsManager.getStrategyMethod( strategy, - "exists" + "exists", ); if (await existStrategy(request, user._id, strategy)) { @@ -387,7 +387,7 @@ class UserRepository extends Repository { for (const strategy of userStrategies) { const deleteStrategy = global.kuzzle.pluginsManager.getStrategyMethod( strategy, - "delete" + "delete", ); // We catch any error produced by delete as we want to make as much @@ -396,7 +396,7 @@ class UserRepository extends Repository { debug( "Deleting credentials on strategy %s for user %s", strategy, - user._id + user._id, ); await deleteStrategy(request, user._id, strategy); } catch (error) { @@ -410,7 +410,7 @@ class UserRepository extends Repository { "security", "credentials", "rejected", - errors.join("\n\t- ") + errors.join("\n\t- "), ); } } @@ -436,7 +436,7 @@ class UserRepository extends Repository { term: { profileIds: "admin" }, }, }, - { size: 1 } + { size: 1 }, ); return total >= 1; diff --git a/lib/core/shared/KoncordeWrapper.ts b/lib/core/shared/KoncordeWrapper.ts index a15379b7ba..498d8cf03a 100644 --- a/lib/core/shared/KoncordeWrapper.ts +++ b/lib/core/shared/KoncordeWrapper.ts @@ -194,12 +194,12 @@ export class Koncorde { async normalize( index: string, collection: string, - filter: JSONObject + filter: JSONObject, ): Promise { return new NormalizedFilterV3( index, collection, - this.koncorde.normalize(filter, toKoncordeIndex(index, collection)) + this.koncorde.normalize(filter, toKoncordeIndex(index, collection)), ); } @@ -215,7 +215,7 @@ export class Koncorde { async register( index: string, collection: string, - filter: JSONObject + filter: JSONObject, ): Promise { const indexV4 = toKoncordeIndex(index, collection); const normalized = this.koncorde.normalize(filter, indexV4); @@ -254,7 +254,7 @@ export class Koncorde { const normalizedV4 = new NormalizedFilter( normalized.normalized, normalized.id, - indexV4 + indexV4, ); this.koncorde.store(normalizedV4); @@ -281,7 +281,7 @@ export class Koncorde { index: string, collection: string, data: JSONObject, - id?: string + id?: string, ): string[] { return koncordeTest(this.koncorde, index, collection, data, id); } diff --git a/lib/core/shared/abstractManifest.js b/lib/core/shared/abstractManifest.js index c79fc84057..63fac163d2 100644 --- a/lib/core/shared/abstractManifest.js +++ b/lib/core/shared/abstractManifest.js @@ -62,7 +62,7 @@ class AbstractManifest { "version_mismatch", this.path, global.kuzzle.config.version, - this.kuzzleVersion + this.kuzzleVersion, ); } diff --git a/lib/core/shared/repository.ts b/lib/core/shared/repository.ts index 86d58f352a..b101943ff0 100644 --- a/lib/core/shared/repository.ts +++ b/lib/core/shared/repository.ts @@ -82,7 +82,7 @@ export class Repository { this.fromDTO({ ...item._source, _id: item._id, - }) + }), ); } @@ -102,7 +102,7 @@ export class Repository { const response = await this.store.search( this.collection, searchBody, - options + options, ); return this.formatSearchResults(response); @@ -130,7 +130,7 @@ export class Repository { */ async loadFromCache( id: string, - options: { key?: string } = {} + options: { key?: string } = {}, ): Promise { const key = options.key || this.getCacheKey(id); let response; @@ -204,7 +204,7 @@ export class Repository { return this.store.create( this.collection, this.serializeToDatabase(object), - { ...options, id: object._id } + { ...options, id: object._id }, ); } @@ -212,7 +212,7 @@ export class Repository { this.collection, object._id, this.serializeToDatabase(object), - options + options, ); } @@ -252,7 +252,7 @@ export class Repository { */ async persistToCache( object: TObject, - options: { key?: string; ttl?: number } = {} + options: { key?: string; ttl?: number } = {}, ): Promise { const key = options.key || this.getCacheKey(object._id); const value = JSON.stringify(this.serializeToCache(object)); @@ -284,7 +284,7 @@ export class Repository { */ refreshCacheTTL( object: JSONObject, - options: { key?: string; ttl?: number } = {} + options: { key?: string; ttl?: number } = {}, ) { const key = options.key || this.getCacheKey(object._id); let ttl; @@ -381,7 +381,7 @@ export class Repository { if (part === null) { const objects = await this.search( {}, - { refresh: options.refresh, scroll: "5s", size: 100 } + { refresh: options.refresh, scroll: "5s", size: 100 }, ); const deleted = await this.truncatePart(objects, options); @@ -470,7 +470,7 @@ export class Repository { this.fromDTO({ ...hit._source, _id: hit._id, - }) + }), ); } diff --git a/lib/core/shared/sdk/embeddedSdk.ts b/lib/core/shared/sdk/embeddedSdk.ts index f99635bf23..5d9d5e860c 100644 --- a/lib/core/shared/sdk/embeddedSdk.ts +++ b/lib/core/shared/sdk/embeddedSdk.ts @@ -111,7 +111,7 @@ interface EmbeddedRealtime extends RealtimeController { * Propagate the callback execution on each cluster node (default: false) */ propagate?: boolean; - } + }, ): Promise; } @@ -151,10 +151,10 @@ export class EmbeddedSDK extends Kuzzle { */ query< TRequest extends BaseRequest = BaseRequest, - TResult extends JSONObject = JSONObject + TResult extends JSONObject = JSONObject, >( request: TRequest, - options: { propagate?: boolean } = {} + options: { propagate?: boolean } = {}, ): Promise> { // By default, do not propagate realtime notification accross cluster nodes if ( @@ -179,7 +179,7 @@ export class EmbeddedSDK extends Kuzzle { "forbidden_embedded_sdk_action", request.controller, request.action, - ", use user impersonation or security controller instead" + ", use user impersonation or security controller instead", ); } diff --git a/lib/core/shared/sdk/funnelProtocol.ts b/lib/core/shared/sdk/funnelProtocol.ts index d87dcc65a4..65498ffd7b 100644 --- a/lib/core/shared/sdk/funnelProtocol.ts +++ b/lib/core/shared/sdk/funnelProtocol.ts @@ -51,7 +51,7 @@ export class FunnelProtocol extends KuzzleEventEmitter { async query(request: RequestPayload) { if (!this.connectionId) { this.connectionId = await global.kuzzle.ask( - "core:network:internal:connectionId:get" + "core:network:internal:connectionId:get", ); } @@ -71,7 +71,7 @@ export class FunnelProtocol extends KuzzleEventEmitter { // Get the user and store it in this context to prevent any possible race conditions requestOptions.user = await global.kuzzle.ask( "core:security:user:get", - request.__kuid__ + request.__kuid__, ); } @@ -88,13 +88,12 @@ export class FunnelProtocol extends KuzzleEventEmitter { "forbidden", kuzzleRequest.input.controller, kuzzleRequest.input.action, - requestOptions.user._id + requestOptions.user._id, ); } - const result = await global.kuzzle.funnel.executePluginRequest( - kuzzleRequest - ); + const result = + await global.kuzzle.funnel.executePluginRequest(kuzzleRequest); return { result }; } diff --git a/lib/core/shared/sdk/impersonatedSdk.js b/lib/core/shared/sdk/impersonatedSdk.js index e3e5d50def..373f439959 100644 --- a/lib/core/shared/sdk/impersonatedSdk.js +++ b/lib/core/shared/sdk/impersonatedSdk.js @@ -62,7 +62,7 @@ class ImpersonatedSDK { // Make sure we bring any local methods into our new custom context Object.getOwnPropertyNames( - Object.getPrototypeOf(global.app.sdk[controllerName]) + Object.getPrototypeOf(global.app.sdk[controllerName]), ).forEach((localMethod) => { if (!["constructor", "query"].includes(localMethod)) { customContext[localMethod] = diff --git a/lib/core/shared/store.js b/lib/core/shared/store.js index f174e5c49f..80d46cd683 100644 --- a/lib/core/shared/store.js +++ b/lib/core/shared/store.js @@ -77,7 +77,7 @@ class Store { global.kuzzle.ask( `core:storage:${scope}:document:scroll`, scrollId, - opts + opts, ); this.multiSearch = (targets, searchBody, opts) => @@ -85,7 +85,7 @@ class Store { `core:storage:${scope}:document:multiSearch`, targets, searchBody, - opts + opts, ); } @@ -137,7 +137,7 @@ class Store { this.index, collection, { mappings: config }, - { indexCacheOnly } + { indexCacheOnly }, ); } @@ -153,14 +153,14 @@ class Store { collection, // @deprecated isConfigDeprecated ? { mappings: config.mappings } : config, - { indexCacheOnly } + { indexCacheOnly }, ); } const exist = await global.kuzzle.ask( `core:storage:${this.scope}:collection:exist`, this.index, - collection + collection, ); if (exist) { @@ -172,7 +172,7 @@ class Store { const existingSettings = await global.kuzzle.ask( `core:storage:${this.scope}:collection:settings:get`, this.index, - collection + collection, ); if ( @@ -189,11 +189,11 @@ class Store { this.scope, "number_of_shards", config.settings.number_of_shards, - existingSettings.number_of_shards + existingSettings.number_of_shards, ); } global.kuzzle.log.warn( - `Attempt to recreate an existing collection ${collection} of index ${this.index} of scope ${this.scope} with non matching static setting : number_of_shards at ${config.settings.number_of_shards} while existing one is at ${existingSettings.number_of_shards}` + `Attempt to recreate an existing collection ${collection} of index ${this.index} of scope ${this.scope} with non matching static setting : number_of_shards at ${config.settings.number_of_shards} while existing one is at ${existingSettings.number_of_shards}`, ); } @@ -205,7 +205,7 @@ class Store { isConfigDeprecated ? { mappings: config.mappings } : { mappings: config.mappings, settings: dynamicSettings }, - { indexCacheOnly: true } + { indexCacheOnly: true }, ); } @@ -215,10 +215,10 @@ class Store { collection, // @deprecated isConfigDeprecated ? { mappings: config.mappings } : config, - { indexCacheOnly } + { indexCacheOnly }, ); }), - 10 + 10, ); } } diff --git a/lib/core/statistics/statistics.js b/lib/core/statistics/statistics.js index 69d06c4476..28b79edb3e 100644 --- a/lib/core/statistics/statistics.js +++ b/lib/core/statistics/statistics.js @@ -70,7 +70,7 @@ class Statistics { } else { this.currentStats.ongoingRequests.set( protocol, - this.currentStats.ongoingRequests.get(protocol) + 1 + this.currentStats.ongoingRequests.get(protocol) + 1, ); } } @@ -93,7 +93,7 @@ class Statistics { this.currentStats.ongoingRequests.set( protocol, - this.currentStats.ongoingRequests.get(protocol) - 1 + this.currentStats.ongoingRequests.get(protocol) - 1, ); if (!this.currentStats.completedRequests.has(protocol)) { @@ -101,7 +101,7 @@ class Statistics { } else { this.currentStats.completedRequests.set( protocol, - this.currentStats.completedRequests.get(protocol) + 1 + this.currentStats.completedRequests.get(protocol) + 1, ); } } @@ -124,7 +124,7 @@ class Statistics { this.currentStats.ongoingRequests.set( protocol, - this.currentStats.ongoingRequests.get(protocol) - 1 + this.currentStats.ongoingRequests.get(protocol) - 1, ); if (!this.currentStats.failedRequests.has(protocol)) { @@ -132,7 +132,7 @@ class Statistics { } else { this.currentStats.failedRequests.set( protocol, - this.currentStats.failedRequests.get(protocol) + 1 + this.currentStats.failedRequests.get(protocol) + 1, ); } } @@ -159,7 +159,7 @@ class Statistics { this.currentStats.connections.set( requestContext.connection.protocol, this.currentStats.connections.get(requestContext.connection.protocol) + - 1 + 1, ); } } @@ -187,7 +187,7 @@ class Statistics { this.currentStats.connections.set( requestContext.connection.protocol, this.currentStats.connections.get(requestContext.connection.protocol) - - 1 + 1, ); } } @@ -204,7 +204,7 @@ class Statistics { const frame = Object.assign( { timestamp: new Date().getTime() }, - this.currentStats + this.currentStats, ); if (!this.lastFrame) { @@ -213,7 +213,7 @@ class Statistics { const last = await global.kuzzle.ask( "core:cache:internal:get", - this.cacheKeyPrefix + this.lastFrame + this.cacheKeyPrefix + this.lastFrame, ); return Object.assign(frame, JSON.parse(last)); @@ -265,7 +265,7 @@ class Statistics { const stats = { completedRequests: Object.fromEntries( - this.currentStats.completedRequests + this.currentStats.completedRequests, ), connections: Object.fromEntries(this.currentStats.connections), failedRequests: Object.fromEntries(this.currentStats.failedRequests), @@ -275,7 +275,7 @@ class Statistics { if (!this.lastFrame) { if (!stopTime || stopTime >= currentDate) { response.hits.push( - Object.assign({ timestamp: new Date(currentDate).getTime() }, stats) + Object.assign({ timestamp: new Date(currentDate).getTime() }, stats), ); } @@ -286,14 +286,14 @@ class Statistics { const frames = await global.kuzzle.ask( "core:cache:internal:searchKeys", - `${this.cacheKeyPrefix}*` + `${this.cacheKeyPrefix}*`, ); // Statistics keys are timestamp. // Ordering them guarantees stats frames to be returned in the right order const values = await global.kuzzle.ask( "core:cache:internal:mget", - frames.sort() + frames.sort(), ); values.forEach((v, idx) => { @@ -308,7 +308,7 @@ class Statistics { response.hits.push( Object.assign(JSON.parse(v), { timestamp: new Date(frameDateTime).getTime(), - }) + }), ); } }); @@ -363,7 +363,7 @@ class Statistics { "core:cache:internal:store", this.cacheKeyPrefix + this.lastFrame, stats, - { ttl: this.ttl } + { ttl: this.ttl }, ); } } diff --git a/lib/core/storage/clientAdapter.js b/lib/core/storage/clientAdapter.js index a6712e8ff7..10e7e7bc4a 100644 --- a/lib/core/storage/clientAdapter.js +++ b/lib/core/storage/clientAdapter.js @@ -40,7 +40,7 @@ class ClientAdapter { constructor(scope) { this.client = new Elasticsearch( global.kuzzle.config.services.storageEngine, - scope + scope, ); this.scope = scope; this.cache = new IndexCache(); @@ -62,7 +62,7 @@ class ClientAdapter { * Manually refresh the index cache (e.g. after alias creation) */ global.kuzzle.onAsk(`core:storage:${this.scope}:cache:refresh`, () => - this.populateCache() + this.populateCache(), ); /** @@ -70,7 +70,7 @@ class ClientAdapter { * @returns {Promise.} */ global.kuzzle.onAsk(`core:storage:${this.scope}:info:get`, () => - this.client.info() + this.client.info(), ); /** @@ -80,7 +80,7 @@ class ClientAdapter { * @returns {Object} Equivalent Elasticsearch query */ global.kuzzle.onAsk(`core:storage:${this.scope}:translate`, (filters) => - this.client.translateKoncordeFilters(filters) + this.client.translateKoncordeFilters(filters), ); } @@ -107,7 +107,7 @@ class ClientAdapter { index, collection, opts, - { indexCacheOnly = false, propagate = true } = {} + { indexCacheOnly = false, propagate = true } = {}, ) { if (!indexCacheOnly) { await this.client.createCollection(index, collection, opts); @@ -205,7 +205,7 @@ class ClientAdapter { global.kuzzle.onAsk( `core:storage:${this.scope}:collection:create`, (index, collection, opts, creationOptions) => - this.createCollection(index, collection, opts, creationOptions) + this.createCollection(index, collection, opts, creationOptions), ); /** @@ -217,7 +217,7 @@ class ClientAdapter { */ global.kuzzle.onAsk( `core:storage:${this.scope}:collection:delete`, - (index, collection) => this.deleteCollection(index, collection) + (index, collection) => this.deleteCollection(index, collection), ); /** @@ -230,7 +230,7 @@ class ClientAdapter { (index, collection) => { this.cache.assertCollectionExists(index, collection); return this.client.getSettings(index, collection); - } + }, ); /** @@ -240,7 +240,7 @@ class ClientAdapter { */ global.kuzzle.onAsk( `core:storage:${this.scope}:collection:exist`, - (index, collection) => this.cache.hasCollection(index, collection) + (index, collection) => this.cache.hasCollection(index, collection), ); /** @@ -249,7 +249,7 @@ class ClientAdapter { * @returns {Promise.} */ global.kuzzle.onAsk(`core:storage:${this.scope}:collection:list`, (index) => - this.cache.listCollections(index) + this.cache.listCollections(index), ); /** @@ -263,7 +263,7 @@ class ClientAdapter { (index, collection) => { this.cache.assertCollectionExists(index, collection); return this.client.refreshCollection(index, collection); - } + }, ); /** @@ -277,7 +277,7 @@ class ClientAdapter { (index, collection) => { this.cache.assertCollectionExists(index, collection); return this.client.truncateCollection(index, collection); - } + }, ); /** @@ -292,7 +292,7 @@ class ClientAdapter { (index, collection, changes) => { this.cache.assertCollectionExists(index, collection); return this.client.updateCollection(index, collection, changes); - } + }, ); } @@ -306,7 +306,7 @@ class ClientAdapter { */ global.kuzzle.onAsk( `core:storage:${this.scope}:index:create`, - (index, options) => this.createIndex(index, options) + (index, options) => this.createIndex(index, options), ); /** @@ -316,7 +316,7 @@ class ClientAdapter { * @throws If the index does not exist */ global.kuzzle.onAsk(`core:storage:${this.scope}:index:delete`, (index) => - this.deleteIndex(index) + this.deleteIndex(index), ); /** @@ -325,7 +325,7 @@ class ClientAdapter { * @return {Promise.} */ global.kuzzle.onAsk(`core:storage:${this.scope}:index:exist`, (index) => - this.cache.hasIndex(index) + this.cache.hasIndex(index), ); /** @@ -333,7 +333,7 @@ class ClientAdapter { * @returns {string[]} */ global.kuzzle.onAsk(`core:storage:${this.scope}:index:list`, () => - this.cache.listIndexes() + this.cache.listIndexes(), ); /** @@ -343,7 +343,7 @@ class ClientAdapter { * @throws If at least one index does not exist */ global.kuzzle.onAsk(`core:storage:${this.scope}:index:mDelete`, (indexes) => - this.deleteIndexes(indexes) + this.deleteIndexes(indexes), ); /** @@ -351,7 +351,7 @@ class ClientAdapter { * @returns {Promise.} */ global.kuzzle.onAsk(`core:storage:${this.scope}:index:stats`, () => - this.client.stats() + this.client.stats(), ); } @@ -370,7 +370,7 @@ class ClientAdapter { (index, collection, bulk, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.import(index, collection, bulk, opts); - } + }, ); /** @@ -386,7 +386,7 @@ class ClientAdapter { (index, collection, query) => { this.cache.assertCollectionExists(index, collection); return this.client.count(index, collection, query); - } + }, ); /** @@ -403,7 +403,7 @@ class ClientAdapter { (index, collection, content, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.create(index, collection, content, opts); - } + }, ); /** @@ -425,9 +425,9 @@ class ClientAdapter { collection, id, content, - opts + opts, ); - } + }, ); /** @@ -444,7 +444,7 @@ class ClientAdapter { (index, collection, id, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.delete(index, collection, id, opts); - } + }, ); /** @@ -461,7 +461,7 @@ class ClientAdapter { (index, collection, query, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.deleteByQuery(index, collection, query, opts); - } + }, ); /** @@ -479,7 +479,7 @@ class ClientAdapter { (index, collection, id, fields, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.deleteFields(index, collection, id, fields, opts); - } + }, ); /** @@ -495,7 +495,7 @@ class ClientAdapter { (index, collection, id) => { this.cache.assertCollectionExists(index, collection); return this.client.exists(index, collection, id); - } + }, ); /** @@ -511,7 +511,7 @@ class ClientAdapter { (index, collection, ids) => { this.cache.assertCollectionExists(index, collection); return this.client.mExists(index, collection, ids); - } + }, ); /** @@ -527,7 +527,7 @@ class ClientAdapter { (index, collection, id) => { this.cache.assertCollectionExists(index, collection); return this.client.get(index, collection, id); - } + }, ); /** @@ -537,7 +537,7 @@ class ClientAdapter { */ global.kuzzle.onAsk( `core:storage:${this.scope}:document:import`, - (fixtures, options) => this.loadFixtures(fixtures, options) + (fixtures, options) => this.loadFixtures(fixtures, options), ); /** @@ -554,7 +554,7 @@ class ClientAdapter { (index, collection, documents, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.mCreate(index, collection, documents, opts); - } + }, ); /** @@ -571,7 +571,7 @@ class ClientAdapter { (index, collection, documents, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.mCreateOrReplace(index, collection, documents, opts); - } + }, ); /** @@ -588,7 +588,7 @@ class ClientAdapter { (index, collection, ids, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.mDelete(index, collection, ids, opts); - } + }, ); /** @@ -605,7 +605,7 @@ class ClientAdapter { (index, collection, documents, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.mReplace(index, collection, documents, opts); - } + }, ); /** @@ -622,7 +622,7 @@ class ClientAdapter { (index, collection, documents, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.mUpdate(index, collection, documents, opts); - } + }, ); /** @@ -640,7 +640,7 @@ class ClientAdapter { (index, collection, documents, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.mUpsert(index, collection, documents, opts); - } + }, ); /** @@ -658,7 +658,7 @@ class ClientAdapter { (index, collection, query, callback, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.mExecute(index, collection, query, callback, opts); - } + }, ); /** @@ -674,7 +674,7 @@ class ClientAdapter { (index, collection, ids) => { this.cache.assertCollectionExists(index, collection); return this.client.mGet(index, collection, ids); - } + }, ); /** @@ -692,7 +692,7 @@ class ClientAdapter { (index, collection, id, content, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.replace(index, collection, id, content, opts); - } + }, ); /** @@ -704,7 +704,7 @@ class ClientAdapter { */ global.kuzzle.onAsk( `core:storage:${this.scope}:document:scroll`, - (scrollId, opts) => this.client.scroll(scrollId, opts) + (scrollId, opts) => this.client.scroll(scrollId, opts), ); /** @@ -721,7 +721,7 @@ class ClientAdapter { (index, collection, searchBody, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.search({ collection, index, searchBody }, opts); - } + }, ); /** @@ -742,7 +742,7 @@ class ClientAdapter { } return this.client.search({ searchBody, targets }, opts); - } + }, ); /** @@ -760,7 +760,7 @@ class ClientAdapter { (index, collection, id, content, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.update(index, collection, id, content, opts); - } + }, ); /** @@ -783,9 +783,9 @@ class ClientAdapter { collection, query, changes, - opts + opts, ); - } + }, ); /** @@ -808,9 +808,9 @@ class ClientAdapter { collection, query, changes, - opts + opts, ); - } + }, ); /** @@ -829,7 +829,7 @@ class ClientAdapter { (index, collection, id, content, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.upsert(index, collection, id, content, opts); - } + }, ); } @@ -848,7 +848,7 @@ class ClientAdapter { (index, collection, opts) => { this.cache.assertCollectionExists(index, collection); return this.client.getMapping(index, collection, opts); - } + }, ); /** @@ -861,7 +861,7 @@ class ClientAdapter { */ global.kuzzle.onAsk( `core:storage:${this.scope}:mappings:import`, - (fixtures, options) => this.loadMappings(fixtures, options) + (fixtures, options) => this.loadMappings(fixtures, options), ); /** @@ -877,7 +877,7 @@ class ClientAdapter { (index, collection, mappings) => { this.cache.assertCollectionExists(index, collection); return this.client.updateMapping(index, collection, mappings); - } + }, ); } @@ -891,7 +891,7 @@ class ClientAdapter { * @param {string} index */ global.kuzzle.onAsk(`core:storage:${this.scope}:cache:addIndex`, (index) => - this.cache.addIndex(index) + this.cache.addIndex(index), ); /** @@ -901,7 +901,7 @@ class ClientAdapter { */ global.kuzzle.onAsk( `core:storage:${this.scope}:cache:addCollection`, - (index, collection) => this.cache.addCollection(index, collection) + (index, collection) => this.cache.addCollection(index, collection), ); /** @@ -914,7 +914,7 @@ class ClientAdapter { for (const index of indexes) { this.cache.removeIndex(index); } - } + }, ); /** @@ -924,7 +924,7 @@ class ClientAdapter { */ global.kuzzle.onAsk( `core:storage:${this.scope}:cache:removeCollection`, - (index, collection) => this.cache.removeCollection(index, collection) + (index, collection) => this.cache.removeCollection(index, collection), ); } @@ -946,7 +946,7 @@ class ClientAdapter { "assert", "invalid_argument", fixtures[index], - "object" + "object", ); } @@ -957,7 +957,7 @@ class ClientAdapter { index, collection, payload, - { refresh } + { refresh }, ); if (errors.length > 0) { @@ -983,7 +983,7 @@ class ClientAdapter { propagate: true, rawMappings: false, refresh: false, - } + }, ) { if (!isPlainObject(fixtures)) { throw kerror.get("api", "assert", "invalid_argument", fixtures, "object"); @@ -1001,7 +1001,7 @@ class ClientAdapter { "assert", "invalid_argument", fixtures[index], - "object" + "object", ); } @@ -1026,7 +1026,7 @@ class ClientAdapter { { indexCacheOnly: options.indexCacheOnly, propagate: options.propagate, - } + }, ); if (options.refresh && !options.indexCacheOnly) { diff --git a/lib/core/validation/baseType.js b/lib/core/validation/baseType.js index 17c14b79f4..2e8dc0e532 100644 --- a/lib/core/validation/baseType.js +++ b/lib/core/validation/baseType.js @@ -63,7 +63,7 @@ class BaseType { } return !Object.keys(object).some( - (propertyName) => allowedProperties.indexOf(propertyName) === -1 + (propertyName) => allowedProperties.indexOf(propertyName) === -1, ); } diff --git a/lib/core/validation/types/date.js b/lib/core/validation/types/date.js index 68cf501d39..3b3bb479c0 100644 --- a/lib/core/validation/types/date.js +++ b/lib/core/validation/types/date.js @@ -184,7 +184,7 @@ class DateType extends BaseType { if (momentDate.isBefore(min)) { errorMessages.push( - "The provided date is before the defined minimum." + "The provided date is before the defined minimum.", ); return false; } diff --git a/lib/core/validation/types/enum.js b/lib/core/validation/types/enum.js index 1af4c0c05a..5163e77e2e 100644 --- a/lib/core/validation/types/enum.js +++ b/lib/core/validation/types/enum.js @@ -50,8 +50,8 @@ class EnumType extends BaseType { if (!typeOptions.values.includes(fieldValue)) { errorMessages.push( `The field only accepts following values: "${typeOptions.values.join( - ", " - )}".` + ", ", + )}".`, ); return false; } @@ -75,12 +75,12 @@ class EnumType extends BaseType { "assert", "invalid_type", "values", - "string[]" + "string[]", ); } const nonString = typeOptions.values.filter( - (value) => typeof value !== "string" + (value) => typeof value !== "string", ); if (nonString.length > 0) { @@ -89,7 +89,7 @@ class EnumType extends BaseType { "assert", "invalid_type", "values", - "string[]" + "string[]", ); } diff --git a/lib/core/validation/types/geoShape.js b/lib/core/validation/types/geoShape.js index 7b3b001d2d..766eab8718 100644 --- a/lib/core/validation/types/geoShape.js +++ b/lib/core/validation/types/geoShape.js @@ -75,7 +75,7 @@ class GeoShapeType extends BaseType { return this.recursiveShapeValidation( typeOptions.shapeTypes, fieldValue, - errorMessages + errorMessages, ); } @@ -122,7 +122,7 @@ class GeoShapeType extends BaseType { !this.recursiveShapeValidation( allowedShapes, shape.geometries[i], - errorMessages + errorMessages, ) ) { result = false; @@ -159,11 +159,11 @@ class GeoShapeType extends BaseType { if (isMulti) { if ( shape.coordinates.some( - (coordinate) => !coordinateValidation(coordinate) + (coordinate) => !coordinateValidation(coordinate), ) ) { errorMessages.push( - `One of the shapes in the shape type "${shape.type}" has bad coordinates.` + `One of the shapes in the shape type "${shape.type}" has bad coordinates.`, ); result = false; } @@ -201,7 +201,7 @@ class GeoShapeType extends BaseType { if (shape.type === "geometrycollection" && shape.coordinates) { errorMessages.push( - 'The coordinates property must not be provided for the "geometrycollection" shape type.' + 'The coordinates property must not be provided for the "geometrycollection" shape type.', ); result = false; } @@ -211,21 +211,21 @@ class GeoShapeType extends BaseType { (!shape.coordinates || !Array.isArray(shape.coordinates)) ) { errorMessages.push( - `The coordinates property must be provided for the "${shape.type}" shape type.` + `The coordinates property must be provided for the "${shape.type}" shape type.`, ); result = false; } if (shape.type === "circle" && !shape.radius) { errorMessages.push( - 'The radius property is mandatory for the "circle" shape type.' + 'The radius property is mandatory for the "circle" shape type.', ); result = false; } if (shape.type !== "circle" && shape.radius) { errorMessages.push( - `The radius property must not be provided for the "${shape.type}" shape type.` + `The radius property must not be provided for the "${shape.type}" shape type.`, ); result = false; } @@ -236,14 +236,14 @@ class GeoShapeType extends BaseType { shape.orientation ) { errorMessages.push( - `The orientation property must not be provided for the "${shape.type}" shape type.` + `The orientation property must not be provided for the "${shape.type}" shape type.`, ); result = false; } if (shape.type !== "geometrycollection" && shape.geometries) { errorMessages.push( - `The geometries property must not be provided for the "${shape.type}" shape type.` + `The geometries property must not be provided for the "${shape.type}" shape type.`, ); result = false; } @@ -253,7 +253,7 @@ class GeoShapeType extends BaseType { (!shape.geometries || !Array.isArray(shape.geometries)) ) { errorMessages.push( - 'The geometries property must be provided for the "geometrycollection" shape type.' + 'The geometries property must be provided for the "geometrycollection" shape type.', ); result = false; } @@ -277,12 +277,12 @@ class GeoShapeType extends BaseType { "assert", "invalid_type", "shapeTypes", - "string[]" + "string[]", ); } const invalid = typeOptions.shapeTypes.filter( - (shape) => !allowedShapeTypes.includes(shape) + (shape) => !allowedShapeTypes.includes(shape), ); if (invalid.length > 0) { diff --git a/lib/core/validation/types/numeric.js b/lib/core/validation/types/numeric.js index de3736d31a..9cc046ffd3 100644 --- a/lib/core/validation/types/numeric.js +++ b/lib/core/validation/types/numeric.js @@ -53,7 +53,7 @@ class NumericType extends BaseType { fieldValue < typeOptions.range.min ) { errorMessages.push( - `Value ${fieldValue} is lesser than the allowed minimum (${typeOptions.range.min})` + `Value ${fieldValue} is lesser than the allowed minimum (${typeOptions.range.min})`, ); return false; } @@ -63,7 +63,7 @@ class NumericType extends BaseType { fieldValue > typeOptions.range.max ) { errorMessages.push( - `Value ${fieldValue} is greater than the allowed maximum (${typeOptions.range.max})` + `Value ${fieldValue} is greater than the allowed maximum (${typeOptions.range.max})`, ); return false; } diff --git a/lib/core/validation/types/string.js b/lib/core/validation/types/string.js index dd5b9b130a..d27b11cb87 100644 --- a/lib/core/validation/types/string.js +++ b/lib/core/validation/types/string.js @@ -56,7 +56,7 @@ class StringType extends BaseType { fieldValue.length < typeOptions.length.min ) { errorMessages.push( - `Invalid string length. Expected min: ${typeOptions.length.min}. Received: ${fieldValue.length} ("${fieldValue}")` + `Invalid string length. Expected min: ${typeOptions.length.min}. Received: ${fieldValue.length} ("${fieldValue}")`, ); return false; } @@ -66,7 +66,7 @@ class StringType extends BaseType { fieldValue.length > typeOptions.length.max ) { errorMessages.push( - `Invalid string length. Expected max: ${typeOptions.length.max}. Received: ${fieldValue.length} ("${fieldValue}")` + `Invalid string length. Expected max: ${typeOptions.length.max}. Received: ${fieldValue.length} ("${fieldValue}")`, ); return false; } diff --git a/lib/core/validation/validation.js b/lib/core/validation/validation.js index 1687264dea..91c4033375 100644 --- a/lib/core/validation/validation.js +++ b/lib/core/validation/validation.js @@ -104,7 +104,7 @@ class Validation { "core:storage:public:document:get", index, collection, - _id + _id, ); // Avoid side effects on the request during the update validation @@ -123,7 +123,7 @@ class Validation { collectionSpec.fields.children, collectionSpec.strict, errorMessages, - verbose + verbose, ); } catch (error) { // The strictness message can be received here only if it happens at @@ -137,7 +137,7 @@ class Validation { "document", errorMessages, `The document validation is strict. Cannot add unspecified sub-field "${error.details.field}"`, - verbose + verbose, ); } } @@ -148,7 +148,7 @@ class Validation { index, collection, body, - _id + _id, ); if (filters.length === 0 || filters[0] !== collectionSpec.validators) { @@ -157,7 +157,7 @@ class Validation { "document", errorMessages, "The document does not match validation filters.", - verbose + verbose, ); } } @@ -169,7 +169,7 @@ class Validation { request.input.body = this.recurseApplyDefault( isUpdate, request.input.body, - collectionSpec.fields.children + collectionSpec.fields.children, ); } @@ -199,14 +199,14 @@ class Validation { field[i] = this.recurseApplyDefault( isUpdate, field[i], - specSubset.children + specSubset.children, ); } } else { documentSubset[fieldName] = this.recurseApplyDefault( isUpdate, field, - specSubset.children + specSubset.children, ); } } else if ( @@ -232,7 +232,7 @@ class Validation { collectionSpecSubset, strictness, errorMessages, - verbose + verbose, ) { if (strictness) { for (const field of Object.keys(documentSubset)) { @@ -253,8 +253,8 @@ class Validation { collectionSpecSubset, strictness, errorMessages, - verbose - ) + verbose, + ), ); } @@ -267,9 +267,9 @@ class Validation { collectionSpecSubset, strictness, errorMessages, - verbose + verbose, ) && reductionResult, - true + true, ); } @@ -288,7 +288,7 @@ class Validation { collectionSpecSubset, strictness, errorMessages, - verbose + verbose, ) { /** @type StructuredFieldSpecification */ const field = collectionSpecSubset[fieldName]; @@ -303,7 +303,7 @@ class Validation { field.path, errorMessages, "The field is mandatory.", - verbose + verbose, ); return false; } @@ -318,7 +318,7 @@ class Validation { field.path, errorMessages, "The field must be multivalued, unary value provided.", - verbose + verbose, ); return false; } @@ -331,7 +331,7 @@ class Validation { field.path, errorMessages, `Not enough elements. Minimum count is set to ${field.multivalued.minCount}.`, - verbose + verbose, ); return false; } @@ -344,7 +344,7 @@ class Validation { field.path, errorMessages, `Too many elements. Maximum count is set to ${field.multivalued.maxCount}.`, - verbose + verbose, ); return false; } @@ -356,7 +356,7 @@ class Validation { field.path, errorMessages, "The field is not a multivalued field; Multiple values provided.", - verbose + verbose, ); return false; } @@ -367,7 +367,7 @@ class Validation { if (this.types[field.type].allowChildren) { nestedStrictness = this.types[field.type].getStrictness( field.typeOptions, - strictness + strictness, ); } @@ -383,11 +383,11 @@ class Validation { field.path, errorMessages, "An error has occurred during validation.", - verbose + verbose, ); } else { fieldErrors.forEach((message) => - manageErrorMessage(field.path, errorMessages, message, verbose) + manageErrorMessage(field.path, errorMessages, message, verbose), ); } return false; @@ -401,7 +401,7 @@ class Validation { field.children, nestedStrictness, errorMessages, - verbose + verbose, ) ) { result = false; @@ -412,14 +412,14 @@ class Validation { field.path, errorMessages, `The field is set to "strict"; cannot add unspecified sub-field "${error.details.field}".`, - verbose + verbose, ); } else if (verbose) { manageErrorMessage( field.path, errorMessages, error.message, - verbose + verbose, ); } else { throw error; @@ -445,12 +445,12 @@ class Validation { for (const indexName of Object.keys(this.rawConfiguration)) { for (const collectionName of Object.keys( - this.rawConfiguration[indexName] + this.rawConfiguration[indexName], )) { const promise = this.curateCollectionSpecification( indexName, collectionName, - this.rawConfiguration[indexName][collectionName] + this.rawConfiguration[indexName][collectionName], ) .then((curatedSpec) => { if (!has(specification, indexName)) { @@ -463,7 +463,7 @@ class Validation { }) .catch((error) => { global.kuzzle.log.error( - `Specification for the collection ${collectionName} triggered an error` + `Specification for the collection ${collectionName} triggered an error`, ); global.kuzzle.log.error(`Error: ${error.message}`); @@ -490,7 +490,7 @@ class Validation { indexName, collectionName, collectionSpec, - verboseErrors = false + verboseErrors = false, ) { // We make a deep clone to avoid side effects const specification = _.cloneDeep(collectionSpec); @@ -501,7 +501,7 @@ class Validation { collectionName, specification, true, - verboseErrors + verboseErrors, ) .then((result) => { if (verboseErrors && result.isValid === false) { @@ -529,7 +529,7 @@ class Validation { collection, spec, dryRun = false, - verbose = false + verbose = false, ) { let error = ""; const processed = { @@ -543,7 +543,7 @@ class Validation { error = assertionError.get( "unexpected_properties", `${index}.${collection}`, - allowed.join(", ") + allowed.join(", "), ); if (verbose) { @@ -558,7 +558,7 @@ class Validation { spec, index, collection, - verbose + verbose, ); if (result.isValid === false) { @@ -569,7 +569,7 @@ class Validation { throw assertionError.get( "invalid_specifications", - result.errors.join("\n\t- ") + result.errors.join("\n\t- "), ); } processed.fields = result; @@ -581,7 +581,7 @@ class Validation { index, collection, spec.validators, - dryRun + dryRun, ); processed.validators = filterId; @@ -598,7 +598,7 @@ class Validation { collectionSpec, indexName, collectionName, - verboseErrors = false + verboseErrors = false, ) { const fields = {}; let errors = [], @@ -614,7 +614,7 @@ class Validation { indexName, collectionName, fieldName, - verboseErrors + verboseErrors, ); if (result.isValid === false) { @@ -666,7 +666,7 @@ class Validation { indexName, collectionName, fieldName, - verboseErrors = false + verboseErrors = false, ) { const errors = []; @@ -675,7 +675,7 @@ class Validation { indexName, collectionName, fieldName, - verboseErrors + verboseErrors, ); if (result.isValid === false) { @@ -700,10 +700,10 @@ class Validation { assertionError.get( "unexpected_properties", `${indexName}.${collectionName}.${fieldName}`, - allowed.join(", ") + allowed.join(", "), ), verboseErrors, - errors + errors, ); } @@ -721,7 +721,7 @@ class Validation { "plugin", "runtime", "unexpected_error", - e.message + e.message, ); } @@ -737,7 +737,7 @@ class Validation { indexName, collectionName, fieldName, - fieldSpec + fieldSpec, ); return { fieldSpec, isValid: true }; @@ -757,7 +757,7 @@ class Validation { indexName, collectionName, fieldName, - verboseErrors = false + verboseErrors = false, ) { const errors = []; @@ -775,10 +775,10 @@ class Validation { assertionError.get( "unexpected_properties", `${indexName}.${collectionName}.${fieldName}`, - props.join(", ") + props.join(", "), ), verboseErrors, - errors + errors, ); } @@ -786,10 +786,10 @@ class Validation { throwOrStoreError( assertionError.get( "missing_type", - `${indexName}.${collectionName}.${fieldName}` + `${indexName}.${collectionName}.${fieldName}`, ), verboseErrors, - errors + errors, ); } @@ -798,10 +798,10 @@ class Validation { assertionError.get( "unknown_type", `${indexName}.${collectionName}.${fieldName}`, - fieldSpec.type + fieldSpec.type, ), verboseErrors, - errors + errors, ); } @@ -812,10 +812,10 @@ class Validation { assertionError.get( "unexpected_properties", `${indexName}.${collectionName}.${fieldName}.multivalued`, - multivaluedProps.join(", ") + multivaluedProps.join(", "), ), verboseErrors, - errors + errors, ); } @@ -823,10 +823,10 @@ class Validation { throwOrStoreError( assertionError.get( "missing_value", - `${indexName}.${collectionName}.${fieldName}.multivalued` + `${indexName}.${collectionName}.${fieldName}.multivalued`, ), verboseErrors, - errors + errors, ); } @@ -835,10 +835,10 @@ class Validation { assertionError.get( "invalid_type", `${indexName}.${collectionName}.${fieldName}.multivalued.value`, - "boolean" + "boolean", ), verboseErrors, - errors + errors, ); } @@ -851,10 +851,10 @@ class Validation { assertionError.get( "not_multivalued", `${indexName}.${collectionName}.${fieldName}`, - unexpected + unexpected, ), verboseErrors, - errors + errors, ); } } @@ -869,10 +869,10 @@ class Validation { "invalid_range", `${indexName}.${collectionName}.${fieldName}`, "minCount", - "maxCount" + "maxCount", ), verboseErrors, - errors + errors, ); } } @@ -905,12 +905,12 @@ class Validation { "Registering filter validator %s/%s: %O", indexName, collectionName, - query + query, ); return this.koncorde.register( query, - toKoncordeIndex(indexName, collectionName) + toKoncordeIndex(indexName, collectionName), ); } @@ -935,7 +935,7 @@ class Validation { "types", "missing_function", validationType.typeName, - "validate" + "validate", ); } @@ -948,7 +948,7 @@ class Validation { "types", "missing_function", validationType.typeName, - "validateFieldSpecification" + "validateFieldSpecification", ); } @@ -962,7 +962,7 @@ class Validation { "types", "missing_function", validationType.typeName, - "getStrictness" + "getStrictness", ); } @@ -974,7 +974,7 @@ class Validation { "validation", "types", "already_exists", - validationType.typeName + validationType.typeName, ); } @@ -993,7 +993,7 @@ function checkAllowedProperties(object, allowedProperties) { } return !Object.keys(object).some( - (propertyName) => !allowedProperties.includes(propertyName) + (propertyName) => !allowedProperties.includes(propertyName), ); } @@ -1116,7 +1116,7 @@ function manageErrorMessage(errorContext, errorHolder, message, structured) { "check", "failed_field", errorContext.join("."), - message + message, ); } } @@ -1141,7 +1141,7 @@ function getValidationConfiguration() { throw assertionError.get( "incorrect_validation_format", collectionName, - "index" + "index", ); } @@ -1149,7 +1149,7 @@ function getValidationConfiguration() { throw assertionError.get( "incorrect_validation_format", collectionName, - "collection" + "collection", ); } @@ -1157,7 +1157,7 @@ function getValidationConfiguration() { throw assertionError.get( "incorrect_validation_format", collectionName, - "validation" + "validation", ); } diff --git a/lib/kerror/codes/index.js b/lib/kerror/codes/index.js index 5806d9ca68..f8d9f24fcf 100644 --- a/lib/kerror/codes/index.js +++ b/lib/kerror/codes/index.js @@ -49,57 +49,57 @@ function checkErrors(subdomain, domain, options) { for (const [name, error] of Object.entries(subdomain.errors)) { assert( has(error, "code"), - `Error configuration file : Missing required 'code' field (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).` + `Error configuration file : Missing required 'code' field (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).`, ); assert( Number.isInteger(error.code), - `Error configuration file : Field 'code' must be an integer (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).` + `Error configuration file : Field 'code' must be an integer (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).`, ); assert( error.code > 0x0000 && error.code <= 0xffff, - `Error configuration file : Field 'code' must be between 1 and 65535 (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).` + `Error configuration file : Field 'code' must be between 1 and 65535 (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).`, ); assert( !codes.has(error.code), - `Error configuration file : code ${error.code} for error '${name}' is not unique (domain: ${domain.code}, subdomain: ${subdomain.code}).` + `Error configuration file : code ${error.code} for error '${name}' is not unique (domain: ${domain.code}, subdomain: ${subdomain.code}).`, ); codes.add(error.code); assert( has(error, "message"), - `Error configuration file : Missing required 'message' field (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).` + `Error configuration file : Missing required 'message' field (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).`, ); assert( typeof error.message === "string" && error.message.length > 0, - `Error configuration file : Field 'message' must be a non-empty string (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).` + `Error configuration file : Field 'message' must be a non-empty string (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).`, ); assert( has(error, "class"), - `Error configuration file : Missing required 'class' field (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).` + `Error configuration file : Missing required 'class' field (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).`, ); assert( typeof error.class === "string", - `Error configuration file : Field 'class' must be a string (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).` + `Error configuration file : Field 'class' must be a string (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).`, ); assert( has(errors, error.class), - `Error configuration file : Field 'class' must target a known KuzzleError object (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}), '${name.class}' does not exist.` + `Error configuration file : Field 'class' must target a known KuzzleError object (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}), '${name.class}' does not exist.`, ); // plugin errors aren't required to have descriptions if (!options.plugin) { assert( typeof error.description === "string" && error.description.length > 0, - `Error configuration file : Field 'description' must be a non-empty string (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).` + `Error configuration file : Field 'description' must be a non-empty string (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).`, ); } if (error.deprecated !== undefined && error.deprecated !== null) { assert( typeof error.deprecated === "string" && error.deprecated.length > 0, - `Error configuration file : Field 'deprecated' must be a non-empty string (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).` + `Error configuration file : Field 'deprecated' must be a non-empty string (domain: ${domain.code}, subdomain: ${subdomain.code}, error: ${name}).`, ); } } @@ -115,7 +115,7 @@ function checkSubdomains(domain, options) { if (!options.plugin) { assert( has(subdomain, "code"), - `Error configuration file : Missing required 'code' field (domain: ${domain.code}, subdomain: ${subdomainName}).` + `Error configuration file : Missing required 'code' field (domain: ${domain.code}, subdomain: ${subdomainName}).`, ); } else if (!has(subdomain, "code")) { subdomain.code = 0; @@ -123,15 +123,15 @@ function checkSubdomains(domain, options) { assert( Number.isInteger(subdomain.code), - `Error configuration file : Field 'code' must be an integer (domain: ${domain.code}, subdomain: ${subdomainName}).` + `Error configuration file : Field 'code' must be an integer (domain: ${domain.code}, subdomain: ${subdomainName}).`, ); assert( subdomain.code >= 0x00 && subdomain.code <= 0xff, - `Error configuration file : Field 'code' must be between 0 and 255 (domain: ${domain.code}, subdomain: ${subdomainName}).` + `Error configuration file : Field 'code' must be between 0 and 255 (domain: ${domain.code}, subdomain: ${subdomainName}).`, ); assert( !subdomainCodes.has(subdomain.code), - `Error configuration file : code ${subdomain.code} for subdomain '${subdomainName}' is not unique (domain: ${domain.code}).` + `Error configuration file : code ${subdomain.code} for subdomain '${subdomainName}' is not unique (domain: ${domain.code}).`, ); // We don't allow duplicates, except for defaulted plugin subdomain codes @@ -141,11 +141,11 @@ function checkSubdomains(domain, options) { assert( has(subdomain, "errors"), - `Error configuration file : Missing required 'errors' field (domain: ${domain.code}, subdomain: ${subdomainName}).` + `Error configuration file : Missing required 'errors' field (domain: ${domain.code}, subdomain: ${subdomainName}).`, ); assert( isPlainObject(subdomain.errors), - `Error configuration file : Field 'errors' must be an object (domain: ${domain.code}, subdomain: ${subdomainName}).` + `Error configuration file : Field 'errors' must be an object (domain: ${domain.code}, subdomain: ${subdomainName}).`, ); checkErrors(subdomain, domain, options); @@ -160,30 +160,30 @@ function checkDomains(errorCodesFiles, options = { plugin: false }) { assert( has(domain, "code"), - `Error configuration file : Missing required 'code' field. (domain: '${domainName}').` + `Error configuration file : Missing required 'code' field. (domain: '${domainName}').`, ); assert( Number.isInteger(domain.code), - `Error configuration file : Field 'code' must be an integer. (domain: '${domainName}').` + `Error configuration file : Field 'code' must be an integer. (domain: '${domainName}').`, ); assert( domain.code >= 0x00 && domain.code <= 0xff, - `Error configuration file : Field 'code' must be between 0 and 255. (domain: '${domainName}').` + `Error configuration file : Field 'code' must be between 0 and 255. (domain: '${domainName}').`, ); assert( !domainCodes.has(domain.code), - `Error configuration file : code ${domain.code} for domain ${domainName} is not unique.` + `Error configuration file : code ${domain.code} for domain ${domainName} is not unique.`, ); domainCodes.add(domain.code); assert( has(domain, "subDomains"), - `Error configuration file : Missing required 'subDomains' field. (domain: '${domainName}').` + `Error configuration file : Missing required 'subDomains' field. (domain: '${domainName}').`, ); assert( isPlainObject(domain.subDomains), - `Error configuration file : Field 'subDomains' must be an object. (domain: '${domainName}').` + `Error configuration file : Field 'subDomains' must be an object. (domain: '${domainName}').`, ); checkSubdomains(domain, options); diff --git a/lib/kerror/errors/multipleErrorsError.ts b/lib/kerror/errors/multipleErrorsError.ts index b48a79db2b..13f1c9dda0 100644 --- a/lib/kerror/errors/multipleErrorsError.ts +++ b/lib/kerror/errors/multipleErrorsError.ts @@ -29,7 +29,7 @@ export class MultipleErrorsError extends KuzzleError { message: string, errors: KuzzleError[] = [], id?: string, - code?: number + code?: number, ) { super(message, 400, id, code); diff --git a/lib/kerror/index.ts b/lib/kerror/index.ts index 47d0ad354c..cf6f7fc545 100644 --- a/lib/kerror/index.ts +++ b/lib/kerror/index.ts @@ -70,7 +70,7 @@ export function rawGet( const kuzzleError = _.get( domains, - `${domain}.subDomains.${subdomain}.errors.${error}` + `${domain}.subDomains.${subdomain}.errors.${error}`, ) as any as ErrorDefinition; if (!kuzzleError) { @@ -78,7 +78,7 @@ export function rawGet( "core", "fatal", "unexpected_error", - `${domain}.${subdomain}.${error}` + `${domain}.${subdomain}.${error}`, ); } @@ -173,7 +173,7 @@ export function rawReject( ...placeholders ): Promise { return Promise.reject( - rawGet(domains, domain, subdomain, error, ...placeholders) + rawGet(domains, domain, subdomain, error, ...placeholders), ); } @@ -201,7 +201,7 @@ export function rawGetFrom( domain, subdomain, error, - ...placeholders + ...placeholders, ); // If a stacktrace is present, we need to modify the first line because it @@ -224,7 +224,7 @@ export function rawGetFrom( export function rawWrap( domains: ErrorDomains, domain: string, - subdomain: string + subdomain: string, ) { return { get: (error, ...placeholders) => @@ -294,7 +294,7 @@ export function getFrom( domain, subdomain, error, - ...placeholders + ...placeholders, ); } diff --git a/lib/kuzzle/dumpGenerator.js b/lib/kuzzle/dumpGenerator.js index 00e3c94190..4b6bef0967 100644 --- a/lib/kuzzle/dumpGenerator.js +++ b/lib/kuzzle/dumpGenerator.js @@ -56,7 +56,7 @@ class DumpGenerator { moment() .format(global.kuzzle.config.dump.dateFormat) .concat(`-${suffix}`) - .substring(0, 200) + .substring(0, 200), ); global.kuzzle.log.info("=".repeat(79)); @@ -83,8 +83,8 @@ class DumpGenerator { version: require("../../package.json").version, }, null, - " " - ).concat("\n") + " ", + ).concat("\n"), ); // dump plugins configuration @@ -94,8 +94,8 @@ class DumpGenerator { JSON.stringify( global.kuzzle.pluginsManager.getPluginsDescription(), null, - " " - ).concat("\n") + " ", + ).concat("\n"), ); // dump Node.js configuration @@ -112,8 +112,8 @@ class DumpGenerator { versions: process.versions, }, null, - " " - ).concat("\n") + " ", + ).concat("\n"), ); // dump os configuration @@ -133,8 +133,8 @@ class DumpGenerator { uptime: os.uptime(), }, null, - " " - ).concat("\n") + " ", + ).concat("\n"), ); // core-dump @@ -159,11 +159,11 @@ class DumpGenerator { fs.unlinkSync(corefiles[0]); } catch (e) { global.kuzzle.log.warn( - `> unable to clean up core file ${corefiles[0]}` + `> unable to clean up core file ${corefiles[0]}`, ); } resolve(); - }) + }), ); } else { global.kuzzle.log.warn("> could not generate dump"); @@ -179,17 +179,17 @@ class DumpGenerator { // dumping Kuzzle's stats global.kuzzle.log.info("> dumping kuzzle's stats"); const statistics = await global.kuzzle.statistics.getAllStats( - new Request({ action: "getAllStats", controller: "statistics" }) + new Request({ action: "getAllStats", controller: "statistics" }), ); fs.writeFileSync( path.join(dumpPath, "statistics.json"), - JSON.stringify(statistics.hits, null, " ").concat("\n") + JSON.stringify(statistics.hits, null, " ").concat("\n"), ); global.kuzzle.log.info("Done."); global.kuzzle.log.info( - "[ℹ] You can send the folder to the kuzzle core team at support@kuzzle.io" + "[ℹ] You can send the folder to the kuzzle core team at support@kuzzle.io", ); global.kuzzle.log.info("=".repeat(79)); @@ -204,7 +204,7 @@ class DumpGenerator { try { fs.accessSync( dumpPath, - fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK + fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK, ); } catch (e) { return; @@ -234,7 +234,7 @@ class DumpGenerator { for (let i = 0; i < dumps.length - config.history.coredump; i++) { const corefiles = this._listFilesMatching( path.normalize(dumps[i].path), - "core" + "core", ); if (corefiles[0]) { @@ -249,7 +249,7 @@ class DumpGenerator { .filter( (entry) => fs.lstatSync(`${directory}/${entry}`).isFile() && - entry.startsWith(start) + entry.startsWith(start), ) .map((file) => path.join(directory, file)); } diff --git a/lib/kuzzle/event/kuzzleEventEmitter.js b/lib/kuzzle/event/kuzzleEventEmitter.js index 4bac06ba46..1671abba8f 100644 --- a/lib/kuzzle/event/kuzzleEventEmitter.js +++ b/lib/kuzzle/event/kuzzleEventEmitter.js @@ -81,7 +81,7 @@ class KuzzleEventEmitter extends EventEmitter { onPipe(event, fn) { assert( typeof fn === "function", - `Cannot listen to pipe event ${event}: "${fn}" is not a function` + `Cannot listen to pipe event ${event}: "${fn}" is not a function`, ); if (!this.corePipes.has(event)) { @@ -101,11 +101,11 @@ class KuzzleEventEmitter extends EventEmitter { onAsk(event, fn) { assert( typeof fn === "function", - `Cannot listen to ask event "${event}": "${fn}" is not a function` + `Cannot listen to ask event "${event}": "${fn}" is not a function`, ); assert( !this.coreAnswerers.has(event), - `Cannot add a listener to the ask event "${event}": event has already an answerer` + `Cannot add a listener to the ask event "${event}": event has already an answerer`, ); this.coreAnswerers.set(event, fn); @@ -121,11 +121,11 @@ class KuzzleEventEmitter extends EventEmitter { onCall(event, fn) { assert( typeof fn === "function", - `Cannot register callback for event "${event}": "${fn}" is not a function` + `Cannot register callback for event "${event}": "${fn}" is not a function`, ); assert( !this.coreSyncedAnswerers.has(event), - `Cannot register callback for event "${event}": a callback has already been registered` + `Cannot register callback for event "${event}": a callback has already been registered`, ); this.coreSyncedAnswerers.set(event, fn); @@ -222,7 +222,7 @@ class KuzzleEventEmitter extends EventEmitter { "core", "fatal", "assertion_failed", - `the requested ask event '${event}' doesn't have an answerer` + `the requested ask event '${event}' doesn't have an answerer`, ); } @@ -232,7 +232,7 @@ class KuzzleEventEmitter extends EventEmitter { super.emit(ev, { args: payload, response, - }) + }), ); return response; @@ -251,7 +251,7 @@ class KuzzleEventEmitter extends EventEmitter { "core", "fatal", "assertion_failed", - `the requested callback event '${event}' doesn't have an answerer` + `the requested callback event '${event}' doesn't have an answerer`, ); } @@ -261,7 +261,7 @@ class KuzzleEventEmitter extends EventEmitter { super.emit(ev, { args: payload, response, - }) + }), ); return response; diff --git a/lib/kuzzle/event/pipeRunner.js b/lib/kuzzle/event/pipeRunner.js index 98f1f99d37..48af0a27b4 100644 --- a/lib/kuzzle/event/pipeRunner.js +++ b/lib/kuzzle/event/pipeRunner.js @@ -83,11 +83,11 @@ class PipeRunner { constructor(concurrent, bufferSize) { assert( typeof concurrent === "number" && concurrent > 0, - "Cannot instantiate pipes executor: invalid maxConcurrentPipes parameter value" + "Cannot instantiate pipes executor: invalid maxConcurrentPipes parameter value", ); assert( typeof bufferSize === "number" && bufferSize > 0, - "Cannot instantiate pipes executor: invalid pipesBufferSize parameter value" + "Cannot instantiate pipes executor: invalid pipesBufferSize parameter value", ); this.maxConcurrent = concurrent; diff --git a/lib/kuzzle/internalIndexHandler.js b/lib/kuzzle/internalIndexHandler.js index d09a4477a1..19b19602c2 100644 --- a/lib/kuzzle/internalIndexHandler.js +++ b/lib/kuzzle/internalIndexHandler.js @@ -81,7 +81,7 @@ class InternalIndexHandler extends Store { constructor() { super( global.kuzzle.config.services.storageEngine.internalIndex.name, - scopeEnum.PRIVATE + scopeEnum.PRIVATE, ); this.timeout = @@ -121,7 +121,7 @@ class InternalIndexHandler extends Store { { timestamp: Date.now() }, { id: this._BOOTSTRAP_DONE_ID, - } + }, ); } catch (error) { if (error instanceof Bluebird.TimeoutError) { @@ -129,7 +129,7 @@ class InternalIndexHandler extends Store { "services", "storage", "bootstrap_timeout", - "internalIndex" + "internalIndex", ); } @@ -158,7 +158,7 @@ class InternalIndexHandler extends Store { { version: dataModelVersion }, { id: this._DATAMODEL_VERSION_ID, - } + }, ); } @@ -172,7 +172,7 @@ class InternalIndexHandler extends Store { return this.createOrReplace("roles", roleId, content, { refresh: "wait_for", }); - } + }, ); await Bluebird.map( @@ -181,7 +181,7 @@ class InternalIndexHandler extends Store { return this.createOrReplace("profiles", profileId, content, { refresh: "wait_for", }); - } + }, ); } @@ -194,7 +194,7 @@ class InternalIndexHandler extends Store { const validationId = `${index}#${collectionName}`; promises.push( - this.createOrReplace("validations", validationId, validation) + this.createOrReplace("validations", validationId, validation), ); } } @@ -218,7 +218,7 @@ class InternalIndexHandler extends Store { { seed }, { id: this._JWT_SECRET_ID, - } + }, ); } } diff --git a/lib/kuzzle/kuzzle.ts b/lib/kuzzle/kuzzle.ts index 85230994f2..7f32b4b930 100644 --- a/lib/kuzzle/kuzzle.ts +++ b/lib/kuzzle/kuzzle.ts @@ -73,7 +73,7 @@ Reflect.defineProperty(global, "kuzzle", { get() { if (_kuzzle === null) { throw new Error( - "Kuzzle instance not found. Did you try to use a live-only feature before starting your application?" + "Kuzzle instance not found. Did you try to use a live-only feature before starting your application?", ); } @@ -82,7 +82,7 @@ Reflect.defineProperty(global, "kuzzle", { set(value) { if (_kuzzle !== null) { throw new Error( - "Cannot build a Kuzzle instance: another one already exists" + "Cannot build a Kuzzle instance: another one already exists", ); } @@ -176,7 +176,7 @@ class Kuzzle extends KuzzleEventEmitter { toImport: ImportConfig; toSupport: SupportConfig; }, - status: ImportStatus + status: ImportStatus, ) => Promise; }; @@ -191,7 +191,7 @@ class Kuzzle extends KuzzleEventEmitter { constructor(config: KuzzleConfiguration) { super( config.plugins.common.maxConcurrentPipes, - config.plugins.common.pipesBufferSize + config.plugins.common.pipesBufferSize, ); global.kuzzle = this; @@ -285,7 +285,7 @@ class Kuzzle extends KuzzleEventEmitter { this.log.info( `[✔] Successfully loaded ${ this.pluginsManager.loadedPlugins.length - } plugins: ${this.pluginsManager.loadedPlugins.join(", ")}` + } plugins: ${this.pluginsManager.loadedPlugins.join(", ")}`, ); const imports = _.merge({}, pluginImports, options.import); @@ -303,12 +303,12 @@ class Kuzzle extends KuzzleEventEmitter { await this.install(options.installations); this.log.info( - `[✔] Start "${this.pluginsManager.application.name}" application` + `[✔] Start "${this.pluginsManager.application.name}" application`, ); this.openApiManager = new OpenApiManager( application.openApi, this.config.http.routes, - this.pluginsManager.routes + this.pluginsManager.routes, ); // @deprecated @@ -321,7 +321,7 @@ class Kuzzle extends KuzzleEventEmitter { await this.pipe("kuzzle:state:ready"); this.log.info( - `[✔] Kuzzle ${this.version} is ready (node name: ${this.id})` + `[✔] Kuzzle ${this.version} is ready (node name: ${this.id})`, ); // @deprecated @@ -330,7 +330,7 @@ class Kuzzle extends KuzzleEventEmitter { this._state = kuzzleStateEnum.RUNNING; } catch (error) { this.log.error( - `[X] Cannot start Kuzzle ${this.version}: ${error.message}` + `[X] Cannot start Kuzzle ${this.version}: ${error.message}`, ); throw error; @@ -377,7 +377,7 @@ class Kuzzle extends KuzzleEventEmitter { while (this.funnel.remainingRequests !== 0) { this.log.info( - `[shutdown] Waiting: ${this.funnel.remainingRequests} remaining requests` + `[shutdown] Waiting: ${this.funnel.remainingRequests} remaining requests`, ); await Bluebird.delay(1000); } @@ -408,7 +408,7 @@ class Kuzzle extends KuzzleEventEmitter { "core:storage:private:document:exist", "kuzzle", "installations", - installation.id + installation.id, ); if (!isAlreadyInstalled) { @@ -420,7 +420,7 @@ class Kuzzle extends KuzzleEventEmitter { "runtime", "unexpected_installation_error", installation.id, - error + error, ); } @@ -433,11 +433,11 @@ class Kuzzle extends KuzzleEventEmitter { handler: installation.handler.toString(), installedAt: Date.now(), }, - { id: installation.id } + { id: installation.id }, ); this.log.info( - `[✔] Install code "${installation.id}" successfully executed` + `[✔] Install code "${installation.id}" successfully executed`, ); } } @@ -466,7 +466,7 @@ class Kuzzle extends KuzzleEventEmitter { toImport: ImportConfig; toSupport: SupportConfig; }, - status: ImportStatus + status: ImportStatus, ): Promise { if (!status.firstCall) { return; @@ -486,7 +486,7 @@ class Kuzzle extends KuzzleEventEmitter { toImport: ImportConfig; toSupport: SupportConfig; }, - status: ImportStatus + status: ImportStatus, ): Promise { const toImport = config.toImport; const toSupport = config.toSupport; @@ -497,7 +497,7 @@ class Kuzzle extends KuzzleEventEmitter { "runtime", "incompatible", "_support.mappings", - "import.mappings" + "import.mappings", ); } else if (!_.isEmpty(toSupport.mappings)) { await this.ask( @@ -512,7 +512,7 @@ class Kuzzle extends KuzzleEventEmitter { propagate: false, // Each node needs to do the import themselves rawMappings: true, refresh: true, - } + }, ); this.log.info("[✔] Mappings import successful"); } else if (!_.isEmpty(toImport.mappings)) { @@ -534,7 +534,7 @@ class Kuzzle extends KuzzleEventEmitter { toImport: ImportConfig; toSupport: SupportConfig; }, - status: ImportStatus + status: ImportStatus, ): Promise { if (!status.firstCall) { return; @@ -553,7 +553,7 @@ class Kuzzle extends KuzzleEventEmitter { toImport: ImportConfig; toSupport: SupportConfig; }, - status: ImportStatus + status: ImportStatus, ): Promise { if (!status.firstCall) { return; @@ -580,7 +580,7 @@ class Kuzzle extends KuzzleEventEmitter { "runtime", "incompatible", "_support.securities", - "import profiles roles or users" + "import profiles roles or users", ); } else if (isPermissionsToSupport) { await this.ask("core:security:load", toSupport.securities, { @@ -600,7 +600,7 @@ class Kuzzle extends KuzzleEventEmitter { onExistingUsers: toImport.onExistingUsers, onExistingUsersWarning: true, refresh: "wait_for", - } + }, ); this.log.info("[✔] Permissions import successful"); } @@ -616,7 +616,7 @@ class Kuzzle extends KuzzleEventEmitter { if ( await this.ask( "core:cache:internal:get", - `${BACKEND_IMPORT_KEY}:${importType}` + `${BACKEND_IMPORT_KEY}:${importType}`, ) ) { return; @@ -636,7 +636,7 @@ class Kuzzle extends KuzzleEventEmitter { */ async loadInitialState( toImport: ImportConfig = {}, - toSupport: SupportConfig = {} + toSupport: SupportConfig = {}, ): Promise { if ( _.isEmpty(toImport.mappings) && @@ -678,7 +678,7 @@ class Kuzzle extends KuzzleEventEmitter { const existingHash = await this.ask( "core:cache:internal:get", - `${BACKEND_IMPORT_KEY}:${type}` + `${BACKEND_IMPORT_KEY}:${type}`, ); const initialized = existingHash === importPayloadHash; @@ -690,7 +690,7 @@ class Kuzzle extends KuzzleEventEmitter { firstCall: !initialized && locked, initialized, locked, - } + }, ); if (!initialized && locked) { @@ -699,7 +699,7 @@ class Kuzzle extends KuzzleEventEmitter { await this.ask( "core:cache:internal:store", `${BACKEND_IMPORT_KEY}:${type}`, - importPayloadHash + importPayloadHash, ); } } @@ -732,7 +732,7 @@ class Kuzzle extends KuzzleEventEmitter { return murmur( Buffer.from(inString), "hex", - this.config.internal.hash.seed as number + this.config.internal.hash.seed as number, ); } @@ -757,7 +757,7 @@ class Kuzzle extends KuzzleEventEmitter { if (reason !== undefined) { if (reason instanceof Error) { this.log.error( - `ERROR: unhandledRejection: ${reason.message}. Reason: ${reason.stack}` + `ERROR: unhandledRejection: ${reason.message}. Reason: ${reason.stack}`, ); } else { this.log.error(`ERROR: unhandledRejection: ${reason}`); @@ -771,10 +771,10 @@ class Kuzzle extends KuzzleEventEmitter { // this is what Node.js will do automatically in future versions anyway. if (global.NODE_ENV === "development") { this.log.error( - "Kuzzle caught an unhandled rejected promise and will shutdown." + "Kuzzle caught an unhandled rejected promise and will shutdown.", ); this.log.error( - 'This behavior is only triggered if global.NODE_ENV is set to "development"' + 'This behavior is only triggered if global.NODE_ENV is set to "development"', ); throw reason; diff --git a/lib/kuzzle/log.js b/lib/kuzzle/log.js index 4d37970e4e..87e0c21d79 100644 --- a/lib/kuzzle/log.js +++ b/lib/kuzzle/log.js @@ -58,12 +58,12 @@ class Logger { global.kuzzle.emit( `log:${method}`, - `[${global.kuzzle.id}] ${this.failsafeModeString}[${request.id}] ${message}` + `[${global.kuzzle.id}] ${this.failsafeModeString}[${request.id}] ${message}`, ); } else { global.kuzzle.emit( `log:${method}`, - `[${global.kuzzle.id}] ${this.failsafeModeString}${message}` + `[${global.kuzzle.id}] ${this.failsafeModeString}${message}`, ); } }; diff --git a/lib/kuzzle/vault.js b/lib/kuzzle/vault.js index 0f880a9d86..c3ab762dd8 100644 --- a/lib/kuzzle/vault.js +++ b/lib/kuzzle/vault.js @@ -35,7 +35,7 @@ function load(vaultKey, secretsFile) { // Using KaaF kuzzle is an npm package and is located under node_modules folder // We need to get back to root folder of the project to get the secret file const defaultEncryptedSecretsFile = __dirname.endsWith( - "/node_modules/kuzzle/lib/kuzzle" + "/node_modules/kuzzle/lib/kuzzle", ) ? path.resolve(`${__dirname}/../../../../config/secrets.enc.json`) : path.resolve(`${__dirname}/../../config/secrets.enc.json`); @@ -59,7 +59,7 @@ function load(vaultKey, secretsFile) { if (!_.isEmpty(process.env.KUZZLE_SECRETS_FILE) || !_.isEmpty(secretsFile)) { assert( fileExists, - `A secret file has been provided but Kuzzle cannot find it at "${encryptedSecretsFile}".` + `A secret file has been provided but Kuzzle cannot find it at "${encryptedSecretsFile}".`, ); } @@ -67,14 +67,14 @@ function load(vaultKey, secretsFile) { // but no vault key has been provided assert( !(fileExists && _.isEmpty(key)), - "A secret file has been provided but Kuzzle cannot find the Vault key. Aborting." + "A secret file has been provided but Kuzzle cannot find the Vault key. Aborting.", ); // Abort if a vault key has been provided // but no secrets file can be loaded (default or custom) assert( !(!_.isEmpty(key) && !fileExists), - `A Vault key is present but Kuzzle cannot find the secret file at "${encryptedSecretsFile}". Aborting.` + `A Vault key is present but Kuzzle cannot find the secret file at "${encryptedSecretsFile}". Aborting.`, ); const vault = new Vault(key); diff --git a/lib/model/security/profile.ts b/lib/model/security/profile.ts index 6a2f253ad1..1b5d6e1804 100644 --- a/lib/model/security/profile.ts +++ b/lib/model/security/profile.ts @@ -72,7 +72,7 @@ export class Profile { async ({ restrictedTo, roleId }) => { const role = await global.kuzzle.ask("core:security:role:get", roleId); return { restrictedTo, role }; - } + }, ); } @@ -81,7 +81,7 @@ export class Profile { * @returns {Promise} */ async getAllowedPolicies( - request: KuzzleRequest + request: KuzzleRequest, ): Promise { if ( this.optimizedPolicies === undefined || @@ -113,8 +113,8 @@ export class Profile { policy.role.checkRestrictions( request.input.args.index, request.input.args.collection, - policy.restrictedTo - ) + policy.restrictedTo, + ), ); } @@ -137,7 +137,7 @@ export class Profile { throw assertionError.get( "invalid_type", `${this._id}.policies`, - "object[]" + "object[]", ); } @@ -150,7 +150,7 @@ export class Profile { if (!policy.roleId) { throw assertionError.get( "missing_argument", - `${this._id}.policies[${i}].roleId` + `${this._id}.policies[${i}].roleId`, ); } @@ -159,7 +159,7 @@ export class Profile { throw assertionError.get( "unexpected_argument", `${this._id}.policies[${i}].${member}`, - '"roleId", "restrictedTo"' + '"roleId", "restrictedTo"', ); } } @@ -169,7 +169,7 @@ export class Profile { throw assertionError.get( "invalid_type", `${this._id}.policies[${i}].restrictedTo`, - "object[]" + "object[]", ); } @@ -179,21 +179,21 @@ export class Profile { throw assertionError.get( "invalid_type", `${this._id}.policies[${i}].restrictedTo[${restriction}]`, - "object" + "object", ); } if (restriction.index === null || restriction.index === undefined) { throw assertionError.get( "missing_argument", - `${this._id}.policies[${i}].restrictedTo[${j}].index` + `${this._id}.policies[${i}].restrictedTo[${j}].index`, ); } if (strict) { const indexExists = await global.kuzzle.ask( "core:storage:public:index:exist", - restriction.index + restriction.index, ); if (!indexExists) { @@ -201,7 +201,7 @@ export class Profile { "services", "storage", "unknown_index", - restriction.index + restriction.index, ); } } @@ -214,7 +214,7 @@ export class Profile { throw assertionError.get( "invalid_type", `${this._id}.policies[${i}].restrictedTo[${j}].collections`, - "string[]" + "string[]", ); } @@ -224,7 +224,7 @@ export class Profile { const isValid = await global.kuzzle.ask( "core:storage:public:collection:exist", restriction.index, - collection + collection, ); if (!isValid) { @@ -238,7 +238,7 @@ export class Profile { "storage", "unknown_collection", restriction.index, - invalidCollections + invalidCollections, ); } } @@ -249,7 +249,7 @@ export class Profile { throw assertionError.get( "unexpected_argument", `${this._id}.policies[${i}].restrictedTo[${j}].${member}`, - '"index", "collections"' + '"index", "collections"', ); } } @@ -340,7 +340,7 @@ export class Profile { throw assertionError.get( "invalid_argument", "rateLimit", - "positive integer, or zero" + "positive integer, or zero", ); } } diff --git a/lib/model/security/role.ts b/lib/model/security/role.ts index ac7b264d21..c1cb85b21f 100644 --- a/lib/model/security/role.ts +++ b/lib/model/security/role.ts @@ -107,7 +107,7 @@ export class Role { throw assertionError.get( "invalid_type", `${this._id}.controllers`, - "object" + "object", ); } @@ -115,9 +115,9 @@ export class Role { throw assertionError.get("empty_argument", `${this._id}.controllers`); } - Object.entries(this.controllers).forEach((entry) => - this.validateControllerRights(...entry) - ); + for (const entry of Object.entries(this.controllers)) { + this.validateControllerRights(...entry); + } } /** @@ -129,7 +129,7 @@ export class Role { checkRestrictions( index: string, collection: string, - restrictedTo: OptimizedPolicyRestrictions + restrictedTo: OptimizedPolicyRestrictions, ): boolean { // If no restrictions, we allow the action: if (!restrictedTo || restrictedTo.size === 0) { @@ -200,7 +200,7 @@ export class Role { throw assertionError.get( "invalid_type", `${name}.actions.${actionName}`, - "boolean" + "boolean", ); } } diff --git a/lib/model/security/user.ts b/lib/model/security/user.ts index d7712097ce..67f5a9d846 100644 --- a/lib/model/security/user.ts +++ b/lib/model/security/user.ts @@ -59,7 +59,9 @@ export class User { const rights = {}; - results.forEach((right) => _.assignWith(rights, right, Rights.merge)); + for (const right of results) { + _.assignWith(rights, right, Rights.merge); + } return rights; } @@ -98,10 +100,10 @@ export class User { private async areTargetsAllowed( request: KuzzleRequest, profiles: Profile[], - targets: Target[] + targets: Target[], ) { const profilesPolicies = await Promise.all( - profiles.map((profile) => profile.getAllowedPolicies(request)) + profiles.map((profile) => profile.getAllowedPolicies(request)), ); // Every target must be allowed by at least one profile @@ -127,9 +129,9 @@ export class User { policy.role.checkRestrictions( target.index, collection, - policy.restrictedTo - ) - ) + policy.restrictedTo, + ), + ), ); if (!isTargetAllowed) { diff --git a/lib/model/storage/apiKey.js b/lib/model/storage/apiKey.js index 41fb56fae7..108d17e336 100644 --- a/lib/model/storage/apiKey.js +++ b/lib/model/storage/apiKey.js @@ -38,7 +38,7 @@ class ApiKey extends BaseModel { const token = await global.kuzzle.ask( "core:security:token:get", this.userId, - this.token + this.token, ); if (token) { @@ -93,7 +93,7 @@ class ApiKey extends BaseModel { user, expiresIn, description, - { creatorId = null, apiKeyId = null, refresh, bypassMaxTTL = false } = {} + { creatorId = null, apiKeyId = null, refresh, bypassMaxTTL = false } = {}, ) { const token = await global.kuzzle.ask("core:security:token:create", user, { bypassMaxTTL, @@ -111,7 +111,7 @@ class ApiKey extends BaseModel { ttl: token.ttl, userId: user._id, }, - apiKeyId || fingerprint + apiKeyId || fingerprint, ); await apiKey.save({ refresh, userId: creatorId }); diff --git a/lib/model/storage/baseModel.js b/lib/model/storage/baseModel.js index 324304cdc7..bb0ce0a49d 100644 --- a/lib/model/storage/baseModel.js +++ b/lib/model/storage/baseModel.js @@ -78,7 +78,7 @@ class BaseModel { const { _id, _source } = await global.kuzzle.internalIndex.create( this.constructor.collection, this._source, - { id: this._id, refresh, userId } + { id: this._id, refresh, userId }, ); this._id = _id; @@ -89,7 +89,7 @@ class BaseModel { this.constructor.collection, this._id, this._source, - { refresh, userId } + { refresh, userId }, ); } } @@ -110,7 +110,7 @@ class BaseModel { await global.kuzzle.internalIndex.delete( this.constructor.collection, this._id, - { refresh } + { refresh }, ); await this._afterDelete(); @@ -190,13 +190,13 @@ class BaseModel { static async deleteByQuery(query, { refresh } = {}) { const { documents } = await global.kuzzle.internalIndex.deleteByQuery( this.collection, - query + query, ); await Bluebird.map( documents, (document) => this._instantiateFromDb(document)._afterDelete(), - { concurrency: 10 } + { concurrency: 10 }, ); // limits the load on storage services if (refresh) { @@ -216,7 +216,7 @@ class BaseModel { const resp = await global.kuzzle.internalIndex.search( this.collection, searchBody, - options + options, ); return resp.hits.map((hit) => this._instantiateFromDb(hit)); @@ -237,7 +237,7 @@ class BaseModel { return global.kuzzle.internalIndex.mExecute( this.collection, query, - callback + callback, ); } diff --git a/lib/service/cache/redis.js b/lib/service/cache/redis.js index a04d796c5c..f648cba9b0 100644 --- a/lib/service/cache/redis.js +++ b/lib/service/cache/redis.js @@ -77,7 +77,7 @@ class Redis extends Service { this.client.on("error", (error) => { if (this.connected) { global.kuzzle.log.error( - `Redis service seem to be down, see original error for more info:\n${error.message}` + `Redis service seem to be down, see original error for more info:\n${error.message}`, ); } this.connected = false; @@ -93,7 +93,7 @@ class Redis extends Service { this.client.once("ready", async () => { await this.client.client( "SETNAME", - `${this.adapterName}/${global.kuzzle.id}` + `${this.adapterName}/${global.kuzzle.id}`, ); resolve(); }); @@ -128,7 +128,7 @@ class Redis extends Service { await this.client.ping(); } catch (error) { global.kuzzle.log.error( - `Failed to PING Redis to keep connection alive:\n${error.message}` + `Failed to PING Redis to keep connection alive:\n${error.message}`, ); } } diff --git a/lib/service/storage/elasticsearch.js b/lib/service/storage/elasticsearch.js index d3a8ca28c0..ef99a27c49 100644 --- a/lib/service/storage/elasticsearch.js +++ b/lib/service/storage/elasticsearch.js @@ -168,7 +168,7 @@ class ElasticSearch extends Service { "Your dynamic mapping policy is set to 'true' for new fields.", "Elasticsearch will try to automatically infer mapping for new fields, and those cannot be changed afterward.", 'See the "services.storageEngine.commonMapping.dynamic" option in the kuzzlerc configuration file to change this value.', - ].join("\n") + ].join("\n"), ); } @@ -325,7 +325,7 @@ class ElasticSearch extends Service { const stringifiedScrollInfo = await global.kuzzle.ask( "core:cache:internal:get", - cacheKey + cacheKey, ); if (!stringifiedScrollInfo) { @@ -350,7 +350,7 @@ class ElasticSearch extends Service { JSON.stringify(scrollInfo), { ttl: ms(_scrollTTL) || this.scrollTTL, - } + }, ); } @@ -374,7 +374,7 @@ class ElasticSearch extends Service { */ async search( { index, collection, searchBody, targets } = {}, - { from, size, scroll } = {} + { from, size, scroll } = {}, ) { let esIndexes; @@ -429,7 +429,7 @@ class ElasticSearch extends Service { index, targets, }), - { ttl } + { ttl }, ); body.remaining = body.hits.total.value - body.hits.hits.length; @@ -529,7 +529,7 @@ class ElasticSearch extends Service { for (const [name, innerHit] of Object.entries(innerHits)) { formattedInnerHits[name] = await Bluebird.map( innerHit.hits.hits, - formatHit + formatHit, ); } return formattedInnerHits; @@ -682,7 +682,7 @@ class ElasticSearch extends Service { index, collection, content, - { id, refresh, userId = null, injectKuzzleMeta = true } = {} + { id, refresh, userId = null, injectKuzzleMeta = true } = {}, ) { assertIsObject(content); @@ -738,7 +738,7 @@ class ElasticSearch extends Service { collection, id, content, - { refresh, userId = null, injectKuzzleMeta = true } = {} + { refresh, userId = null, injectKuzzleMeta = true } = {}, ) { const esRequest = { body: content, @@ -792,7 +792,7 @@ class ElasticSearch extends Service { collection, id, content, - { refresh, userId = null, retryOnConflict, injectKuzzleMeta = true } = {} + { refresh, userId = null, retryOnConflict, injectKuzzleMeta = true } = {}, ) { const esRequest = { _source: true, @@ -852,7 +852,7 @@ class ElasticSearch extends Service { userId = null, retryOnConflict, injectKuzzleMeta = true, - } = {} + } = {}, ) { const esRequest = { _source: true, @@ -917,7 +917,7 @@ class ElasticSearch extends Service { collection, id, content, - { refresh, userId = null, injectKuzzleMeta = true } = {} + { refresh, userId = null, injectKuzzleMeta = true } = {}, ) { const alias = this._getAlias(index, collection); const esRequest = { @@ -1010,7 +1010,7 @@ class ElasticSearch extends Service { index, collection, query, - { refresh, size = 1000, fetch = true } = {} + { refresh, size = 1000, fetch = true } = {}, ) { const esRequest = { body: this._sanitizeSearchBody({ query }), @@ -1066,7 +1066,7 @@ class ElasticSearch extends Service { collection, id, fields, - { refresh, userId = null } = {} + { refresh, userId = null } = {}, ) { const alias = this._getAlias(index, collection); const esRequest = { @@ -1128,7 +1128,7 @@ class ElasticSearch extends Service { collection, query, changes, - { refresh, size = 1000, userId = null } = {} + { refresh, size = 1000, userId = null } = {}, ) { try { const esRequest = { @@ -1153,7 +1153,7 @@ class ElasticSearch extends Service { index, collection, documents, - { refresh, userId } + { refresh, userId }, ); return { @@ -1181,7 +1181,7 @@ class ElasticSearch extends Service { collection, query, changes, - { refresh = "false" } = {} + { refresh = "false" } = {}, ) { const script = { params: {}, @@ -1244,7 +1244,7 @@ class ElasticSearch extends Service { collection, query, callback, - { size = 10, scrollTTl = "5s" } = {} + { size = 10, scrollTTl = "5s" } = {}, ) { const esRequest = { body: this._sanitizeSearchBody({ query }), @@ -1270,7 +1270,7 @@ class ElasticSearch extends Service { esRequest, async function getMoreUntilDone( error, - { body: { hits, _scroll_id } } + { body: { hits, _scroll_id } }, ) { if (error) { reject(error); @@ -1290,12 +1290,12 @@ class ElasticSearch extends Service { scroll: esRequest.scroll, scrollId: _scroll_id, }, - getMoreUntilDone + getMoreUntilDone, ); } else { resolve(results); } - } + }, ); }); } finally { @@ -1360,7 +1360,7 @@ class ElasticSearch extends Service { async createCollection( index, collection, - { mappings = {}, settings = {} } = {} + { mappings = {}, settings = {} } = {}, ) { this._assertValidIndexAndCollection(index, collection); @@ -1407,7 +1407,7 @@ class ElasticSearch extends Service { dynamic: mappings.dynamic || this._config.commonMapping.dynamic, properties: _.merge( mappings.properties, - this._config.commonMapping.properties + this._config.commonMapping.properties, ), }; @@ -1508,7 +1508,7 @@ class ElasticSearch extends Service { async updateCollection( index, collection, - { mappings = {}, settings = {} } = {} + { mappings = {}, settings = {} } = {}, ) { const esRequest = { index: await this._getIndice(index, collection), @@ -1635,7 +1635,7 @@ class ElasticSearch extends Service { const fullProperties = _.merge( collectionMappings.properties, - mappings.properties + mappings.properties, ); return { @@ -1731,7 +1731,7 @@ class ElasticSearch extends Service { index, collection, documents, - { refresh, timeout, userId = null } = {} + { refresh, timeout, userId = null } = {}, ) { const alias = this._getAlias(index, collection); const actionNames = ["index", "create", "update", "delete"]; @@ -2018,7 +2018,7 @@ class ElasticSearch extends Service { return request; }, - { index: [] } + { index: [] }, ); if (esRequest.index.length === 0) { @@ -2208,7 +2208,7 @@ class ElasticSearch extends Service { index, collection, documents, - { refresh, timeout, userId = null } = {} + { refresh, timeout, userId = null } = {}, ) { const alias = this._getAlias(index, collection), kuzzleMeta = { @@ -2306,7 +2306,7 @@ class ElasticSearch extends Service { injectKuzzleMeta = true, limits = true, source = true, - } = {} + } = {}, ) { let kuzzleMeta = {}; @@ -2330,7 +2330,7 @@ class ElasticSearch extends Service { }; const { rejected, extractedDocuments } = this._extractMDocuments( documents, - kuzzleMeta + kuzzleMeta, ); esRequest.body = []; @@ -2373,7 +2373,7 @@ class ElasticSearch extends Service { index, collection, documents, - { refresh, retryOnConflict = 0, timeout, userId = null } = {} + { refresh, retryOnConflict = 0, timeout, userId = null } = {}, ) { const alias = this._getAlias(index, collection), toImport = [], @@ -2391,7 +2391,7 @@ class ElasticSearch extends Service { }, { rejected, extractedDocuments } = this._extractMDocuments( documents, - kuzzleMeta + kuzzleMeta, ); /** @@ -2464,7 +2464,7 @@ class ElasticSearch extends Service { index, collection, documents, - { refresh, retryOnConflict = 0, timeout, userId = null } = {} + { refresh, retryOnConflict = 0, timeout, userId = null } = {}, ) { const alias = this._getAlias(index, collection); const esRequest = { @@ -2496,7 +2496,7 @@ class ElasticSearch extends Service { { prepareMUpsert: true, requireId: true, - } + }, ); /** @@ -2518,7 +2518,7 @@ class ElasticSearch extends Service { { doc: extractedDocuments[i]._source.changes, upsert: extractedDocuments[i]._source.default, - } + }, ); // _source: true // Makes ES return the updated document source in the response. @@ -2529,7 +2529,7 @@ class ElasticSearch extends Service { const response = await this._mExecute( esRequest, extractedDocuments, - rejected + rejected, ); // with _source: true, ES returns the updated document in @@ -2563,7 +2563,7 @@ class ElasticSearch extends Service { index, collection, documents, - { refresh, timeout, userId = null } = {} + { refresh, timeout, userId = null } = {}, ) { const alias = this._getAlias(index, collection), kuzzleMeta = { @@ -2722,7 +2722,7 @@ class ElasticSearch extends Service { esRequest, documents, partialErrors, - { limits = true, source = true } = {} + { limits = true, source = true } = {}, ) { assertWellFormedRefresh(esRequest); @@ -2807,7 +2807,7 @@ class ElasticSearch extends Service { _extractMDocuments( documents, metadata, - { prepareMGet = false, requireId = false, prepareMUpsert = false } = {} + { prepareMGet = false, requireId = false, prepareMUpsert = false } = {}, ) { const rejected = []; const extractedDocuments = []; @@ -2860,7 +2860,7 @@ class ElasticSearch extends Service { {}, metadata.upsert, document.changes, - document.default + document.default, ), }, }; @@ -2910,7 +2910,7 @@ class ElasticSearch extends Service { throw kerror.get( "invalid_mapping", currentPath, - didYouMean(property, mappingProperties) + didYouMean(property, mappingProperties), ); } @@ -2970,7 +2970,7 @@ class ElasticSearch extends Service { throw kerror.get( "multiple_indice_alias", `"alias" starting with "${ALIAS_PREFIX}"`, - '"indices"' + '"indices"', ); } @@ -3000,7 +3000,7 @@ class ElasticSearch extends Service { */ async _getAvailableIndice(index, collection) { let indice = this._getAlias(index, collection).substr( - INDEX_PREFIX_POSITION_IN_ALIAS + INDEX_PREFIX_POSITION_IN_ALIAS, ); if (!(await this._client.indices.exists({ index: indice })).body) { @@ -3039,7 +3039,7 @@ class ElasticSearch extends Service { async _getAliasFromIndice(indice) { const { body } = await this._client.indices.getAlias({ index: indice }); const aliases = Object.keys(body[indice].aliases).filter((alias) => - alias.startsWith(ALIAS_PREFIX) + alias.startsWith(ALIAS_PREFIX), ); if (aliases.length < 1) { @@ -3065,7 +3065,7 @@ class ElasticSearch extends Service { const indicesWithoutAlias = indices.filter( (indice) => indice[INDEX_PREFIX_POSITION_IN_INDICE] === this._indexPrefix && - !aliases.some((alias) => alias.indice === indice) + !aliases.some((alias) => alias.indice === indice), ); const esRequest = { body: { actions: [] } }; @@ -3109,7 +3109,7 @@ class ElasticSearch extends Service { _extractIndex(alias) { return alias.substr( INDEX_PREFIX_POSITION_IN_ALIAS + 1, - alias.indexOf(NAME_SEPARATOR) - INDEX_PREFIX_POSITION_IN_ALIAS - 1 + alias.indexOf(NAME_SEPARATOR) - INDEX_PREFIX_POSITION_IN_ALIAS - 1, ); } @@ -3249,7 +3249,7 @@ class ElasticSearch extends Service { hits.hits.map((h) => ({ _id: h._id, _source: h._source, - })) + })), ); } @@ -3350,14 +3350,14 @@ class ElasticSearch extends Service { assert( typeof configValue === "string", - `services.storageEngine.${key} must be a string.` + `services.storageEngine.${key} must be a string.`, ); const parsedValue = ms(configValue); assert( typeof parsedValue === "number", - `Invalid parsed value from ms() for services.storageEngine.${key} ("${typeof parsedValue}").` + `Invalid parsed value from ms() for services.storageEngine.${key} ("${typeof parsedValue}").`, ); return parsedValue; @@ -3410,7 +3410,7 @@ class ElasticSearch extends Service { esState = esStateEnum.OK; } else { global.kuzzle.log.info( - `[ℹ] Still waiting for Elasticsearch: ${health.body.number_of_pending_tasks} cluster tasks remaining` + `[ℹ] Still waiting for Elasticsearch: ${health.body.number_of_pending_tasks} cluster tasks remaining`, ); await Bluebird.delay(1000); } @@ -3433,7 +3433,7 @@ class ElasticSearch extends Service { throw kerror.get( "invalid_mapping", path, - "Dynamic property value should be a string." + "Dynamic property value should be a string.", ); } @@ -3442,8 +3442,8 @@ class ElasticSearch extends Service { "invalid_mapping", path, `Incorrect dynamic property value (${value}). Should be one of "${DYNAMIC_PROPERTY_VALUES.join( - '", "' - )}"` + '", "', + )}"`, ); } } diff --git a/lib/service/storage/esWrapper.js b/lib/service/storage/esWrapper.js index 51ddcb062d..c4d85922f8 100644 --- a/lib/service/storage/esWrapper.js +++ b/lib/service/storage/esWrapper.js @@ -197,7 +197,7 @@ class ESWrapper { if (matches) { return kerror.get( betterError.subcode, - ...betterError.getPlaceholders(error, matches) + ...betterError.getPlaceholders(error, matches), ); } } @@ -281,7 +281,7 @@ class ESWrapper { debug( 'unhandled "BadRequest" elasticsearch error: %a', - _.get(error, "meta.body.error.reason", error.message) + _.get(error, "meta.body.error.reason", error.message), ); return kerror.get("unexpected_bad_request", errorMessage); @@ -291,7 +291,7 @@ class ESWrapper { debug( "unhandled elasticsearch error (unhandled type: %s): %o", _.get(error, "error.meta.statusCode", ""), - error + error, ); return kerror.get("unexpected_error", message); diff --git a/lib/service/storage/queryTranslator.js b/lib/service/storage/queryTranslator.js index 3659792ce3..b76b08ed8f 100644 --- a/lib/service/storage/queryTranslator.js +++ b/lib/service/storage/queryTranslator.js @@ -26,7 +26,7 @@ const kerror = require("../../kerror"); class KeywordError extends Error { constructor(type, name) { super( - `The ${type} "${name}" of Koncorde DSL is not supported for search queries.` + `The ${type} "${name}" of Koncorde DSL is not supported for search queries.`, ); this.keyword = { name, type }; @@ -58,7 +58,7 @@ function parseKoncordePath(path) { "services", "koncorde", "elastic_translation_error", - `Invalid exists path "${path}": missing closing bracket` + `Invalid exists path "${path}": missing closing bracket`, ); } diff --git a/lib/types/EventHandler.ts b/lib/types/EventHandler.ts index 700eb63c2d..369ad6989d 100644 --- a/lib/types/EventHandler.ts +++ b/lib/types/EventHandler.ts @@ -41,7 +41,7 @@ export type EventDefinition = { * Handler for hook events */ export type HookEventHandler< - TEventDefinition extends EventDefinition = EventDefinition + TEventDefinition extends EventDefinition = EventDefinition, > = (...args: TEventDefinition["args"]) => void; /** @@ -50,14 +50,14 @@ export type HookEventHandler< * It should return a promise resolving the first received argument. */ export type PipeEventHandler< - TEventDefinition extends EventDefinition = EventDefinition + TEventDefinition extends EventDefinition = EventDefinition, > = (...args: TEventDefinition["args"]) => Promise; /** * Handler for cluster event. */ export type ClusterEventHandler< - TEventDefinition extends EventDefinition = EventDefinition + TEventDefinition extends EventDefinition = EventDefinition, > = (...args: TEventDefinition["args"]) => any; /** diff --git a/lib/types/HttpStream.ts b/lib/types/HttpStream.ts index d7d1b91216..b1be3a4ab4 100644 --- a/lib/types/HttpStream.ts +++ b/lib/types/HttpStream.ts @@ -41,7 +41,7 @@ export class HttpStream { constructor( readableStream: Readable, - { totalBytes = -1 }: HttpStreamProperties = {} + { totalBytes = -1 }: HttpStreamProperties = {}, ) { this.stream = readableStream; this.totalBytes = totalBytes; diff --git a/lib/types/events/EventGenericDocument.ts b/lib/types/events/EventGenericDocument.ts index 4c02404f1e..e8829be1be 100644 --- a/lib/types/events/EventGenericDocument.ts +++ b/lib/types/events/EventGenericDocument.ts @@ -65,6 +65,6 @@ export type EventGenericDocumentInjectMetadata = { * Only used when calling document:upsert. */ defaultMetadata?: JSONObject; - } + }, ]; } & PipeEventHandler; diff --git a/lib/util/assertType.js b/lib/util/assertType.js index 4246ce9cd5..8b8b010d86 100644 --- a/lib/util/assertType.js +++ b/lib/util/assertType.js @@ -69,7 +69,7 @@ function assertArray(attr, data, type) { if (d !== undefined && d !== null) { if (typeof d !== type) { throw new BadRequestError( - `Attribute ${attr} must contain only values of type "${type}"` + `Attribute ${attr} must contain only values of type "${type}"`, ); } diff --git a/lib/util/async.ts b/lib/util/async.ts index 705bb7b6a3..c41a72263f 100644 --- a/lib/util/async.ts +++ b/lib/util/async.ts @@ -6,7 +6,7 @@ */ export function promiseAllN( collection: Array<() => Promise>, - n = 100 + n = 100, ): Promise { let i = 0; let jobsLeft = collection.length; diff --git a/lib/util/bufferedPassThrough.ts b/lib/util/bufferedPassThrough.ts index 249a329614..df5672aeb9 100644 --- a/lib/util/bufferedPassThrough.ts +++ b/lib/util/bufferedPassThrough.ts @@ -65,7 +65,7 @@ export class BufferedPassThrough extends stream.Duplex { data: ChunkData, start: number, end: number, - encoding: Encoding + encoding: Encoding, ): number { if (encoding === "buffer") { return (data as Buffer).copy(this.buffer, this.offset, start, end); @@ -75,14 +75,14 @@ export class BufferedPassThrough extends stream.Duplex { data as string, this.offset, end - start, - encoding + encoding, ); } return this.buffer.write( (data as string).slice(start, end), this.offset, end - start, - encoding + encoding, ); } @@ -100,7 +100,7 @@ export class BufferedPassThrough extends stream.Duplex { */ private async writeChunkData( chunk: ChunkData, - encoding: Encoding + encoding: Encoding, ): Promise { let chunkOffset = 0; @@ -115,7 +115,7 @@ export class BufferedPassThrough extends stream.Duplex { chunk, chunkOffset, chunkOffset + remainingBufferSize, - encoding + encoding, ); // Sends the whole buffer to the stream since it is full @@ -132,7 +132,7 @@ export class BufferedPassThrough extends stream.Duplex { chunk, chunkOffset, chunk.length, - encoding + encoding, ); // Increase the internal buffer offset this.offset += size; diff --git a/lib/util/deprecate.js b/lib/util/deprecate.js index e6fc16aeb3..ad927812c9 100644 --- a/lib/util/deprecate.js +++ b/lib/util/deprecate.js @@ -30,7 +30,7 @@ const deprecationWarning = (logger, ...args) => { const warnIfDeprecated = (logger, deprecations, member) => { const deprecatedProperty = Object.keys(deprecations).find( - (deprecated) => deprecated === member + (deprecated) => deprecated === member, ), alternative = deprecations[deprecatedProperty]; @@ -43,12 +43,12 @@ const warnIfDeprecated = (logger, deprecations, member) => { } else if (typeof alternative === "string") { deprecationWarning( logger, - `Use of '${deprecatedProperty}' property is deprecated. Please, use '${alternative}' instead.` + `Use of '${deprecatedProperty}' property is deprecated. Please, use '${alternative}' instead.`, ); } else { deprecationWarning( logger, - `Use of '${deprecatedProperty}' property is deprecated.` + `Use of '${deprecatedProperty}' property is deprecated.`, ); } }; diff --git a/lib/util/dump-collection.ts b/lib/util/dump-collection.ts index 9acf65793a..0a54f3f126 100644 --- a/lib/util/dump-collection.ts +++ b/lib/util/dump-collection.ts @@ -36,7 +36,7 @@ export function flattenObject(target: JSONObject): JSONObject { function flattenStep( output: JSONObject, object: JSONObject, - prev: string | null = null + prev: string | null = null, ): void { const keys = Object.keys(object); @@ -119,7 +119,7 @@ abstract class AbstractDumper { scroll: "5s", separator: ",", size: 10, - } + }, ) { if (!writeStream) { throw kerror.get("api", "assert", "missing_argument", "writeStream"); @@ -172,7 +172,7 @@ abstract class AbstractDumper { return await global.kuzzle.ask( "core:storage:public:document:scroll", scrollId, - { scrollTTL: this.options.scroll } + { scrollTTL: this.options.scroll }, ); } catch { return null; @@ -187,7 +187,7 @@ abstract class AbstractDumper { */ async dump() { const waitWrite: Promise = new Promise((resolve, reject) => - this.writeStream ? this.writeStream.on("finish", resolve) : reject() + this.writeStream ? this.writeStream.on("finish", resolve) : reject(), ); this.writeStream.on("error", (error) => { @@ -207,7 +207,7 @@ abstract class AbstractDumper { lang: this.options.lang, scroll: this.options.scroll, size: this.options.size, - } + }, ); do { @@ -276,7 +276,7 @@ class CSVDumper extends AbstractDumper { query: any = {}, writeStream: stream.Writable, options: JSONObject, - protected fields: string[] + protected fields: string[], ) { super(index, collection, query, writeStream, options); } @@ -290,13 +290,13 @@ class CSVDumper extends AbstractDumper { const mappings = await global.kuzzle.ask( "core:storage:public:mappings:get", this.index, - this.collection + this.collection, ); if (!mappings.properties) { return; } this.fields = Object.keys( - flattenObject(extractMappingFields(mappings.properties)) + flattenObject(extractMappingFields(mappings.properties)), ); } else if (this.fields.includes("_id")) { // Delete '_id' from the selected fields, since IDs are @@ -334,7 +334,7 @@ export function dumpCollectionDocuments( query: any = {}, format = "jsonl", fields: string[] = [], - options: JSONObject = {} + options: JSONObject = {}, ): HttpStream { let dumper: AbstractDumper; @@ -348,7 +348,7 @@ export function dumpCollectionDocuments( query, writableStream, options, - fields + fields, ); dumper.dump(); break; @@ -358,7 +358,7 @@ export function dumpCollectionDocuments( collection, query, writableStream, - options + options, ); dumper.dump(); break; diff --git a/lib/util/extractFields.js b/lib/util/extractFields.js index a0c48ca731..8303564967 100644 --- a/lib/util/extractFields.js +++ b/lib/util/extractFields.js @@ -35,7 +35,7 @@ const { isPlainObject } = require("./safeObject"); function extractFields( document, { fieldsToIgnore = [], alsoExtractValues = false } = {}, - { path = null, extractedFields = [] } = {} + { path = null, extractedFields = [] } = {}, ) { for (const [key, value] of Object.entries(document)) { if ( @@ -51,7 +51,7 @@ function extractFields( extractFields( value, { alsoExtractValues, fieldsToIgnore }, - { extractedFields, path: currentPath } + { extractedFields, path: currentPath }, ); } else if (alsoExtractValues) { extractedFields.push({ key: currentPath, value }); diff --git a/lib/util/koncordeCompat.ts b/lib/util/koncordeCompat.ts index 265b7f682c..668c1aa958 100644 --- a/lib/util/koncordeCompat.ts +++ b/lib/util/koncordeCompat.ts @@ -74,7 +74,7 @@ export function koncordeTest( index: string, collection: string, body: JSONObject, - _id?: string + _id?: string, ): string[] { const indexV4 = toKoncordeIndex(index, collection); diff --git a/lib/util/mutex.ts b/lib/util/mutex.ts index 9fb117e7db..4231950ec6 100644 --- a/lib/util/mutex.ts +++ b/lib/util/mutex.ts @@ -104,7 +104,7 @@ export class Mutex { */ constructor( resource: string, - { attemptDelay = 200, timeout = -1, ttl = 5000 }: MutexOptions = {} + { attemptDelay = 200, timeout = -1, ttl = 5000 }: MutexOptions = {}, ) { this.resource = resource; this.mutexId = `${global.kuzzle.id}/${randomBytes(16).toString("hex")}`; @@ -124,7 +124,7 @@ export class Mutex { if (this._locked) { throw fatal.get( "assertion_failed", - `resource "${this.resource}" already locked by this mutex (id: ${this.mutexId})` + `resource "${this.resource}" already locked by this mutex (id: ${this.mutexId})`, ); } @@ -135,7 +135,7 @@ export class Mutex { "core:cache:internal:store", this.resource, this.mutexId, - { onlyIfNew: true, ttl: this.ttl } + { onlyIfNew: true, ttl: this.ttl }, ); duration += this.attemptDelay; @@ -167,7 +167,7 @@ export class Mutex { if (!this._locked) { throw fatal.get( "assertion_failed", - `tried to unlock the resource "${this.resource}", which is not locked (mutex id: ${this.mutexId})` + `tried to unlock the resource "${this.resource}", which is not locked (mutex id: ${this.mutexId})`, ); } @@ -176,7 +176,7 @@ export class Mutex { "core:cache:internal:script:define", "delIfValueEqual", 1, - delIfValueEqualLua + delIfValueEqualLua, ); delScriptRegistered = true; } @@ -185,7 +185,7 @@ export class Mutex { "core:cache:internal:script:execute", "delIfValueEqual", this.resource, - this.mutexId + this.mutexId, ); this._locked = false; @@ -218,7 +218,7 @@ export class Mutex { do { isLocked = await global.kuzzle.ask( "core:cache:internal:get", - this.resource + this.resource, ); duration += attemptDelay; diff --git a/lib/util/name-generator.ts b/lib/util/name-generator.ts index 2c422c5d0f..3e1b619960 100644 --- a/lib/util/name-generator.ts +++ b/lib/util/name-generator.ts @@ -124,7 +124,7 @@ export class NameGenerator { return `${prefix}${adjective}${separator}${name}${separator}${randomNumber( min, - max + max, )}`; } } diff --git a/lib/util/wildcard.js b/lib/util/wildcard.js index d008aabbb4..b99bff9e82 100644 --- a/lib/util/wildcard.js +++ b/lib/util/wildcard.js @@ -36,7 +36,7 @@ function match(pattern, list) { .split("*") .filter( (patternPart, index, array) => - patternPart !== "" || index === 0 || index === array.length - 1 + patternPart !== "" || index === 0 || index === array.length - 1, ) .map((patternPart) => _.escapeRegExp(patternPart)) // escape special regex characters .join(".*"); diff --git a/package-lock.json b/package-lock.json index 752a0a67fb..f239895dd1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,8 +19,8 @@ "didyoumean": "1.2.2", "dumpme": "1.0.3", "eventemitter3": "4.0.7", - "inquirer": "9.1.4", - "ioredis": "5.3.0", + "inquirer": "9.2.12", + "ioredis": "5.3.2", "js-yaml": "4.1.0", "json-stable-stringify": "1.0.2", "json2yaml": "1.1.0", @@ -28,27 +28,27 @@ "koncorde": "4.3.0", "kuzzle-plugin-auth-passport-local": "6.4.0", "kuzzle-plugin-logger": "3.0.3", - "kuzzle-sdk": "7.11.0", + "kuzzle-sdk": "7.11.1", "kuzzle-vault": "2.0.4", "lodash": "4.17.21", - "long": "5.2.1", + "long": "5.2.3", "moment": "2.29.4", "ms": "2.1.3", "murmurhash-native": "3.5.0", "ndjson": "2.0.0", "node-segfault-handler": "1.4.2", "passport": "0.6.0", - "protobufjs": "~7.2.1", + "protobufjs": "7.2.5", "rc": "1.2.8", - "semver": "7.3.8", + "semver": "7.5.4", "sorted-array": "2.0.4", "uuid": "9.0.1", - "uWebSockets.js": "https://github.com/uNetworking/uWebSockets.js/archive/refs/tags/v20.32.0.tar.gz", + "uWebSockets.js": "https://github.com/uNetworking/uWebSockets.js/archive/refs/tags/v20.34.0.tar.gz", "validator": "13.11.0", - "winston": "3.10.0", + "winston": "3.11.0", "winston-elasticsearch": "0.17.4", "winston-syslog": "2.7.0", - "winston-transport": "4.5.0", + "winston-transport": "4.6.0", "yargs": "17.7.2", "zeromq": "6.0.0-beta.6" }, @@ -65,7 +65,7 @@ "codecov": "3.8.3", "cucumber": "6.0.5", "ergol": "1.0.2", - "eslint-plugin-kuzzle": "0.0.6", + "eslint-plugin-kuzzle": "0.0.12", "jest": "29.7.0", "mocha": "10.2.0", "mock-require": "3.0.3", @@ -78,7 +78,7 @@ "should-sinon": "0.0.6", "sinon": "14.0.2", "strip-json-comments": "https://github.com/sindresorhus/strip-json-comments/archive/refs/tags/v3.1.1.tar.gz", - "ts-jest": "29.0.5", + "ts-jest": "29.1.1", "ts-node": "10.9.1", "typescript": "4.9.5", "yaml": "2.2.1" @@ -772,9 +772,9 @@ "dev": true }, "node_modules/@colors/colors": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", - "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz", + "integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==", "engines": { "node": ">=0.1.90" } @@ -1504,6 +1504,17 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@ljharb/through": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/@ljharb/through/-/through-2.3.11.tgz", + "integrity": "sha512-ccfcIDlogiXNq5KcbAwbaO7lMh3Tm1i3khMPYpxlK8hH/W53zN81KM9coerRLOnTGu3nfXIniAmQbRI9OxbC0w==", + "dependencies": { + "call-bind": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -1625,6 +1636,26 @@ "node": ">=14" } }, + "node_modules/@pkgr/utils": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/@pkgr/utils/-/utils-2.4.2.tgz", + "integrity": "sha512-POgTXhjrTfbTV63DiFXav4lBHiICLKKwDeaKn9Nphwj7WH6m0hMMCaJkMyRWjgtPFyRKRVoMXXjczsTQRDEhYw==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.3", + "fast-glob": "^3.3.0", + "is-glob": "^4.0.3", + "open": "^9.1.0", + "picocolors": "^1.0.0", + "tslib": "^2.6.0" + }, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" + } + }, "node_modules/@protobufjs/aspromise": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", @@ -2298,7 +2329,6 @@ "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", - "dev": true, "dependencies": { "type-fest": "^0.21.3" }, @@ -2313,7 +2343,6 @@ "version": "0.21.3", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", - "dev": true, "engines": { "node": ">=10" }, @@ -2794,6 +2823,15 @@ "integrity": "sha512-FnWonOyaw7Vivg5nIkrUll9HSS5TjFbyuURAiDssuL6VxrBe3ERzudRxOcWRhZYlP89UArMDikz7SapRPQpmZQ==", "dev": true }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "dev": true, + "engines": { + "node": ">=0.6" + } + }, "node_modules/binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", @@ -2846,6 +2884,18 @@ "npm": ">= 2.14.4" } }, + "node_modules/bplist-parser": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.2.0.tgz", + "integrity": "sha512-z0M+byMThzQmD9NILRniCUXYsYpjwnlO8N5uCFaCqIOpqRsJCrQL9NK3JsD67CN5a08nF5oIL2bD6loTdHOuKw==", + "dev": true, + "dependencies": { + "big-integer": "^1.6.44" + }, + "engines": { + "node": ">= 5.10.0" + } + }, "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -2978,6 +3028,21 @@ "readable-stream": "^3.1.1" } }, + "node_modules/bundle-name": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-3.0.0.tgz", + "integrity": "sha512-PKA4BeSvBpQKQ8iPOGCSiell+N8P+Tf1DlwqmYhpe2gAhKPHn8EYOxVT+ShuGmhg8lN8XiSlS80yiExKXrURlw==", + "dev": true, + "dependencies": { + "run-applescript": "^5.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/cacache": { "version": "17.1.4", "resolved": "https://registry.npmjs.org/cacache/-/cacache-17.1.4.tgz", @@ -3224,7 +3289,6 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.5.tgz", "integrity": "sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==", - "optional": true, "dependencies": { "function-bind": "^1.1.2", "get-intrinsic": "^1.2.1", @@ -3282,7 +3346,6 @@ "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -3388,7 +3451,6 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", - "dev": true, "dependencies": { "restore-cursor": "^3.1.0" }, @@ -3397,9 +3459,9 @@ } }, "node_modules/cli-spinners": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.1.tgz", - "integrity": "sha512-jHgecW0pxkonBJdrKsqxgRX9AcG+u/5k0Q7WPDfi8AogLAdwxEkyYYNWwZ5GvVFoFx2uiY1eNcSK00fh+1+FyQ==", + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", "engines": { "node": ">=6" }, @@ -3932,6 +3994,150 @@ "node": ">=0.10.0" } }, + "node_modules/default-browser": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-4.0.0.tgz", + "integrity": "sha512-wX5pXO1+BrhMkSbROFsyxUm0i/cJEScyNhA4PPxc41ICuv05ZZB/MX28s8aZx6xjmatvebIapF6hLEKEcpneUA==", + "dev": true, + "dependencies": { + "bundle-name": "^3.0.0", + "default-browser-id": "^3.0.0", + "execa": "^7.1.1", + "titleize": "^3.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/default-browser-id": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/default-browser-id/-/default-browser-id-3.0.0.tgz", + "integrity": "sha512-OZ1y3y0SqSICtE8DE4S8YOE9UZOJ8wO16fKWVP5J1Qz42kV9jcnMVFrEE/noXb/ss3Q4pZIH79kxofzyNNtUNA==", + "dev": true, + "dependencies": { + "bplist-parser": "^0.2.0", + "untildify": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/default-browser/node_modules/execa": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-7.2.0.tgz", + "integrity": "sha512-UduyVP7TLB5IcAQl+OzLyLcS/l32W/GLg+AhHJ+ow40FOk2U3SAllPwR44v4vmdFwIWqpdwxxpQbF1n5ta9seA==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.1", + "human-signals": "^4.3.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^3.0.7", + "strip-final-newline": "^3.0.0" + }, + "engines": { + "node": "^14.18.0 || ^16.14.0 || >=18.0.0" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/default-browser/node_modules/human-signals": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-4.3.1.tgz", + "integrity": "sha512-nZXjEF2nbo7lIw3mgYjItAfgQXog3OjJogSbKa2CQIIvSGWcKgeJnQlNXip6NglNzYH45nSRiEVimMvYL8DDqQ==", + "dev": true, + "engines": { + "node": ">=14.18.0" + } + }, + "node_modules/default-browser/node_modules/is-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", + "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", + "dev": true, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/default-browser/node_modules/mimic-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", + "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/default-browser/node_modules/npm-run-path": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.1.0.tgz", + "integrity": "sha512-sJOdmRGrY2sjNTRMbSvluQqg+8X7ZK61yvzBEIDhz4f8z1TZFYABsqjjCBd/0PUNE9M6QDgHJXQkGUEm7Q+l9Q==", + "dev": true, + "dependencies": { + "path-key": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/default-browser/node_modules/onetime": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", + "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", + "dev": true, + "dependencies": { + "mimic-fn": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/default-browser/node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/default-browser/node_modules/strip-final-newline": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", + "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/default-require-extensions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-3.0.1.tgz", @@ -3962,7 +4168,6 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz", "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==", - "optional": true, "dependencies": { "get-intrinsic": "^1.2.1", "gopd": "^1.0.1", @@ -3972,6 +4177,18 @@ "node": ">= 0.4" } }, + "node_modules/define-lazy-prop": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-3.0.0.tgz", + "integrity": "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/define-properties": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", @@ -4584,35 +4801,72 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint-plugin-jest": { + "version": "27.6.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-27.6.0.tgz", + "integrity": "sha512-MTlusnnDMChbElsszJvrwD1dN3x6nZl//s4JD23BxB6MgR66TZlL064su24xEIS3VACfAoHV1vgyMgPw8nkdng==", + "dev": true, + "dependencies": { + "@typescript-eslint/utils": "^5.10.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@typescript-eslint/eslint-plugin": "^5.0.0 || ^6.0.0", + "eslint": "^7.0.0 || ^8.0.0", + "jest": "*" + }, + "peerDependenciesMeta": { + "@typescript-eslint/eslint-plugin": { + "optional": true + }, + "jest": { + "optional": true + } + } + }, "node_modules/eslint-plugin-kuzzle": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/eslint-plugin-kuzzle/-/eslint-plugin-kuzzle-0.0.6.tgz", - "integrity": "sha512-1tWOBxr0Fpe7yVFh3WLwrN8jgjaA39yKM0ohAkLNAN22P4HvPrN2rk0EhEUA8UFrpuRpX4wp4sF1HYUXJ2786g==", + "version": "0.0.12", + "resolved": "https://registry.npmjs.org/eslint-plugin-kuzzle/-/eslint-plugin-kuzzle-0.0.12.tgz", + "integrity": "sha512-Fqqeqp85i0yu0yJ44tdWFHL9xzpcExwc94ho363VbcPQHve92FSFaDXxTO+jPd3IYlTrWa/5viKvGsHJGxsVVQ==", "dev": true, "dependencies": { "@typescript-eslint/eslint-plugin": "^5.38.0", "@typescript-eslint/parser": "^5.38.0", - "eslint": "^8.23.1", - "eslint-plugin-prettier": "^4.2.1", - "prettier": "^2.7.1" + "eslint": "^8.45.0", + "eslint-plugin-jest": "^27.2.3", + "eslint-plugin-prettier": "^5.0.0", + "prettier": "^3.0.0" + }, + "engines": { + "node": ">=16.0.0" } }, "node_modules/eslint-plugin-prettier": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-4.2.1.tgz", - "integrity": "sha512-f/0rXLXUt0oFYs8ra4w49wYZBG5GKZpAYsJSm6rnYL5uVDjd+zowwMwVZHnAjf4edNrKpCDYfXDgmRE/Ak7QyQ==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.0.1.tgz", + "integrity": "sha512-m3u5RnR56asrwV/lDC4GHorlW75DsFfmUcjfCYylTUs85dBRnB7VM6xG8eCMJdeDRnppzmxZVf1GEPJvl1JmNg==", "dev": true, "dependencies": { - "prettier-linter-helpers": "^1.0.0" + "prettier-linter-helpers": "^1.0.0", + "synckit": "^0.8.5" }, "engines": { - "node": ">=12.0.0" + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/prettier" }, "peerDependencies": { - "eslint": ">=7.28.0", - "prettier": ">=2.0.0" + "@types/eslint": ">=8.0.0", + "eslint": ">=8.0.0", + "prettier": ">=3.0.0" }, "peerDependenciesMeta": { + "@types/eslint": { + "optional": true + }, "eslint-config-prettier": { "optional": true } @@ -5355,7 +5609,6 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "devOptional": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -5470,7 +5723,6 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz", "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==", - "optional": true, "dependencies": { "function-bind": "^1.1.2", "has-proto": "^1.0.1", @@ -5630,7 +5882,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", - "optional": true, "dependencies": { "get-intrinsic": "^1.1.3" }, @@ -5685,7 +5936,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, "engines": { "node": ">=8" } @@ -5694,7 +5944,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz", "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==", - "optional": true, "dependencies": { "get-intrinsic": "^1.2.2" }, @@ -5706,7 +5955,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz", "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", - "optional": true, "engines": { "node": ">= 0.4" }, @@ -5718,7 +5966,6 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", - "optional": true, "engines": { "node": ">= 0.4" }, @@ -5775,7 +6022,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", - "devOptional": true, "dependencies": { "function-bind": "^1.1.2" }, @@ -6031,64 +6277,28 @@ "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" }, "node_modules/inquirer": { - "version": "9.1.4", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-9.1.4.tgz", - "integrity": "sha512-9hiJxE5gkK/cM2d1mTEnuurGTAoHebbkX0BYl3h7iEg7FYfuNIom+nDfBCSWtvSnoSrWCeBxqqBZu26xdlJlXA==", - "dependencies": { - "ansi-escapes": "^6.0.0", - "chalk": "^5.1.2", - "cli-cursor": "^4.0.0", - "cli-width": "^4.0.0", - "external-editor": "^3.0.3", + "version": "9.2.12", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-9.2.12.tgz", + "integrity": "sha512-mg3Fh9g2zfuVWJn6lhST0O7x4n03k7G8Tx5nvikJkbq8/CK47WDVm+UznF0G6s5Zi0KcyUisr6DU8T67N5U+1Q==", + "dependencies": { + "@ljharb/through": "^2.3.11", + "ansi-escapes": "^4.3.2", + "chalk": "^5.3.0", + "cli-cursor": "^3.1.0", + "cli-width": "^4.1.0", + "external-editor": "^3.1.0", "figures": "^5.0.0", "lodash": "^4.17.21", - "mute-stream": "0.0.8", - "ora": "^6.1.2", - "run-async": "^2.4.0", - "rxjs": "^7.5.7", - "string-width": "^5.1.2", - "strip-ansi": "^7.0.1", - "through": "^2.3.6", - "wrap-ansi": "^8.0.1" - }, - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/inquirer/node_modules/ansi-escapes": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-6.2.0.tgz", - "integrity": "sha512-kzRaCqXnpzWs+3z5ABPQiVke+iq0KXkHo8xiWV4RPTi5Yli0l97BEQuhXV1s7+aSU/fu1kUuxgS4MsQ0fRuygw==", - "dependencies": { - "type-fest": "^3.0.0" - }, - "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/inquirer/node_modules/ansi-regex": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", - "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", - "engines": { - "node": ">=12" + "mute-stream": "1.0.0", + "ora": "^5.4.1", + "run-async": "^3.0.0", + "rxjs": "^7.8.1", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^6.2.0" }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/inquirer/node_modules/ansi-styles": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", - "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" + "node": ">=14.18.0" } }, "node_modules/inquirer/node_modules/chalk": { @@ -6102,25 +6312,6 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/inquirer/node_modules/cli-cursor": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", - "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", - "dependencies": { - "restore-cursor": "^4.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/inquirer/node_modules/emoji-regex": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", - "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" - }, "node_modules/inquirer/node_modules/escape-string-regexp": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", @@ -6147,6 +6338,14 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/inquirer/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, "node_modules/inquirer/node_modules/is-unicode-supported": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", @@ -6158,76 +6357,33 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/inquirer/node_modules/restore-cursor": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", - "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", - "dependencies": { - "onetime": "^5.1.0", - "signal-exit": "^3.0.2" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/inquirer/node_modules/string-width": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", - "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", - "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/inquirer/node_modules/strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "dependencies": { - "ansi-regex": "^6.0.1" - }, + "node_modules/inquirer/node_modules/mute-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-1.0.0.tgz", + "integrity": "sha512-avsJQhyd+680gKXyG/sQc0nXaC6rBkPOfyHYcFb9+hdkqQkR9bdnkJ0AMZhke0oesPqIO+mFFJ+IdBc7mst4IA==", "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" } }, - "node_modules/inquirer/node_modules/type-fest": { - "version": "3.13.1", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-3.13.1.tgz", - "integrity": "sha512-tLq3bSNx+xSpwvAJnzrK0Ep5CLNWjvFTOp71URMaAEWBfRb9nnJiBoUe0tF8bI4ZFO3omgBR6NvnbzVUT3Ly4g==", + "node_modules/inquirer/node_modules/run-async": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-3.0.0.tgz", + "integrity": "sha512-540WwVDOMxA6dN6We19EcT9sc3hkXPw5mzRNGM3FkdN/vtE9NFvj5lFAPNwUDmJjXidm3v7TC1cTE7t17Ulm1Q==", "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=0.12.0" } }, - "node_modules/inquirer/node_modules/wrap-ansi": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", - "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "node_modules/inquirer/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" }, "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + "node": ">=8" } }, "node_modules/install-artifact-from-github": { @@ -6254,9 +6410,9 @@ } }, "node_modules/ioredis": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.3.0.tgz", - "integrity": "sha512-Id9jKHhsILuIZpHc61QkagfVdUj2Rag5GzG1TGEvRNeM7dtTOjICgjC+tvqYxi//PuX2wjQ+Xjva2ONBuf92Pw==", + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.3.2.tgz", + "integrity": "sha512-1DKMMzlIHM02eBBVOFQ1+AolGjs6+xEcM4PDL7NqOS6szq7H9jSaEkIUH6/a5Hl241LzW6JLSiAbNvTQjUupUA==", "dependencies": { "@ioredis/commands": "^1.1.1", "cluster-key-slot": "^1.1.0", @@ -6380,6 +6536,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-docker": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", + "integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==", + "dev": true, + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -6436,6 +6607,24 @@ "node": ">=0.10.0" } }, + "node_modules/is-inside-container": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz", + "integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==", + "dev": true, + "dependencies": { + "is-docker": "^3.0.0" + }, + "bin": { + "is-inside-container": "cli.js" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-integer": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/is-integer/-/is-integer-1.0.7.tgz", @@ -6446,14 +6635,11 @@ } }, "node_modules/is-interactive": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", - "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=8" } }, "node_modules/is-lambda": { @@ -6630,7 +6816,6 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", - "dev": true, "engines": { "node": ">=10" }, @@ -6659,6 +6844,33 @@ "node": ">=0.10.0" } }, + "node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-wsl/node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true, + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", @@ -6705,47 +6917,14 @@ "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^7.5.4" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-instrument/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-instrument/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" }, "engines": { "node": ">=10" } }, - "node_modules/istanbul-lib-instrument/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - }, "node_modules/istanbul-lib-processinfo": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/istanbul-lib-processinfo/-/istanbul-lib-processinfo-2.0.3.tgz", @@ -7305,39 +7484,6 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, - "node_modules/jest-snapshot/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/jest-snapshot/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/jest-snapshot/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - }, "node_modules/jest-util": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", @@ -7770,9 +7916,9 @@ } }, "node_modules/kuzzle-sdk": { - "version": "7.11.0", - "resolved": "https://registry.npmjs.org/kuzzle-sdk/-/kuzzle-sdk-7.11.0.tgz", - "integrity": "sha512-g1fvQLCm5/zFntwNa+09bIniyzofVVIanVBWcOuzjwqgg7sHeILJQUsiGdLaKQFQmZHrdfkYWQrcoD9f0Qb7Fg==", + "version": "7.11.1", + "resolved": "https://registry.npmjs.org/kuzzle-sdk/-/kuzzle-sdk-7.11.1.tgz", + "integrity": "sha512-1nPZmekFE2Q1gNhPisn9kg1/LsDRzDnl4GIYGdjIHISK5BhiAICMEsmMMyTiYqja42/mdMqm+M5bFx4p3wMJdQ==", "dependencies": { "min-req-promise": "^1.0.1", "ws": "^8.13.0" @@ -7929,7 +8075,6 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", - "dev": true, "dependencies": { "chalk": "^4.1.0", "is-unicode-supported": "^0.1.0" @@ -7957,18 +8102,10 @@ "node": ">= 12.0.0" } }, - "node_modules/logform/node_modules/@colors/colors": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz", - "integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==", - "engines": { - "node": ">=0.1.90" - } - }, "node_modules/long": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/long/-/long-5.2.1.tgz", - "integrity": "sha512-GKSNGeNAtw8IryjjkhZxuKB3JzlcLTwjtiQCHKvqQet81I93kXslhDQruGI/QsddO83mcDToBVy7GqGS/zYf/A==" + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz", + "integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==" }, "node_modules/lower-case": { "version": "1.1.4", @@ -8008,39 +8145,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/make-dir/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/make-dir/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/make-dir/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - }, "node_modules/make-error": { "version": "1.3.6", "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", @@ -8776,7 +8880,8 @@ "node_modules/mute-stream": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", - "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==" + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true }, "node_modules/mz": { "version": "2.7.0", @@ -9634,6 +9739,24 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/open": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/open/-/open-9.1.0.tgz", + "integrity": "sha512-OS+QTnw1/4vrf+9hh1jc1jnYjzSG4ttTBB8UxOwAnInG3Uo4ssetzC1ihqaIHjLJnA5GGlRl6QlZXOTQhRBUvg==", + "dev": true, + "dependencies": { + "default-browser": "^4.0.0", + "define-lazy-prop": "^3.0.0", + "is-inside-container": "^1.0.0", + "is-wsl": "^2.2.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/optional-js": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/optional-js/-/optional-js-2.3.0.tgz", @@ -9658,118 +9781,27 @@ } }, "node_modules/ora": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/ora/-/ora-6.3.1.tgz", - "integrity": "sha512-ERAyNnZOfqM+Ao3RAvIXkYh5joP220yf59gVe2X/cI6SiCxIdi4c9HZKZD8R6q/RDXEje1THBju6iExiSsgJaQ==", - "dependencies": { - "chalk": "^5.0.0", - "cli-cursor": "^4.0.0", - "cli-spinners": "^2.6.1", - "is-interactive": "^2.0.0", - "is-unicode-supported": "^1.1.0", - "log-symbols": "^5.1.0", - "stdin-discarder": "^0.1.0", - "strip-ansi": "^7.0.1", - "wcwidth": "^1.0.1" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ora/node_modules/ansi-regex": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", - "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/ora/node_modules/chalk": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", - "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", - "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/ora/node_modules/cli-cursor": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", - "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", - "dependencies": { - "restore-cursor": "^4.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ora/node_modules/is-unicode-supported": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", - "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ora/node_modules/log-symbols": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-5.1.0.tgz", - "integrity": "sha512-l0x2DvrW294C9uDCoQe1VSU4gf529FkSZ6leBl4TiqZH/e+0R7hSfHQBNut2mNygDgHwvYHfFLn6Oxb3VWj2rA==", - "dependencies": { - "chalk": "^5.0.0", - "is-unicode-supported": "^1.1.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ora/node_modules/restore-cursor": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", - "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", + "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", "dependencies": { - "onetime": "^5.1.0", - "signal-exit": "^3.0.2" + "bl": "^4.1.0", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.5.0", + "is-interactive": "^1.0.0", + "is-unicode-supported": "^0.1.0", + "log-symbols": "^4.1.0", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" }, "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/ora/node_modules/strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "dependencies": { - "ansi-regex": "^6.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, "node_modules/original-url": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/original-url/-/original-url-1.2.3.tgz", @@ -10156,15 +10188,15 @@ } }, "node_modules/prettier": { - "version": "2.8.8", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", - "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.1.0.tgz", + "integrity": "sha512-TQLvXjq5IAibjh8EpBIkNKxO749UEWABoiIZehEPiY4GNpVdhaFKqSTu+QrlU6D2dPAfubRmtJTi4K4YkQ5eXw==", "dev": true, "bin": { - "prettier": "bin-prettier.js" + "prettier": "bin/prettier.cjs" }, "engines": { - "node": ">=10.13.0" + "node": ">=14" }, "funding": { "url": "https://github.com/prettier/prettier?sponsor=1" @@ -10721,7 +10753,6 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", - "dev": true, "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" @@ -11354,10 +11385,26 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/run-applescript": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-5.0.0.tgz", + "integrity": "sha512-XcT5rBksx1QdIhlFOCtgZkB99ZEouFZ1E2Kc2LHqNW13U3/74YGdkQRmThTwxy4QIyookibDKYZOPqX//6BlAg==", + "dev": true, + "dependencies": { + "execa": "^5.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/run-async": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "dev": true, "engines": { "node": ">=0.12.0" } @@ -11480,9 +11527,9 @@ "dev": true }, "node_modules/semver": { - "version": "7.3.8", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", - "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dependencies": { "lru-cache": "^6.0.0" }, @@ -11548,7 +11595,6 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.1.1.tgz", "integrity": "sha512-VoaqjbBJKiWtg4yRcKBQ7g7wnGnLV3M8oLvVWwOk2PdYY6PEFegR1vezXR0tw6fZGF9csVakIRjrJiy2veSBFQ==", - "optional": true, "dependencies": { "define-data-property": "^1.1.1", "get-intrinsic": "^1.2.1", @@ -12055,53 +12101,6 @@ "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==" }, - "node_modules/stdin-discarder": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.1.0.tgz", - "integrity": "sha512-xhV7w8S+bUwlPTb4bAOUQhv8/cSS5offJuX8GQGq32ONF0ZtDWKfkdomM3HMRA+LhX6um/FZ0COqlwsjD53LeQ==", - "dependencies": { - "bl": "^5.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/stdin-discarder/node_modules/bl": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-5.1.0.tgz", - "integrity": "sha512-tv1ZJHLfTDnXE6tMHv73YgSJaWR2AFuPwMntBe7XL/GBFHnT0CLnsHMogfk5+GzCDC5ZWarSCYaIGATZt9dNsQ==", - "dependencies": { - "buffer": "^6.0.3", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, - "node_modules/stdin-discarder/node_modules/buffer": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", - "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.2.1" - } - }, "node_modules/stealthy-require": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/stealthy-require/-/stealthy-require-1.1.1.tgz", @@ -12334,7 +12333,6 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -12354,6 +12352,22 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/synckit": { + "version": "0.8.5", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.8.5.tgz", + "integrity": "sha512-L1dapNV6vu2s/4Sputv8xGsCdAVlb5nRDMFU/E27D44l5U6cw1g0dGd45uLc+OXjNMmF4ntiMdCimzcjFKQI8Q==", + "dev": true, + "dependencies": { + "@pkgr/utils": "^2.3.1", + "tslib": "^2.5.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/unts" + } + }, "node_modules/table": { "version": "5.4.6", "resolved": "https://registry.npmjs.org/table/-/table-5.4.6.tgz", @@ -12549,7 +12563,8 @@ "node_modules/through": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==" + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", + "dev": true }, "node_modules/through2": { "version": "4.0.2", @@ -12578,6 +12593,18 @@ "upper-case": "^1.0.3" } }, + "node_modules/titleize": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/titleize/-/titleize-3.0.0.tgz", + "integrity": "sha512-KxVu8EYHDPBdUYdKZdKtU2aj2XfEx9AfjXxE/Aj0vT06w2icA09Vus1rh6eSu1y01akYg6BjIK/hxyLJINoMLQ==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/tmp": { "version": "0.0.33", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", @@ -12658,9 +12685,9 @@ "integrity": "sha512-Ck+9CKS+lZ277gvUSbrV99ZKLlgZCEANUIZNmOsf8749LQnJ6vYk92dWwaVdCOj4jdEc1TebC8Fu3i2aK0H6cA==" }, "node_modules/ts-jest": { - "version": "29.0.5", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.0.5.tgz", - "integrity": "sha512-PL3UciSgIpQ7f6XjVOmbi96vmDHUqAyqDr8YxzopDqX3kfgYtX1cuNeBjP+L9sFXi6nzsGGA6R3fP3DDDJyrxA==", + "version": "29.1.1", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.1.1.tgz", + "integrity": "sha512-D6xjnnbP17cC85nliwGiL+tpoKN0StpgE0TeOjXQTU6MVCfsB4v7aW05CgQ/1OywGb0x/oy9hHFnN+sczTiRaA==", "dev": true, "dependencies": { "bs-logger": "0.x", @@ -12669,7 +12696,7 @@ "json5": "^2.2.3", "lodash.memoize": "4.x", "make-error": "1.x", - "semver": "7.x", + "semver": "^7.5.3", "yargs-parser": "^21.0.1" }, "bin": { @@ -12683,7 +12710,7 @@ "@jest/types": "^29.0.0", "babel-jest": "^29.0.0", "jest": "^29.0.0", - "typescript": ">=4.3" + "typescript": ">=4.3 <6" }, "peerDependenciesMeta": { "@babel/core": { @@ -13010,6 +13037,15 @@ "node": ">=0.10.48" } }, + "node_modules/untildify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/untildify/-/untildify-4.0.0.tgz", + "integrity": "sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, "node_modules/update-browserslist-db": { "version": "1.0.13", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", @@ -13101,9 +13137,9 @@ "integrity": "sha512-OdmXxA8rDsQ7YpNVbKSJkNzTw2I+S5WsbMDnCtIWSQaosNAcWtFuI/YK1TjzUI6nbkgiqEyh8gWngfcv8Asd9A==" }, "node_modules/uWebSockets.js": { - "version": "20.32.0", - "resolved": "https://github.com/uNetworking/uWebSockets.js/archive/refs/tags/v20.32.0.tar.gz", - "integrity": "sha512-9yW46miwZrz/78C9HledabscJrjoK0ZTL+mp/X05iLoWuEXyAxqzUzY/3CYYAdRmNL2FF98iRcGT7d33qxnBdQ==", + "version": "20.34.0", + "resolved": "https://github.com/uNetworking/uWebSockets.js/archive/refs/tags/v20.34.0.tar.gz", + "integrity": "sha512-CHw0g1nmfNi8R9KrnMGp8KVjiO2sK7N+eVPPvnYR7A1GpJ2ozTCpx/C80LbvVghaxJC+SfZw6XsehZvRPHnamg==", "license": "Apache-2.0" }, "node_modules/v8-compile-cache": { @@ -13251,11 +13287,11 @@ } }, "node_modules/winston": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/winston/-/winston-3.10.0.tgz", - "integrity": "sha512-nT6SIDaE9B7ZRO0u3UvdrimG0HkB7dSTAgInQnNR2SOPJ4bvq5q79+pXLftKmP52lJGW15+H5MCK0nM9D3KB/g==", + "version": "3.11.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-3.11.0.tgz", + "integrity": "sha512-L3yR6/MzZAOl0DsysUXHVjOwv8mKZ71TrA/41EIduGpOOV5LQVodqN+QdQ6BS6PJ/RdIshZhq84P/fStEZkk7g==", "dependencies": { - "@colors/colors": "1.5.0", + "@colors/colors": "^1.6.0", "@dabh/diagnostics": "^2.0.2", "async": "^3.2.3", "is-stream": "^2.0.0", @@ -13331,16 +13367,16 @@ } }, "node_modules/winston-transport": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.5.0.tgz", - "integrity": "sha512-YpZzcUzBedhlTAfJg6vJDlyEai/IFMIVcaEZZyl3UXIl4gmqRpU7AE89AHLkbzLUsv0NVmw7ts+iztqKxxPW1Q==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.6.0.tgz", + "integrity": "sha512-wbBA9PbPAHxKiygo7ub7BYRiKxms0tpfU2ljtWzb3SjRjv5yl6Ozuy/TkXf00HTAt+Uylo3gSkNwzc4ME0wiIg==", "dependencies": { "logform": "^2.3.2", "readable-stream": "^3.6.0", "triple-beam": "^1.3.0" }, "engines": { - "node": ">= 6.4.0" + "node": ">= 12.0.0" } }, "node_modules/word-wrap": { @@ -13362,7 +13398,6 @@ "version": "6.2.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", - "dev": true, "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -13414,7 +13449,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, "engines": { "node": ">=8" } @@ -13423,7 +13457,6 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", diff --git a/package.json b/package.json index e73aea61a4..ba12e9b8d5 100644 --- a/package.json +++ b/package.json @@ -9,32 +9,21 @@ "clean": "touch index.ts && npm run build | grep TSFILE | cut -d' ' -f 2 | xargs rm", "codecov": "codecov", "cucumber": "cucumber.js --fail-fast", - "dev:test": "npm run dev -- docker/scripts/start-kuzzle-test.ts --enable-plugins functional-test-plugin", - "dev": "npx ergol docker/scripts/start-kuzzle-dev.ts -c ./config/ergol.config.json", + "dev": "ergol docker/scripts/start-kuzzle-dev.ts -c ./config/ergol.config.json", "doc-error-codes": "node -r ts-node/register doc/build-error-codes", - "docker:install": "docker compose run kuzzle_node_1 npm ci", - "docker:npm": "docker compose run kuzzle_node_1 npm run --", - "docker:test:unit": "docker compose run kuzzle_node_1 npm run test:unit", - "docker": "docker compose run kuzzle_node_1 ", - "file": "npx ergol docker/scripts/start-kuzzle-dev.ts -c ./config/ergol.config.json", "prepublishOnly": "npm run build", - "prettier": "npx prettier ./lib ./test ./bin ./features ./plugins/available/functional-test-plugin --write", - "services": "npx kourou app:start-services", - "start:dev": "npx ergol docker/scripts/start-kuzzle-dev.ts -c ./config/ergol.config.json --script-args=--enable-plugins functional-test-plugin", - "test:functional:http": "KUZZLE_PROTOCOL=http npx cucumber-js --profile http", + "prettier": "prettier ./lib ./test ./bin ./features ./plugins/available/functional-test-plugin --write", + "test:functional:http": "KUZZLE_PROTOCOL=http cucumber-js --profile http", "test:functional:jest": "jest", - "test:functional:legacy:http": "npx cucumber-js --format progress-bar --profile http ./features-legacy", - "test:functional:legacy:mqtt": "npx cucumber-js --format progress-bar --profile mqtt ./features-legacy", - "test:functional:legacy:websocket": "npx cucumber-js --format progress-bar --profile websocket ./features-legacy", + "test:functional:legacy:http": "cucumber-js --format progress-bar --profile http ./features-legacy", + "test:functional:legacy:mqtt": "cucumber-js --format progress-bar --profile mqtt ./features-legacy", + "test:functional:legacy:websocket": "cucumber-js --format progress-bar --profile websocket ./features-legacy", "test:functional:legacy": "npm run test:functional:legacy:http && npm run test:functional:legacy:websocket && npm run test:functional:legacy:mqtt", - "test:functional:websocket": "KUZZLE_PROTOCOL=websocket npx cucumber-js --profile websocket", + "test:functional:websocket": "KUZZLE_PROTOCOL=websocket cucumber-js --profile websocket", "test:functional": "npm run test:functional:http && npm run test:functional:websocket && npm run test:functional:jest", - "test:lint:js:fix": "eslint --max-warnings=0 --fix ./lib ./test ./bin ./features", - "test:lint:js": "eslint --max-warnings=0 ./lib ./test ./bin ./features ./plugins/available/functional-test-plugin", - "test:lint:ts:fix": "eslint --max-warnings=0 --fix ./lib --ext .ts --config .eslintc-ts.json", - "test:lint:ts": "eslint --max-warnings=0 ./lib --ext .ts --config .eslintc-ts.json", + "test:lint:js": "eslint ./lib ./test ./bin ./features ./plugins/available/functional-test-plugin", + "test:lint:ts": "eslint ./lib --ext .ts --config .eslintc-ts.json", "test:lint": "npm run test:lint:js && npm run test:lint:ts", - "test:unit:coverage": "DEBUG= nyc --reporter=text-summary --reporter=lcov mocha --exit", "test:unit": "DEBUG= npx --node-arg=--trace-warnings mocha --exit", "test": "npm run clean && npm run --silent test:lint && npm run build && npm run test:unit:coverage && npm run test:functional" }, @@ -52,8 +41,8 @@ "didyoumean": "1.2.2", "dumpme": "1.0.3", "eventemitter3": "4.0.7", - "inquirer": "9.1.4", - "ioredis": "5.3.0", + "inquirer": "9.2.12", + "ioredis": "5.3.2", "js-yaml": "4.1.0", "json-stable-stringify": "1.0.2", "json2yaml": "1.1.0", @@ -61,27 +50,27 @@ "koncorde": "4.3.0", "kuzzle-plugin-auth-passport-local": "6.4.0", "kuzzle-plugin-logger": "3.0.3", - "kuzzle-sdk": "7.11.0", + "kuzzle-sdk": "7.11.1", "kuzzle-vault": "2.0.4", "lodash": "4.17.21", - "long": "5.2.1", + "long": "5.2.3", "moment": "2.29.4", "ms": "2.1.3", "murmurhash-native": "3.5.0", "ndjson": "2.0.0", "node-segfault-handler": "1.4.2", "passport": "0.6.0", - "protobufjs": "~7.2.1", + "protobufjs": "7.2.5", "rc": "1.2.8", - "semver": "7.3.8", + "semver": "7.5.4", "sorted-array": "2.0.4", "uuid": "9.0.1", - "uWebSockets.js": "https://github.com/uNetworking/uWebSockets.js/archive/refs/tags/v20.32.0.tar.gz", + "uWebSockets.js": "https://github.com/uNetworking/uWebSockets.js/archive/refs/tags/v20.34.0.tar.gz", "validator": "13.11.0", - "winston": "3.10.0", + "winston": "3.11.0", "winston-elasticsearch": "0.17.4", "winston-syslog": "2.7.0", - "winston-transport": "4.5.0", + "winston-transport": "4.6.0", "yargs": "17.7.2", "zeromq": "6.0.0-beta.6" }, @@ -97,13 +86,13 @@ "async": "3.2.4", "chokidar": "3.5.3", "codecov": "3.8.3", + "mqtt": "4.3.7", "cucumber": "6.0.5", "ergol": "1.0.2", - "eslint-plugin-kuzzle": "0.0.6", + "eslint-plugin-kuzzle": "0.0.12", "jest": "29.7.0", "mocha": "10.2.0", "mock-require": "3.0.3", - "mqtt": "4.3.7", "nyc": "15.1.0", "request": "2.88.2", "request-promise": "4.2.6", @@ -112,7 +101,7 @@ "should-sinon": "0.0.6", "sinon": "14.0.2", "strip-json-comments": "https://github.com/sindresorhus/strip-json-comments/archive/refs/tags/v3.1.1.tar.gz", - "ts-jest": "29.0.5", + "ts-jest": "29.1.1", "ts-node": "10.9.1", "typescript": "4.9.5", "yaml": "2.2.1" diff --git a/plugins/available/functional-test-plugin/functionalTestPlugin.js b/plugins/available/functional-test-plugin/functionalTestPlugin.js index 506988b085..949e8b49b7 100644 --- a/plugins/available/functional-test-plugin/functionalTestPlugin.js +++ b/plugins/available/functional-test-plugin/functionalTestPlugin.js @@ -125,7 +125,7 @@ class FunctionalTestPlugin { this.genericDocumentEvent("afterDelete", ...args); this.pipes["plugin-functional-test-plugin:testPipesReturn"] = async ( - name + name, ) => `Hello, ${name}`; // Pipe declared with a function name ====================================== @@ -168,7 +168,7 @@ class FunctionalTestPlugin { await this.context.accessors.sdk.realtime.publish( "functional-test", "hooks", - { event: "server:afterNow" } + { event: "server:afterNow" }, ); }; } @@ -195,7 +195,7 @@ class FunctionalTestPlugin { equals: { name: "Luca", }, - } + }, ); return { @@ -213,7 +213,7 @@ class FunctionalTestPlugin { await this.context.accessors.subscription.unregister( connectionId, roomId, - false + false, ); return { @@ -258,7 +258,7 @@ class FunctionalTestPlugin { JSON.stringify({ payload, state, - }) + }), ); return null; @@ -278,7 +278,7 @@ class FunctionalTestPlugin { async genericDocumentEvent(event, documents) { const pipe = JSON.parse( - await this.sdk.ms.get(`plugin:pipes:generic:document:${event}`) + await this.sdk.ms.get(`plugin:pipes:generic:document:${event}`), ); if (!pipe || pipe.state === "off") { @@ -296,7 +296,7 @@ class FunctionalTestPlugin { async afterNowPipe(request) { const pipe = JSON.parse( - await this.sdk.ms.get("plugin:pipes:server:afterNow") + await this.sdk.ms.get("plugin:pipes:server:afterNow"), ); if (pipe && pipe.state !== "off") { @@ -317,7 +317,7 @@ class FunctionalTestPlugin { async () => { await this.sdk.realtime.publish("test", "answer", {}); await this.sdk.realtime.unsubscribe(roomId); - } + }, ); } @@ -328,7 +328,7 @@ class FunctionalTestPlugin { async pipesTestReturn(request) { const helloName = await this.context.accessors.trigger( "testPipesReturn", - request.input.args.name + request.input.args.name, ); return { result: helloName }; diff --git a/test/api/OpenApiManager.test.js b/test/api/OpenApiManager.test.js index dad5b00f28..ad033e0e4c 100644 --- a/test/api/OpenApiManager.test.js +++ b/test/api/OpenApiManager.test.js @@ -91,45 +91,45 @@ describe("OpenApiManager", () => { manager = new OpenApiManager( applicationOpenApi, kuzzleRoutes, - pluginsRoutes + pluginsRoutes, ); }); describe("#constructor", () => { it("should generate open API paths from kuzzle routes", () => { should(manager.kuzzleDefinition.paths).have.ownProperty( - "/nativeController/nativeAction" + "/nativeController/nativeAction", ); }); it("should generate open API paths from kuzzle routes", () => { should(manager.applicationDefinition.paths).have.ownProperty( - "/logistic-objects/patch" + "/logistic-objects/patch", ); }); it("should make sure that route verbs are lowercase only", () => { should(manager.kuzzleDefinition.paths).have.ownProperty( - "/nativeController/nativeAction" + "/nativeController/nativeAction", ); should( - manager.kuzzleDefinition.paths["/nativeController/nativeAction"] + manager.kuzzleDefinition.paths["/nativeController/nativeAction"], ).have.ownProperty("get"); }); it("should transform our :param path notation to {param}", () => { should(manager.kuzzleDefinition.paths).have.ownProperty( - "/{index}/{collection}/_exists" + "/{index}/{collection}/_exists", ); }); it("should extract parameters when required", () => { should(manager.kuzzleDefinition.paths).have.ownProperty( - "/{index}/{collection}/_exists" + "/{index}/{collection}/_exists", ); should( manager.kuzzleDefinition.paths["/{index}/{collection}/_exists"].get - .parameters + .parameters, ).match([ { name: "index", in: "path" }, { name: "collection", in: "path" }, diff --git a/test/api/controllers/adminController.test.js b/test/api/controllers/adminController.test.js index 0504126b81..208807d5d1 100644 --- a/test/api/controllers/adminController.test.js +++ b/test/api/controllers/adminController.test.js @@ -23,7 +23,7 @@ describe("AdminController", () => { before(() => { mockRequire("../../../lib/util/mutex", { Mutex: MutexMock }); AdminController = mockRequire.reRequire( - "../../../lib/api/controllers/adminController" + "../../../lib/api/controllers/adminController", ); }); @@ -81,7 +81,7 @@ describe("AdminController", () => { return should(adminController.resetCache(request)).rejectedWith( NotFoundError, - { id: "services.cache.database_not_found" } + { id: "services.cache.database_not_found" }, ); }); }); @@ -104,14 +104,14 @@ describe("AdminController", () => { should(kuzzle.internalIndex.createInitialSecurities).be.calledOnce(); should(kuzzle.ask).be.calledWith( "core:cache:internal:del", - `${BACKEND_IMPORT_KEY}:permissions` + `${BACKEND_IMPORT_KEY}:permissions`, ); sinon.assert.callOrder( userSpy, profileSpy, roleSpy, - kuzzle.internalIndex.createInitialSecurities + kuzzle.internalIndex.createInitialSecurities, ); const mutex = MutexMock.__getLastMutex(); @@ -154,7 +154,7 @@ describe("AdminController", () => { try { await should(adminController.resetSecurity(request)).rejectedWith( PreconditionError, - { id: "api.process.action_locked" } + { id: "api.process.action_locked" }, ); should(MutexMock.__getLastMutex().resource).eql("resetSecurity"); } finally { @@ -186,7 +186,7 @@ describe("AdminController", () => { should(kuzzle.ask).be.calledWith( "core:cache:internal:del", - `${BACKEND_IMPORT_KEY}:mappings` + `${BACKEND_IMPORT_KEY}:mappings`, ); const mutex = MutexMock.__getLastMutex(); @@ -203,7 +203,7 @@ describe("AdminController", () => { try { await should(adminController.resetDatabase(request)).rejectedWith( PreconditionError, - { id: "api.process.action_locked" } + { id: "api.process.action_locked" }, ); should(MutexMock.__getLastMutex().resource).eql("resetDatabase"); } finally { @@ -235,7 +235,7 @@ describe("AdminController", () => { await should(adminController.shutdown(request)).rejectedWith( PreconditionError, - { id: "api.process.action_locked" } + { id: "api.process.action_locked" }, ); }); @@ -257,7 +257,7 @@ describe("AdminController", () => { should(kuzzle.ask).be.calledWith( "core:storage:public:mappings:import", - request.input.body + request.input.body, ); }); }); @@ -275,7 +275,7 @@ describe("AdminController", () => { should(kuzzle.ask).be.calledWith( "core:storage:public:document:import", request.input.body, - { refresh: "false" } + { refresh: "false" }, ); }); }); @@ -300,7 +300,7 @@ describe("AdminController", () => { refresh: "wait_for", user: null, force: false, - } + }, ); }); }); diff --git a/test/api/controllers/authController.test.js b/test/api/controllers/authController.test.js index 0711172d3d..aff329b5f6 100644 --- a/test/api/controllers/authController.test.js +++ b/test/api/controllers/authController.test.js @@ -297,7 +297,7 @@ describe("Test the auth controller", () => { { id: "api.assert.missing_argument", message: 'Missing argument "strategy".', - } + }, ); }); @@ -327,7 +327,7 @@ describe("Test the auth controller", () => { should(createTokenStub).be.calledWith( "core:security:token:create", user, - { expiresIn: "1s" } + { expiresIn: "1s" }, ); }); @@ -344,7 +344,7 @@ describe("Test the auth controller", () => { BadRequestError, { id: "security.credentials.unknown_strategy", - } + }, ); }); }); @@ -381,7 +381,7 @@ describe("Test the auth controller", () => { should(requestcookieAuth.response.headers["Set-Cookie"]) .be.an.Array() .and.match( - /authToken=bar; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/ + /authToken=bar; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/, ); should(response).be.deepEqual({ @@ -422,7 +422,7 @@ describe("Test the auth controller", () => { should(requestcookieAuth.response.headers["Set-Cookie"]) .be.an.Array() .and.match( - /authToken=bar; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/ + /authToken=bar; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/, ); should(response).be.deepEqual({ @@ -461,7 +461,7 @@ describe("Test the auth controller", () => { should(requestcookieAuth.response.headers["Set-Cookie"]) .be.an.Array() .and.match( - /authToken=kapikey-foo; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/ + /authToken=kapikey-foo; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/, ); should(response).be.deepEqual({ @@ -500,7 +500,7 @@ describe("Test the auth controller", () => { should(requestcookieAuth.response.headers["Set-Cookie"]) .be.an.Array() .and.match( - /authToken=foo; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/ + /authToken=foo; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/, ); should(response).be.deepEqual({ @@ -567,7 +567,7 @@ describe("Test the auth controller", () => { { id: "api.assert.missing_argument", message: 'Missing argument "strategy".', - } + }, ); }); @@ -592,7 +592,7 @@ describe("Test the auth controller", () => { should(requestcookieAuth.response.headers["Set-Cookie"]) .be.an.Array() .and.match( - /authToken=bar; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/ + /authToken=bar; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/, ); should(response).be.deepEqual({ @@ -604,7 +604,7 @@ describe("Test the auth controller", () => { should(createTokenStub).be.calledWith( "core:security:token:create", user, - { expiresIn: "1s" } + { expiresIn: "1s" }, ); }); @@ -621,7 +621,7 @@ describe("Test the auth controller", () => { BadRequestError, { id: "security.credentials.unknown_strategy", - } + }, ); }); }); @@ -631,7 +631,7 @@ describe("Test the auth controller", () => { const signedToken = jwt.sign( { _id: "admin" }, kuzzle.config.security.jwt.secret, - { algorithm: kuzzle.config.security.jwt.algorithm } + { algorithm: kuzzle.config.security.jwt.algorithm }, ); const t = new Token({ _id: "foo#" + signedToken, @@ -649,7 +649,7 @@ describe("Test the auth controller", () => { connectionId: "papagaya", token: t, user: { _id: "foo" }, - } + }, ); }); @@ -658,7 +658,7 @@ describe("Test the auth controller", () => { should(kuzzle.ask).calledWith( "core:security:token:delete", - request.context.token + request.context.token, ); should(response.responseObject).be.instanceof(Object); @@ -687,7 +687,7 @@ describe("Test the auth controller", () => { return should(authController.logout(request)).rejectedWith( UnauthorizedError, - { id: "security.rights.unauthorized" } + { id: "security.rights.unauthorized" }, ); }); @@ -699,7 +699,7 @@ describe("Test the auth controller", () => { should(kuzzle.ask).not.be.calledWith( "core:security:token:delete", - request.context.token + request.context.token, ); }); }); @@ -711,7 +711,7 @@ describe("Test the auth controller", () => { const signedToken = jwt.sign( { _id: "admin" }, kuzzle.config.security.jwt.secret, - { algorithm: kuzzle.config.security.jwt.algorithm } + { algorithm: kuzzle.config.security.jwt.algorithm }, ); const t = new Token({ _id: "foo#" + signedToken, @@ -729,7 +729,7 @@ describe("Test the auth controller", () => { connectionId: "papagaya", token: t, user: { _id: "foo" }, - } + }, ); request.input.headers = { cookie: `authToken=${signedToken};` }; @@ -750,7 +750,7 @@ describe("Test the auth controller", () => { should(kuzzle.ask).calledWith( "core:security:token:delete", - request.context.token + request.context.token, ); should(response.responseObject).be.instanceof(Object); @@ -782,7 +782,7 @@ describe("Test the auth controller", () => { should(kuzzle.ask).not.be.calledWith( "core:security:token:delete", - request.context.token + request.context.token, ); should(response.responseObject).be.instanceof(Object); @@ -796,7 +796,7 @@ describe("Test the auth controller", () => { { token: { userId: "admin" }, user: { _id: "admin" }, - } + }, ); const response = await authController.getCurrentUser(req); @@ -807,16 +807,16 @@ describe("Test the auth controller", () => { it("should a PluginImplementationError if a plugin throws a non-KuzzleError error", () => { const req = new Request( { body: {} }, - { token: { userId: "admin" }, user: { _id: "admin" } } + { token: { userId: "admin" }, user: { _id: "admin" } }, ); kuzzle.pluginsManager.listStrategies.returns(["foo"]); kuzzle.pluginsManager.getStrategyMethod.returns(() => - Bluebird.reject(new Error("bar")) + Bluebird.reject(new Error("bar")), ); return should(authController.getCurrentUser(req)).be.rejectedWith( - PluginImplementationError + PluginImplementationError, ); }); }); @@ -831,7 +831,7 @@ describe("Test the auth controller", () => { controller: "auth", body: { token: "foobar" }, }, - {} + {}, ); testToken = new Token({ expiresAt: 42, userId: "durres" }); }); @@ -842,7 +842,7 @@ describe("Test the auth controller", () => { .resolves(new Token({ userId: "-1" })); const response = await authController.checkToken( - new Request({ body: {} }) + new Request({ body: {} }), ); await should(verifyStub).calledOnce(); @@ -904,7 +904,7 @@ describe("Test the auth controller", () => { body: {}, cookieAuth: true, }, - {} + {}, ); request.input.jwt = "foobar"; @@ -976,9 +976,9 @@ describe("Test the auth controller", () => { authController.refreshToken( new Request( {}, - { token: { userId: "anonymous", _id: "-1" }, user: { _id: "-1" } } - ) - ) + { token: { userId: "anonymous", _id: "-1" }, user: { _id: "-1" } }, + ), + ), ).rejectedWith(UnauthorizedError, { id: "security.rights.unauthorized" }); }); @@ -1002,7 +1002,7 @@ describe("Test the auth controller", () => { user: { _id: "user", }, - } + }, ); kuzzle.ask.withArgs("core:security:token:refresh").resolves(newToken); @@ -1020,7 +1020,7 @@ describe("Test the auth controller", () => { "core:security:token:refresh", req.context.user, req.context.token, - req.input.args.expiresIn + req.input.args.expiresIn, ); }); }); @@ -1036,9 +1036,9 @@ describe("Test the auth controller", () => { authController.refreshToken( new Request( { cookieAuth: true }, - { token: { userId: "anonymous", _id: "-1" }, user: { _id: "-1" } } - ) - ) + { token: { userId: "anonymous", _id: "-1" }, user: { _id: "-1" } }, + ), + ), ).rejectedWith(UnauthorizedError, { id: "security.rights.unauthorized" }); }); @@ -1065,7 +1065,7 @@ describe("Test the auth controller", () => { user: { _id: "user", }, - } + }, ); kuzzle.ask.withArgs("core:security:token:refresh").resolves(newToken); @@ -1083,14 +1083,14 @@ describe("Test the auth controller", () => { should(req.response.headers["Set-Cookie"]) .be.an.Array() .and.match( - /authToken=new-token; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/ + /authToken=new-token; Path=\/; Expires=[^;]+; HttpOnly; SameSite=Strict/, ); should(kuzzle.ask).calledWith( "core:security:token:refresh", req.context.user, req.context.token, - req.input.args.expiresIn + req.input.args.expiresIn, ); }); }); @@ -1102,7 +1102,7 @@ describe("Test the auth controller", () => { { token: { userId: "admin", _id: "admin" }, user: { _id: "admin" }, - } + }, ); kuzzle.ask.resolves(user); @@ -1119,14 +1119,14 @@ describe("Test the auth controller", () => { refresh: "wait_for", retryOnConflict: 10, userId: r.context.user._id, - } + }, ); }); it("should reject an error if profile is specified", () => { const r = new Request( { body: { foo: "bar", profileIds: ["test"] } }, - { token: { userId: "admin", _id: "admin" }, user: { _id: "admin" } } + { token: { userId: "admin", _id: "admin" }, user: { _id: "admin" } }, ); return should(authController.updateSelf(r)).rejectedWith( @@ -1135,14 +1135,14 @@ describe("Test the auth controller", () => { id: "api.assert.forbidden_argument", message: 'The argument "body.profileIds" is not allowed by this API action.', - } + }, ); }); it("should reject an error if _id is specified in the body", () => { const r = new Request( { body: { foo: "bar", _id: "test" } }, - { token: { userId: "admin", _id: "admin" }, user: { _id: "admin" } } + { token: { userId: "admin", _id: "admin" }, user: { _id: "admin" } }, ); return should(authController.updateSelf(r)).rejectedWith( @@ -1150,19 +1150,19 @@ describe("Test the auth controller", () => { { id: "api.assert.forbidden_argument", message: 'The argument "body._id" is not allowed by this API action.', - } + }, ); }); it("should reject an error if current user is anonymous", () => { const r = new Request( { body: { foo: "bar" } }, - { token: { userId: "-1" }, user: { _id: "-1" } } + { token: { userId: "-1" }, user: { _id: "-1" } }, ); return should(authController.updateSelf(r)).rejectedWith( UnauthorizedError, - { id: "security.rights.unauthorized" } + { id: "security.rights.unauthorized" }, ); }); }); @@ -1193,7 +1193,7 @@ describe("Test the auth controller", () => { }); }, }, - } + }, ); it("should be able to get current user's rights", () => { @@ -1257,7 +1257,7 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.getStrategyMethod.returns(methodStub); @@ -1266,16 +1266,16 @@ describe("Test the auth controller", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.getStrategyMethod).be.calledTwice(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("create"); should( - kuzzle.pluginsManager.getStrategyMethod.secondCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.secondCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.secondCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.secondCall.args[1], ).be.eql("validate"); should(methodStub).be.calledTwice(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -1307,16 +1307,16 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.getStrategyMethod.returns(() => - Bluebird.reject(new Error("foo")) + Bluebird.reject(new Error("foo")), ); return should( - authController.createMyCredentials(request) + authController.createMyCredentials(request), ).be.rejectedWith(PluginImplementationError); }); }); @@ -1339,7 +1339,7 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.getStrategyMethod.returns(methodStub); @@ -1348,16 +1348,16 @@ describe("Test the auth controller", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.getStrategyMethod).be.calledTwice(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("update"); should( - kuzzle.pluginsManager.getStrategyMethod.secondCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.secondCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.secondCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.secondCall.args[1], ).be.eql("validate"); should(methodStub).be.calledTwice(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -1389,15 +1389,15 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.getStrategyMethod.returns(() => - Bluebird.reject(new Error("foo")) + Bluebird.reject(new Error("foo")), ); return should( - authController.updateMyCredentials(request) + authController.updateMyCredentials(request), ).be.rejectedWith(PluginImplementationError); }); }); @@ -1417,7 +1417,7 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies = sinon .stub() @@ -1430,10 +1430,10 @@ describe("Test the auth controller", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("exists"); should(methodStub).be.calledOnce(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -1453,15 +1453,15 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.getStrategyMethod.returns(() => - Bluebird.reject(new Error("foo")) + Bluebird.reject(new Error("foo")), ); return should(authController.credentialsExist(request)).be.rejectedWith( - PluginImplementationError + PluginImplementationError, ); }); }); @@ -1484,7 +1484,7 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.getStrategyMethod.returns(methodStub); @@ -1493,10 +1493,10 @@ describe("Test the auth controller", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("validate"); should(methodStub).be.calledOnce(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -1522,16 +1522,16 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.getStrategyMethod.returns(() => - Bluebird.reject(new Error("foo")) + Bluebird.reject(new Error("foo")), ); return should( - authController.validateMyCredentials(request) + authController.validateMyCredentials(request), ).be.rejectedWith(PluginImplementationError); }); }); @@ -1551,7 +1551,7 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.getStrategyMethod.returns(methodStub); @@ -1560,10 +1560,10 @@ describe("Test the auth controller", () => { should(result).be.deepEqual({ acknowledged: true }); should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("delete"); should(methodStub).be.calledOnce(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -1583,16 +1583,16 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.getStrategyMethod.returns(() => - Bluebird.reject(new Error("foo")) + Bluebird.reject(new Error("foo")), ); return should( - authController.deleteMyCredentials(request) + authController.deleteMyCredentials(request), ).be.rejectedWith(PluginImplementationError); }); }); @@ -1612,7 +1612,7 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.hasStrategyMethod.returns(true); @@ -1622,17 +1622,17 @@ describe("Test the auth controller", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.hasStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1], ).be.eql("getInfo"); should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("getInfo"); should(methodStub).be.calledOnce(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -1655,7 +1655,7 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.hasStrategyMethod.returns(false); @@ -1665,10 +1665,10 @@ describe("Test the auth controller", () => { should(result).be.deepEqual({}); should(kuzzle.pluginsManager.hasStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1], ).be.eql("getInfo"); should(kuzzle.pluginsManager.getStrategyMethod.callCount).be.eql(0); }); @@ -1685,17 +1685,17 @@ describe("Test the auth controller", () => { user: { _id: "someUserId", }, - } + }, ); kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]); kuzzle.pluginsManager.hasStrategyMethod.returns(true); kuzzle.pluginsManager.getStrategyMethod.returns(() => - Bluebird.reject(new Error("foo")) + Bluebird.reject(new Error("foo")), ); return should(authController.getMyCredentials(request)).be.rejectedWith( - PluginImplementationError + PluginImplementationError, ); }); }); diff --git a/test/api/controllers/baseController.test.js b/test/api/controllers/baseController.test.js index bce9c71f51..5e0b68ceff 100644 --- a/test/api/controllers/baseController.test.js +++ b/test/api/controllers/baseController.test.js @@ -62,7 +62,7 @@ describe("#base/native controller", () => { koncordeFilters = "not an object"; return should( - nativeController.translateKoncorde(koncordeFilters) + nativeController.translateKoncorde(koncordeFilters), ).rejectedWith(BadRequestError, { id: "api.assert.invalid_type" }); }); @@ -73,7 +73,7 @@ describe("#base/native controller", () => { kuzzle.ask.withArgs("core:storage:public:translate").rejects(error); return should( - nativeController.translateKoncorde(koncordeFilters) + nativeController.translateKoncorde(koncordeFilters), ).rejectedWith(BadRequestError, { id: "api.assert.koncorde_restricted_keyword", }); @@ -93,7 +93,7 @@ describe("#base/native controller", () => { should( (async () => { nativeController.assertTargetsAreValid([{ collections: "foo" }]); - })() + })(), ).rejectedWith(BadRequestError, { id: "api.assert.missing_argument" }); }); @@ -101,7 +101,7 @@ describe("#base/native controller", () => { should( (async () => { nativeController.assertTargetsAreValid([{ index: "index" }]); - })() + })(), ).rejectedWith(BadRequestError, { id: "api.assert.missing_argument" }); }); @@ -111,7 +111,7 @@ describe("#base/native controller", () => { nativeController.assertTargetsAreValid([ { index: "index", collections: [] }, ]); - })() + })(), ).rejectedWith(BadRequestError, { id: "api.assert.empty_argument" }); }); @@ -120,9 +120,9 @@ describe("#base/native controller", () => { (async () => { nativeController.assertTargetsAreValid( [{ index: "index", collections: [] }], - { emptyCollectionsAllowed: true } + { emptyCollectionsAllowed: true }, ); - })() + })(), ).not.be.rejectedWith(BadRequestError, { id: "api.assert.empty_argument", }); @@ -134,7 +134,7 @@ describe("#base/native controller", () => { nativeController.assertTargetsAreValid([{ index: "index" }], { emptyCollectionsAllowed: true, }); - })() + })(), ).not.be.rejectedWith(BadRequestError, { id: "api.assert.missing_argument", }); @@ -146,7 +146,7 @@ describe("#base/native controller", () => { nativeController.assertTargetsAreValid([ { index: "index", collections: "" }, ]); - })() + })(), ).rejectedWith(BadRequestError, { id: "api.assert.invalid_type" }); }); @@ -156,7 +156,7 @@ describe("#base/native controller", () => { nativeController.assertTargetsAreValid([ { index: "index", collections: [42] }, ]); - })() + })(), ).rejectedWith(BadRequestError, { id: "api.assert.invalid_type" }); }); @@ -166,7 +166,7 @@ describe("#base/native controller", () => { nativeController.assertTargetsAreValid([ { index: "index", collections: ["a,b"] }, ]); - })() + })(), ).rejectedWith({ id: "services.storage.invalid_target_format" }); }); @@ -176,7 +176,7 @@ describe("#base/native controller", () => { nativeController.assertTargetsAreValid([ { index: "index,bar", collections: ["foo"] }, ]); - })() + })(), ).rejectedWith({ id: "services.storage.invalid_target_format" }); }); }); diff --git a/test/api/controllers/bulkController.test.js b/test/api/controllers/bulkController.test.js index 2aaaaa7d91..71afcc3783 100644 --- a/test/api/controllers/bulkController.test.js +++ b/test/api/controllers/bulkController.test.js @@ -70,7 +70,7 @@ describe("Test the bulk controller", () => { index, collection, bulkData, - { refresh: "false", userId: null } + { refresh: "false", userId: null }, ); should(response).match({ @@ -133,7 +133,7 @@ describe("Test the bulk controller", () => { "core:realtime:document:notify", sinon.match.object, sinon.match.number, - sinon.match.object + sinon.match.object, ); }); @@ -147,7 +147,7 @@ describe("Test the bulk controller", () => { collection, _id, _source, - { refresh: "false", injectKuzzleMeta: false } + { refresh: "false", injectKuzzleMeta: false }, ); should(response).match({ @@ -176,7 +176,7 @@ describe("Test the bulk controller", () => { "core:realtime:document:notify", request, actionEnum.WRITE, - { _id, _source } + { _id, _source }, ); }); }); @@ -226,7 +226,7 @@ describe("Test the bulk controller", () => { "core:realtime:document:mNotify", sinon.match.object, sinon.match.number, - sinon.match.every(sinon.match.object) + sinon.match.every(sinon.match.object), ); }); @@ -239,7 +239,7 @@ describe("Test the bulk controller", () => { index, collection, documents, - { refresh: "false", limits: false, injectKuzzleMeta: false } + { refresh: "false", limits: false, injectKuzzleMeta: false }, ); should(response).match({ @@ -260,7 +260,7 @@ describe("Test the bulk controller", () => { "core:realtime:document:mNotify", request, actionEnum.WRITE, - mCreateOrReplaceResult + mCreateOrReplaceResult, ); }); @@ -306,7 +306,7 @@ describe("Test the bulk controller", () => { index, collection, query, - { refresh: "wait_for", fetch: false, size: -1 } + { refresh: "wait_for", fetch: false, size: -1 }, ); should(response.deleted).be.eql(2); @@ -348,7 +348,7 @@ describe("Test the bulk controller", () => { collection, query, changes, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(response).be.eql(esResponse); }); @@ -362,7 +362,7 @@ describe("Test the bulk controller", () => { collection, query, changes, - { refresh: "false" } + { refresh: "false" }, ); }); @@ -374,7 +374,7 @@ describe("Test the bulk controller", () => { { id: "api.assert.invalid_type", message: 'Wrong type for argument "body.query" (expected: object)', - } + }, ); }); @@ -386,7 +386,7 @@ describe("Test the bulk controller", () => { { id: "api.assert.missing_argument", message: 'Missing argument "body.changes".', - } + }, ); }); }); diff --git a/test/api/controllers/collectionController.test.js b/test/api/controllers/collectionController.test.js index 4af25faada..31fdb912d5 100644 --- a/test/api/controllers/collectionController.test.js +++ b/test/api/controllers/collectionController.test.js @@ -45,7 +45,7 @@ describe("Test: collection controller", () => { it("should throw a BadRequestError if the body is missing", () => { return should(collectionController.updateMapping(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); }); @@ -67,7 +67,7 @@ describe("Test: collection controller", () => { "core:storage:public:mappings:update", index, collection, - mappings + mappings, ); should(response).match({ @@ -96,7 +96,7 @@ describe("Test: collection controller", () => { "core:storage:public:mappings:get", index, collection, - { includeKuzzleMeta: false } + { includeKuzzleMeta: false }, ); should(response).match(mappings); @@ -120,7 +120,7 @@ describe("Test: collection controller", () => { "core:storage:public:mappings:get", index, collection, - { includeKuzzleMeta: true } + { includeKuzzleMeta: true }, ); }); }); @@ -132,7 +132,7 @@ describe("Test: collection controller", () => { should(kuzzle.ask).be.calledWith( "core:storage:public:collection:truncate", index, - collection + collection, ); should(response).match({ @@ -155,7 +155,7 @@ describe("Test: collection controller", () => { "core:storage:private:document:get", kuzzle.internalIndex.index, "validations", - `${index}#${collection}` + `${index}#${collection}`, ); should(response).match({ @@ -169,7 +169,7 @@ describe("Test: collection controller", () => { .rejects(new NotFoundError("not found")); return should( - collectionController.getSpecifications(request) + collectionController.getSpecifications(request), ).be.rejectedWith(NotFoundError, { id: "validation.assert.not_found" }); }); }); @@ -181,7 +181,7 @@ describe("Test: collection controller", () => { request.input.args.size = 20; return should( - collectionController.searchSpecifications(request) + collectionController.searchSpecifications(request), ).rejectedWith(SizeLimitError, { id: "services.storage.get_limit_exceeded", }); @@ -216,7 +216,7 @@ describe("Test: collection controller", () => { from: request.input.args.from, size: request.input.args.size, scroll: request.input.args.scroll, - } + }, ); should(response).match({ @@ -235,7 +235,7 @@ describe("Test: collection controller", () => { }); return should( - collectionController.scrollSpecifications(request) + collectionController.scrollSpecifications(request), ).rejectedWith(BadRequestError, { id: "api.assert.missing_argument" }); }); @@ -253,7 +253,7 @@ describe("Test: collection controller", () => { should(kuzzle.ask).be.calledWithMatch( "core:storage:private:document:scroll", "foobar", - collectionController.defaultScrollTTL + collectionController.defaultScrollTTL, ); should(response).match({ @@ -277,7 +277,7 @@ describe("Test: collection controller", () => { should(kuzzle.ask).be.calledWithMatch( "core:storage:private:document:scroll", "foobar", - "qux" + "qux", ); should(response).match({ @@ -308,7 +308,7 @@ describe("Test: collection controller", () => { should(kuzzle.ask).be.calledWith( "core:storage:private:collection:refresh", kuzzle.internalIndex.index, - "validations" + "validations", ); should(kuzzle.validation.curateSpecification).be.called(); @@ -322,7 +322,7 @@ describe("Test: collection controller", () => { index, collection, validation: request.input.body, - } + }, ); should(response).match(request.input.body); @@ -345,7 +345,7 @@ describe("Test: collection controller", () => { }); await should( - collectionController.updateSpecifications(request) + collectionController.updateSpecifications(request), ).be.rejectedWith(BadRequestError, { id: "validation.assert.invalid_specifications", }); @@ -372,15 +372,14 @@ describe("Test: collection controller", () => { it("should call the right functions and respond with the right response", async () => { kuzzle.validation.validateFormat.resolves({ isValid: true }); - const response = await collectionController.validateSpecifications( - request - ); + const response = + await collectionController.validateSpecifications(request); should(kuzzle.validation.validateFormat).be.calledWith( index, collection, request.input.body, - true + true, ); should(response).match({ valid: true, @@ -393,9 +392,8 @@ describe("Test: collection controller", () => { errors: "errors", }); - const response = await collectionController.validateSpecifications( - request - ); + const response = + await collectionController.validateSpecifications(request); should(response).match({ valid: false, @@ -413,13 +411,13 @@ describe("Test: collection controller", () => { "core:storage:private:document:delete", kuzzle.internalIndex.index, "validations", - `${index}#${collection}` + `${index}#${collection}`, ); should(kuzzle.ask).be.calledWith( "core:storage:private:collection:refresh", kuzzle.internalIndex.index, - "validations" + "validations", ); should(kuzzle.validation.curateSpecification).be.calledOnce(); @@ -448,12 +446,12 @@ describe("Test: collection controller", () => { should(kuzzle.ask).calledWith( "core:realtime:collections:get", - request.input.args.index + request.input.args.index, ); should(kuzzle.ask).calledWith( "core:storage:public:collection:list", - index + index, ); should(response.type).be.exactly("all"); @@ -471,7 +469,7 @@ describe("Test: collection controller", () => { return should(collectionController.list(request)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); }); @@ -496,11 +494,11 @@ describe("Test: collection controller", () => { should(realtimeListCollectionsStub).calledWith( "core:realtime:collections:get", - "index" + "index", ); should( - kuzzle.ask.withArgs("core:storage:public:collection:list") + kuzzle.ask.withArgs("core:storage:public:collection:list"), ).not.be.called(); }); @@ -530,7 +528,7 @@ describe("Test: collection controller", () => { should(response.type).be.exactly("all"); should(realtimeListCollectionsStub).calledWith( "core:realtime:collections:get", - "index" + "index", ); should(kuzzle.ask).calledWith("core:storage:public:collection:list"); }); @@ -560,7 +558,7 @@ describe("Test: collection controller", () => { should(response).be.instanceof(Object); should(realtimeListCollectionsStub).calledWith( "core:realtime:collections:get", - "index" + "index", ); should(kuzzle.ask).be.calledWith("core:storage:public:collection:list"); }); @@ -590,7 +588,7 @@ describe("Test: collection controller", () => { should(response.type).be.exactly("all"); should(realtimeListCollectionsStub).calledWithMatch( "core:realtime:collections:get", - "index" + "index", ); should(kuzzle.ask).be.calledWith("core:storage:public:collection:list"); }); @@ -626,7 +624,7 @@ describe("Test: collection controller", () => { should(kuzzle.ask).calledWith( "core:storage:public:collection:exist", request.input.args.index, - request.input.args.collection + request.input.args.collection, ); }); }); @@ -639,7 +637,7 @@ describe("Test: collection controller", () => { should(kuzzle.ask).be.calledWith( "core:storage:public:collection:refresh", index, - collection + collection, ); }); }); @@ -651,7 +649,7 @@ describe("Test: collection controller", () => { should(kuzzle.ask).be.calledWith( "core:storage:public:collection:create", index, - collection + collection, ); should(response).be.instanceof(Object); @@ -668,7 +666,7 @@ describe("Test: collection controller", () => { should(kuzzle.ask).be.calledWith( "core:storage:public:collection:delete", index, - collection + collection, ); should(response).be.null(); diff --git a/test/api/controllers/debugController.test.js b/test/api/controllers/debugController.test.js index 3965600527..5c1b745e51 100644 --- a/test/api/controllers/debugController.test.js +++ b/test/api/controllers/debugController.test.js @@ -49,7 +49,7 @@ describe("Test: debug controller", () => { await should(kuzzle.ask).be.calledWith( "core:debugger:post", - "Debugger.enable" + "Debugger.enable", ); }); }); @@ -65,7 +65,7 @@ describe("Test: debug controller", () => { request.context.connection.protocol = "http"; await should(debugController.addListener(request)).be.rejectedWith( InternalError, - { id: "api.assert.unsupported_protocol" } + { id: "api.assert.unsupported_protocol" }, ); }); @@ -79,7 +79,7 @@ describe("Test: debug controller", () => { await should(kuzzle.ask).be.calledWith( "core:debugger:addListener", "EventMock.event_foo", - "foobar" + "foobar", ); }); }); @@ -95,7 +95,7 @@ describe("Test: debug controller", () => { request.context.connection.protocol = "http"; await should(debugController.removeListener(request)).be.rejectedWith( InternalError, - { id: "api.assert.unsupported_protocol" } + { id: "api.assert.unsupported_protocol" }, ); }); @@ -109,7 +109,7 @@ describe("Test: debug controller", () => { await should(kuzzle.ask).be.calledWith( "core:debugger:removeListener", "EventMock.event_foo", - "foobar" + "foobar", ); }); }); diff --git a/test/api/controllers/documentController.test.js b/test/api/controllers/documentController.test.js index 0598d0822b..a1b7fb5613 100644 --- a/test/api/controllers/documentController.test.js +++ b/test/api/controllers/documentController.test.js @@ -66,7 +66,7 @@ describe("DocumentController", () => { index, collection, { query: { bar: "bar " } }, - { from: 1, size: 3, scroll: "10s" } + { from: 1, size: 3, scroll: "10s" }, ); should(response).match({ @@ -84,7 +84,7 @@ describe("DocumentController", () => { return should(documentController.search(request)).rejectedWith( BadRequestError, - { id: "services.storage.invalid_multi_index_collection_usage" } + { id: "services.storage.invalid_multi_index_collection_usage" }, ); }); @@ -95,7 +95,7 @@ describe("DocumentController", () => { return should(documentController.search(request)).rejectedWith( BadRequestError, - { id: "services.storage.invalid_multi_index_collection_usage" } + { id: "services.storage.invalid_multi_index_collection_usage" }, ); }); @@ -107,7 +107,7 @@ describe("DocumentController", () => { await should(documentController.search(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -122,7 +122,7 @@ describe("DocumentController", () => { { id: "api.assert.missing_argument", message: 'Missing argument "index".', - } + }, ); }); @@ -137,7 +137,7 @@ describe("DocumentController", () => { { id: "api.assert.missing_argument", message: 'Missing argument "collection".', - } + }, ); }); @@ -177,7 +177,7 @@ describe("DocumentController", () => { await documentController.search(request); return should(kuzzle.ask).be.calledWith( "core:storage:public:document:multiSearch", - [{ index: "foo", collections: ["bar"] }] + [{ index: "foo", collections: ["bar"] }], ); }); @@ -188,7 +188,7 @@ describe("DocumentController", () => { return should(documentController.search(request)).rejectedWith( SizeLimitError, - { id: "services.storage.get_limit_exceeded" } + { id: "services.storage.get_limit_exceeded" }, ); }); @@ -205,7 +205,7 @@ describe("DocumentController", () => { return should(documentController.search(request)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); }); @@ -215,7 +215,7 @@ describe("DocumentController", () => { return should(documentController.search(request)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); }); @@ -250,7 +250,7 @@ describe("DocumentController", () => { should(kuzzle.ask).be.calledWith( "core:storage:public:document:scroll", "SomeScrollIdentifier", - { scrollTTL: "1m" } + { scrollTTL: "1m" }, ); should(response).match({ @@ -270,7 +270,7 @@ describe("DocumentController", () => { .rejects(new Error("foobar")); return should(documentController.scroll(request)).be.rejectedWith( - "foobar" + "foobar", ); }); }); @@ -286,7 +286,7 @@ describe("DocumentController", () => { "core:storage:public:document:exist", index, collection, - "foo" + "foo", ); should(response).be.True(); @@ -315,7 +315,7 @@ describe("DocumentController", () => { "core:storage:public:document:mExists", index, collection, - ["id", "id2"] + ["id", "id2"], ); should(response).match({ @@ -332,7 +332,7 @@ describe("DocumentController", () => { should(documentController.mExists(request)).be.rejectedWith( SizeLimitError, - { id: "services.storage.get_limit_exceeded" } + { id: "services.storage.get_limit_exceeded" }, ); }); @@ -360,7 +360,7 @@ describe("DocumentController", () => { return should(documentController.mExists(request)).be.rejectedWith( MultipleErrorsError, - { id: "api.process.incomplete_multiple_request" } + { id: "api.process.incomplete_multiple_request" }, ); }); }); @@ -382,7 +382,7 @@ describe("DocumentController", () => { "core:storage:public:document:get", index, collection, - "foo" + "foo", ); should(response).be.eql({ @@ -415,7 +415,7 @@ describe("DocumentController", () => { "core:storage:public:document:mGet", index, collection, - ["id", "id2"] + ["id", "id2"], ); should(response).match({ @@ -459,7 +459,7 @@ describe("DocumentController", () => { return should(documentController.mGet(request)).be.rejectedWith( MultipleErrorsError, - { id: "api.process.incomplete_multiple_request" } + { id: "api.process.incomplete_multiple_request" }, ); }); }); @@ -475,7 +475,7 @@ describe("DocumentController", () => { "core:storage:public:document:count", index, collection, - { query: {} } + { query: {} }, ); should(response).be.eql({ count: 42 }); @@ -505,7 +505,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -526,7 +526,7 @@ describe("DocumentController", () => { injectKuzzleMeta: false, userId: "aschen", refresh: "wait_for", - } + }, ); should(kuzzle.validation.validate).be.calledWith(request, false); @@ -535,7 +535,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); should(response).match({ @@ -553,7 +553,7 @@ describe("DocumentController", () => { index, collection, content, - { id: null, injectKuzzleMeta: false, userId: null, refresh: "false" } + { id: null, injectKuzzleMeta: false, userId: null, refresh: "false" }, ); }); }); @@ -620,7 +620,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -631,7 +631,7 @@ describe("DocumentController", () => { const response = await documentController._mChanges( request, "mCreate", - actionEnum.CREATE + actionEnum.CREATE, ); should(kuzzle.ask).be.calledWith( @@ -644,14 +644,14 @@ describe("DocumentController", () => { userId: "aschen", refresh: "wait_for", retryOnConflict: undefined, - } + }, ); should(kuzzle.ask).be.calledWith( "core:realtime:document:mNotify", request, actionEnum.CREATE, - items + items, ); should(response).match({ @@ -673,7 +673,7 @@ describe("DocumentController", () => { userId: null, refresh: "false", retryOnConflict: undefined, - } + }, ); }); @@ -692,7 +692,7 @@ describe("DocumentController", () => { const response = await documentController._mChanges( request, "mCreate", - actionEnum.CREATE + actionEnum.CREATE, ); should(response).match({ @@ -714,7 +714,7 @@ describe("DocumentController", () => { ]; return should( - documentController._mChanges(request, "mCreate", actionEnum.CREATE) + documentController._mChanges(request, "mCreate", actionEnum.CREATE), ).be.rejectedWith({ id: "api.assert.unexpected_argument" }); }); @@ -722,7 +722,7 @@ describe("DocumentController", () => { kuzzle.config.limits.documentsWriteCount = 1; return should( - documentController._mChanges(request, "foobar", actionEnum.CREATE) + documentController._mChanges(request, "foobar", actionEnum.CREATE), ).rejectedWith(SizeLimitError, { id: "services.storage.write_limit_exceeded", }); @@ -734,7 +734,7 @@ describe("DocumentController", () => { const response = await documentController._mChanges( request, "mCreate", - actionEnum.CREATE + actionEnum.CREATE, ); should(response).match({ @@ -743,10 +743,10 @@ describe("DocumentController", () => { }); should( - kuzzle.ask.withArgs("core:storage:public:document:mCreate") + kuzzle.ask.withArgs("core:storage:public:document:mCreate"), ).not.called(); should( - kuzzle.ask.withArgs("core:realtime:document:mNotify") + kuzzle.ask.withArgs("core:realtime:document:mNotify"), ).not.called(); }); @@ -765,7 +765,7 @@ describe("DocumentController", () => { }); return should( - documentController._mChanges(request, "mCreate", actionEnum.CREATE) + documentController._mChanges(request, "mCreate", actionEnum.CREATE), ).rejectedWith(MultipleErrorsError, { id: "api.process.incomplete_multiple_request", }); @@ -781,7 +781,7 @@ describe("DocumentController", () => { index, collection, documents, - { source: true, userId: null, refresh: "false", retryOnConflict: 2 } + { source: true, userId: null, refresh: "false", retryOnConflict: 2 }, ); }); @@ -795,7 +795,7 @@ describe("DocumentController", () => { index, collection, documents, - { source: true, userId: null, refresh: "false", retryOnConflict: 2 } + { source: true, userId: null, refresh: "false", retryOnConflict: 2 }, ); }); @@ -814,7 +814,7 @@ describe("DocumentController", () => { userId: null, refresh: "false", retryOnConflict: undefined, - } + }, ); }); @@ -833,7 +833,7 @@ describe("DocumentController", () => { "core:realtime:document:mNotify", request, actionEnum.UPDATE, - items + items, ); }); @@ -896,7 +896,7 @@ describe("DocumentController", () => { "core:realtime:document:mNotify", request, actionEnum.UPSERT, - updatedItems + updatedItems, ); }); }); @@ -949,7 +949,7 @@ describe("DocumentController", () => { refresh: "false", retryOnConflict: undefined, userId: null, - } + }, ) .resolves({ items, @@ -967,7 +967,7 @@ describe("DocumentController", () => { refresh: "false", retryOnConflict: undefined, userId: null, - } + }, ) .resolves({ items: items.map((item) => { @@ -984,7 +984,7 @@ describe("DocumentController", () => { await documentController._mChanges( request, "mCreateOrReplace", - actionEnum.WRITE + actionEnum.WRITE, ); should(kuzzle.ask).be.calledWith( @@ -997,7 +997,7 @@ describe("DocumentController", () => { refresh: "false", retryOnConflict: undefined, userId: null, - } + }, ); }); @@ -1008,7 +1008,7 @@ describe("DocumentController", () => { const response = await documentController._mChanges( request, "mCreateOrReplace", - actionEnum.WRITE + actionEnum.WRITE, ); should(kuzzle.ask).be.calledWith( @@ -1021,7 +1021,7 @@ describe("DocumentController", () => { refresh: "false", retryOnConflict: undefined, userId: null, - } + }, ); for (const item of response.successes) { @@ -1036,7 +1036,7 @@ describe("DocumentController", () => { await documentController._mChanges( request, "mCreateOrReplace", - actionEnum.WRITE + actionEnum.WRITE, ); should(kuzzle.ask).be.calledWith( @@ -1049,7 +1049,7 @@ describe("DocumentController", () => { refresh: "false", retryOnConflict: undefined, userId: null, - } + }, ); }); }); @@ -1085,7 +1085,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -1101,7 +1101,7 @@ describe("DocumentController", () => { collection, "foobar", content, - { injectKuzzleMeta: false, userId: "aschen", refresh: "wait_for" } + { injectKuzzleMeta: false, userId: "aschen", refresh: "wait_for" }, ); should(kuzzle.validation.validate).be.calledWith(request, false); @@ -1110,7 +1110,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.WRITE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); should(response).match({ @@ -1130,7 +1130,7 @@ describe("DocumentController", () => { collection, "foobar", content, - { injectKuzzleMeta: false, userId: null, refresh: "false" } + { injectKuzzleMeta: false, userId: null, refresh: "false" }, ); }); }); @@ -1163,7 +1163,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -1185,7 +1185,7 @@ describe("DocumentController", () => { userId: "aschen", refresh: "wait_for", retryOnConflict: 42, - } + }, ); should(kuzzle.validation.validate).be.calledWith(request, false); @@ -1198,7 +1198,7 @@ describe("DocumentController", () => { _id: "_id", _source: content, _updatedFields: ["foo"], - } + }, ); should(response).match({ @@ -1222,7 +1222,7 @@ describe("DocumentController", () => { userId: null, refresh: "false", retryOnConflict: undefined, - } + }, ); }); @@ -1266,7 +1266,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -1289,7 +1289,7 @@ describe("DocumentController", () => { refresh: "wait_for", retryOnConflict: 42, userId: "aschen", - } + }, ); should(kuzzle.ask).be.calledWithMatch( @@ -1300,7 +1300,7 @@ describe("DocumentController", () => { _id: "_id", _source: { ...changes, name: "gordon" }, _updatedFields: ["foo"], - } + }, ); should(response).match({ @@ -1336,14 +1336,14 @@ describe("DocumentController", () => { refresh: "wait_for", retryOnConflict: 42, userId: "aschen", - } + }, ); should(kuzzle.ask).be.calledWithMatch( "core:realtime:document:notify", request, actionEnum.CREATE, - { ...defaultValues, ...changes, name: "gordon" } + { ...defaultValues, ...changes, name: "gordon" }, ); should(response).match({ @@ -1370,7 +1370,7 @@ describe("DocumentController", () => { refresh: "false", retryOnConflict: undefined, userId: null, - } + }, ); }); @@ -1422,7 +1422,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -1447,7 +1447,7 @@ describe("DocumentController", () => { collection, { match: { foo: "bar" } }, { bar: "foo" }, - { refresh: "wait_for", userId: "aschen" } + { refresh: "wait_for", userId: "aschen" }, ); should(kuzzle.ask).be.calledWith( @@ -1458,7 +1458,7 @@ describe("DocumentController", () => { _id: doc._id, _source: doc._source, _updatedFields: ["bar"], - })) + })), ); should(response).be.eql(esResponse); @@ -1484,7 +1484,7 @@ describe("DocumentController", () => { collection, { match: { foo: "bar" } }, { bar: "foo" }, - { refresh: "wait_for", userId: null } + { refresh: "wait_for", userId: null }, ); should(kuzzle.ask).calledWith( @@ -1495,7 +1495,7 @@ describe("DocumentController", () => { _id: doc._id, _source: { foo: "bar", bar: "foo" }, _updatedFields: ["bar"], - })) + })), ); should(response).be.eql(esResponse); @@ -1518,7 +1518,7 @@ describe("DocumentController", () => { { id: "api.assert.missing_argument", message: /^Missing argument "body.query"/, - } + }, ); }); @@ -1539,7 +1539,7 @@ describe("DocumentController", () => { { id: "api.assert.missing_argument", message: /^Missing argument "body.changes"/, - } + }, ); }); @@ -1552,7 +1552,7 @@ describe("DocumentController", () => { return should(documentController.updateByQuery(request)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); }); @@ -1600,7 +1600,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -1616,7 +1616,7 @@ describe("DocumentController", () => { collection, "foobar", content, - { injectKuzzleMeta: false, userId: "aschen", refresh: "wait_for" } + { injectKuzzleMeta: false, userId: "aschen", refresh: "wait_for" }, ); should(kuzzle.validation.validate).be.calledWith(request, false); @@ -1625,7 +1625,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.REPLACE, - { _id: request.input.args._id, _source: content } + { _id: request.input.args._id, _source: content }, ); should(response).match({ @@ -1644,7 +1644,7 @@ describe("DocumentController", () => { collection, "foobar", content, - { injectKuzzleMeta: false, userId: null, refresh: "false" } + { injectKuzzleMeta: false, userId: null, refresh: "false" }, ); }); }); @@ -1668,7 +1668,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -1682,14 +1682,14 @@ describe("DocumentController", () => { index, collection, "foobar", - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(kuzzle.ask).be.calledWith( "core:realtime:document:notify", request, actionEnum.DELETE, - { _id: "foobar", _source: "_source" } + { _id: "foobar", _source: "_source" }, ); should(response).be.eql({ _id: "foobar" }); @@ -1704,14 +1704,14 @@ describe("DocumentController", () => { "core:storage:public:document:delete", index, collection, - "foobar" + "foobar", ); should(kuzzle.ask).be.calledWith( "core:realtime:document:notify", request, actionEnum.DELETE, - { _id: "foobar", _source: "_source" } + { _id: "foobar", _source: "_source" }, ); should(response).be.eql({ _id: "foobar", _source: "_source" }); @@ -1748,7 +1748,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -1764,7 +1764,7 @@ describe("DocumentController", () => { collection, "foobar", content.fields, - { userId: "aschen", refresh: "wait_for" } + { userId: "aschen", refresh: "wait_for" }, ); should(kuzzle.ask).be.calledWithMatch( @@ -1774,7 +1774,7 @@ describe("DocumentController", () => { { _id: "_id", _source: { foo: "bar" }, - } + }, ); should(response).match({ @@ -1792,7 +1792,7 @@ describe("DocumentController", () => { collection, "foobar", content.fields, - { userId: null, refresh: "false" } + { userId: null, refresh: "false" }, ); }); @@ -1838,7 +1838,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -1852,14 +1852,14 @@ describe("DocumentController", () => { index, collection, ids, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(kuzzle.ask).be.calledWith( "core:realtime:document:mNotify", request, actionEnum.DELETE, - documents + documents, ); should(response).match({ @@ -1892,7 +1892,7 @@ describe("DocumentController", () => { should(documentController.mDelete(request)).be.rejectedWith( MultipleErrorsError, - { id: "api.process.incomplete_multiple_request" } + { id: "api.process.incomplete_multiple_request" }, ); }); }); @@ -1921,7 +1921,7 @@ describe("DocumentController", () => { "core:realtime:document:notify", request, actionEnum.CREATE, - { _id: "_id", _source: "_source" } + { _id: "_id", _source: "_source" }, ); }); @@ -1936,7 +1936,7 @@ describe("DocumentController", () => { index, collection, { foo: "bar" }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(kuzzle.ask).be.calledWith( @@ -1946,7 +1946,7 @@ describe("DocumentController", () => { [ { _id: "id1", _source: undefined }, { _id: "id2", _source: undefined }, - ] + ], ); should(response).match({ @@ -1969,7 +1969,7 @@ describe("DocumentController", () => { index, collection, { foo: "bar" }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(kuzzle.ask).be.calledWith( @@ -1979,7 +1979,7 @@ describe("DocumentController", () => { [ { _id: "id1", _source: "_source1" }, { _id: "id2", _source: "_source2" }, - ] + ], ); should(response).match({ @@ -1996,7 +1996,7 @@ describe("DocumentController", () => { return should(documentController.deleteByQuery(request)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); }); diff --git a/test/api/controllers/indexController.test.js b/test/api/controllers/indexController.test.js index ecfdbb84c4..e21153ec21 100644 --- a/test/api/controllers/indexController.test.js +++ b/test/api/controllers/indexController.test.js @@ -109,7 +109,7 @@ describe("IndexController", () => { should(kuzzle.ask).be.calledWith( "core:storage:public:index:create", - index + index, ); should(response).be.undefined(); @@ -122,7 +122,7 @@ describe("IndexController", () => { should(kuzzle.ask).be.calledWith( "core:storage:public:index:delete", - index + index, ); should(response).match({ @@ -155,7 +155,7 @@ describe("IndexController", () => { should(kuzzle.ask).be.calledWith( "core:storage:public:index:exist", - index + index, ); should(response).be.eql(true); diff --git a/test/api/controllers/memoryStorageController.test.js b/test/api/controllers/memoryStorageController.test.js index e3bbfe8b67..c77dfe7865 100644 --- a/test/api/controllers/memoryStorageController.test.js +++ b/test/api/controllers/memoryStorageController.test.js @@ -10,7 +10,7 @@ const { NativeController, } = require("../../../lib/api/controllers/baseController"); const MemoryStorageController = rewire( - "../../../lib/api/controllers/memoryStorageController.js" + "../../../lib/api/controllers/memoryStorageController.js", ); describe("MemoryStorageController", () => { @@ -64,24 +64,24 @@ describe("MemoryStorageController", () => { }; extractArgumentsFromRequest = wrap( - MemoryStorageController.__get__("extractArgumentsFromRequest") + MemoryStorageController.__get__("extractArgumentsFromRequest"), ); extractArgumentsFromRequestForSet = wrap( - MemoryStorageController.__get__("extractArgumentsFromRequestForSet") + MemoryStorageController.__get__("extractArgumentsFromRequestForSet"), ); extractArgumentsFromRequestForSort = wrap( - MemoryStorageController.__get__("extractArgumentsFromRequestForSort") + MemoryStorageController.__get__("extractArgumentsFromRequestForSort"), ); extractArgumentsFromRequestForZAdd = wrap( - MemoryStorageController.__get__("extractArgumentsFromRequestForZAdd") + MemoryStorageController.__get__("extractArgumentsFromRequestForZAdd"), ); extractArgumentsFromRequestForZInterstore = wrap( MemoryStorageController.__get__( - "extractArgumentsFromRequestForZInterstore" - ) + "extractArgumentsFromRequestForZInterstore", + ), ); extractArgumentsFromRequestForMExecute = wrap( - MemoryStorageController.__get__("extractArgumentsFromRequestForMExecute") + MemoryStorageController.__get__("extractArgumentsFromRequestForMExecute"), ); MemoryStorageController.__set__({ @@ -251,12 +251,12 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForSet(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); req.input.body.value = { foo: "bar" }; should(() => extractArgumentsFromRequestForSet(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -272,7 +272,7 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForSet(req)).throw( BadRequestError, - { id: "api.assert.mutually_exclusive" } + { id: "api.assert.mutually_exclusive" }, ); }); @@ -288,7 +288,7 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForSet(req)).throw( BadRequestError, - { id: "api.assert.mutually_exclusive" } + { id: "api.assert.mutually_exclusive" }, ); }); }); @@ -306,7 +306,7 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForSort(req)).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -365,31 +365,31 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForSort(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); req.input.body.limit = [10]; should(() => extractArgumentsFromRequestForSort(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); req.input.body.limit = [10, "foo"]; should(() => extractArgumentsFromRequestForSort(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); req.input.body.limit = [null, 20]; should(() => extractArgumentsFromRequestForSort(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); req.input.body.limit = [10, [20]]; should(() => extractArgumentsFromRequestForSort(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -403,7 +403,7 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForSort(req)).throw( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); req.input.body.direction = "asc"; @@ -462,7 +462,7 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForZAdd(req)).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -478,47 +478,47 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForZAdd(req)).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); req.input.body.elements = { score: 1, member: "m1" }; should(() => extractArgumentsFromRequestForZAdd(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); req.input.body.elements = []; should(() => extractArgumentsFromRequestForZAdd(req)).throw( BadRequestError, - { id: "api.assert.empty_argument" } + { id: "api.assert.empty_argument" }, ); req.input.body.elements = [{ score: 1 }]; should(() => extractArgumentsFromRequestForZAdd(req)).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); req.input.body.elements = [{ member: "m1" }]; should(() => extractArgumentsFromRequestForZAdd(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); req.input.body.elements = [{ score: "foo", member: "m1" }]; should(() => extractArgumentsFromRequestForZAdd(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); req.input.body.elements = [{ score: 1.23, member: "m1" }]; should(() => extractArgumentsFromRequestForZAdd(req)).not.throw( - BadRequestError + BadRequestError, ); req.input.body.elements = [{ score: "1.23", member: "m1" }]; should(() => extractArgumentsFromRequestForZAdd(req)).not.throw( - BadRequestError + BadRequestError, ); }); @@ -534,7 +534,7 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForZAdd(req)).throw( BadRequestError, - { id: "api.assert.mutually_exclusive" } + { id: "api.assert.mutually_exclusive" }, ); }); @@ -552,7 +552,7 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForZAdd(req)).throw( BadRequestError, - { id: "api.assert.too_many_arguments" } + { id: "api.assert.too_many_arguments" }, ); }); }); @@ -615,19 +615,19 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForZInterstore(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); req.input.body.keys = []; should(() => extractArgumentsFromRequestForZInterstore(req)).throw( BadRequestError, - { id: "api.assert.empty_argument" } + { id: "api.assert.empty_argument" }, ); delete req.input.body.keys; should(() => extractArgumentsFromRequestForZInterstore(req)).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -640,7 +640,7 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForZInterstore(req)).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -655,7 +655,7 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForZInterstore(req)).throw( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); req.input.body.aggregate = "min"; @@ -679,7 +679,7 @@ describe("MemoryStorageController", () => { should(() => extractArgumentsFromRequestForZInterstore(req)).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -721,13 +721,13 @@ describe("MemoryStorageController", () => { request.input.body.actions = [{ action: "set", args: {} }]; should(() => extractArgumentsFromRequestForMExecute(request)).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); request.input.body.actions = [{ action: "exec", args: {} }]; should(() => extractArgumentsFromRequestForMExecute(request)).throw( BadRequestError, - { id: "api.assert.forbidden_argument" } + { id: "api.assert.forbidden_argument" }, ); }); }); @@ -753,7 +753,7 @@ describe("MemoryStorageController", () => { "core:cache:public:execute", "set", "myKey", - "bar" + "bar", ); }); @@ -865,7 +865,7 @@ describe("MemoryStorageController", () => { "palermo", "15.087269", "37.502669", - "catania" + "catania", ); }); @@ -888,7 +888,7 @@ describe("MemoryStorageController", () => { "myKey", "foo", "bar", - "baz" + "baz", ); }); @@ -921,7 +921,7 @@ describe("MemoryStorageController", () => { "WITHDIST", "COUNT", "25", - "ASC" + "ASC", ); }); @@ -940,7 +940,7 @@ describe("MemoryStorageController", () => { await msController.georadiusbymember(req); should( - kuzzle.ask.withArgs("core:cache:public:execute", "georadiusbymember") + kuzzle.ask.withArgs("core:cache:public:execute", "georadiusbymember"), ) .calledTwice() .alwaysCalledWith( @@ -954,7 +954,7 @@ describe("MemoryStorageController", () => { "WITHDIST", "COUNT", "25", - "ASC" + "ASC", ); }); @@ -973,7 +973,7 @@ describe("MemoryStorageController", () => { "myKey", "foo", "bar", - "baz" + "baz", ); } }); @@ -1035,7 +1035,7 @@ describe("MemoryStorageController", () => { "foo", "bar", "baz", - "qux" + "qux", ); }); @@ -1145,7 +1145,7 @@ describe("MemoryStorageController", () => { "MATCH", "foobar", "COUNT", - 3 + 3, ); }); @@ -1186,7 +1186,7 @@ describe("MemoryStorageController", () => { "MATCH", "foobar", "COUNT", - 3 + 3, ); }); @@ -1205,7 +1205,7 @@ describe("MemoryStorageController", () => { "key", "foo", "bar", - "baz" + "baz", ); } }); @@ -1221,7 +1221,7 @@ describe("MemoryStorageController", () => { "sunion", "foo", "bar", - "baz" + "baz", ); } }); @@ -1246,7 +1246,7 @@ describe("MemoryStorageController", () => { "myKey", "startVal", "stopVal", - "WITHSCORES" + "WITHSCORES", ); } }); @@ -1263,7 +1263,7 @@ describe("MemoryStorageController", () => { return should(msController.zrangebylex(req)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); }); @@ -1287,7 +1287,7 @@ describe("MemoryStorageController", () => { "maxVal", "LIMIT", 10, - 20 + 20, ); }); @@ -1303,7 +1303,7 @@ describe("MemoryStorageController", () => { return should(msController.zrevrangebylex(req)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); }); @@ -1327,7 +1327,7 @@ describe("MemoryStorageController", () => { "minVal", "LIMIT", "10", - "20" + "20", ); }); @@ -1344,7 +1344,7 @@ describe("MemoryStorageController", () => { return should(msController.zrangebyscore(req)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); }); @@ -1370,7 +1370,7 @@ describe("MemoryStorageController", () => { "WITHSCORES", "LIMIT", 10, - 20 + 20, ); }); @@ -1387,7 +1387,7 @@ describe("MemoryStorageController", () => { return should(msController.zrevrangebyscore(req)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); }); @@ -1413,7 +1413,7 @@ describe("MemoryStorageController", () => { "WITHSCORES", "LIMIT", 10, - 20 + 20, ); }); }); diff --git a/test/api/controllers/realtimeController.test.js b/test/api/controllers/realtimeController.test.js index 3eedc000bb..b300c37bb7 100644 --- a/test/api/controllers/realtimeController.test.js +++ b/test/api/controllers/realtimeController.test.js @@ -28,7 +28,7 @@ describe("RealtimeController", () => { { connection: { id: "connectionId" }, user: { _id: "42" }, - } + }, ); }); @@ -44,7 +44,7 @@ describe("RealtimeController", () => { should(realtimeController.subscribe(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -53,7 +53,7 @@ describe("RealtimeController", () => { should(realtimeController.subscribe(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -62,7 +62,7 @@ describe("RealtimeController", () => { should(realtimeController.subscribe(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); }); @@ -113,14 +113,14 @@ describe("RealtimeController", () => { return should(realtimeController.join(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); }); it("should throw an error if roomId is not provided", () => { return should(realtimeController.join(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -143,14 +143,14 @@ describe("RealtimeController", () => { return should(realtimeController.unsubscribe(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); }); it("should throw an error if roomId is not provided", () => { return should(realtimeController.unsubscribe(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -163,7 +163,7 @@ describe("RealtimeController", () => { should(kuzzle.ask).calledWithMatch( "core:realtime:unsubscribe", "connectionId", - "foo" + "foo", ); }); }); @@ -174,14 +174,14 @@ describe("RealtimeController", () => { return should(realtimeController.count(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); }); it("should throw an error if roomId is not provided", () => { return should(realtimeController.count(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -234,7 +234,7 @@ describe("RealtimeController", () => { should(req.input.body._kuzzle_info.author).be.eql("42"); should(req.input.body._kuzzle_info.createdAt).be.approximately( Date.now(), - 100 + 100, ); }); diff --git a/test/api/controllers/securityController/credentials.test.js b/test/api/controllers/securityController/credentials.test.js index 76a5e4e199..7f597ba772 100644 --- a/test/api/controllers/securityController/credentials.test.js +++ b/test/api/controllers/securityController/credentials.test.js @@ -12,7 +12,7 @@ const { const KuzzleMock = require("../../../mocks/kuzzle.mock"); const SecurityController = rewire( - "../../../../lib/api/controllers/securityController" + "../../../../lib/api/controllers/securityController", ); describe("Test: security controller - credentials", () => { @@ -44,16 +44,16 @@ describe("Test: security controller - credentials", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.getStrategyMethod).be.calledTwice(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("validate"); should( - kuzzle.pluginsManager.getStrategyMethod.secondCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.secondCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.secondCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.secondCall.args[1], ).be.eql("create"); should(methodStub).be.calledTwice(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -88,7 +88,7 @@ describe("Test: security controller - credentials", () => { .rejects(error); return should(securityController.createCredentials(request)).rejectedWith( - error + error, ); }); }); @@ -111,16 +111,16 @@ describe("Test: security controller - credentials", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.getStrategyMethod).be.calledTwice(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("validate"); should( - kuzzle.pluginsManager.getStrategyMethod.secondCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.secondCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.secondCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.secondCall.args[1], ).be.eql("update"); should(methodStub).be.calledTwice(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -155,7 +155,7 @@ describe("Test: security controller - credentials", () => { .rejects(error); return should(securityController.updateCredentials(request)).rejectedWith( - error + error, ); }); }); @@ -175,10 +175,10 @@ describe("Test: security controller - credentials", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("exists"); should(methodStub).be.calledOnce(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -206,10 +206,10 @@ describe("Test: security controller - credentials", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("validate"); should(methodStub).be.calledOnce(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -237,10 +237,10 @@ describe("Test: security controller - credentials", () => { should(result).be.deepEqual({ acknowledged: true }); should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("delete"); should(methodStub).be.calledOnce(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -289,7 +289,7 @@ describe("Test: security controller - credentials", () => { should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce(); should(kuzzle.pluginsManager.getStrategyMethod).be.calledWith( "someStrategy", - "search" + "search", ); should(methodStub).be.calledOnce(); should(methodStub.firstCall.args[0]).be.eql({ query }); @@ -300,7 +300,7 @@ describe("Test: security controller - credentials", () => { kuzzle.pluginsManager.getStrategyMethod.returns(undefined); return should( - securityController.searchUsersByCredentials(request) + securityController.searchUsersByCredentials(request), ).rejectedWith({ id: "plugin.strategy.missing_optional_method" }); }); @@ -309,7 +309,7 @@ describe("Test: security controller - credentials", () => { request.input.args.size = 10; return should( - securityController.searchUsersByCredentials(request) + securityController.searchUsersByCredentials(request), ).rejectedWith(SizeLimitError, { id: "services.storage.get_limit_exceeded", }); @@ -319,7 +319,7 @@ describe("Test: security controller - credentials", () => { request.input.args.lang = "turkish"; return should( - securityController.searchUsersByCredentials(request) + securityController.searchUsersByCredentials(request), ).rejectedWith(BadRequestError, { id: "api.assert.invalid_argument" }); }); @@ -353,17 +353,17 @@ describe("Test: security controller - credentials", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.hasStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1], ).be.eql("getInfo"); should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("getInfo"); should(methodStub).be.calledOnce(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -387,10 +387,10 @@ describe("Test: security controller - credentials", () => { should(result).be.deepEqual({}); should(kuzzle.pluginsManager.hasStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1], ).be.eql("getInfo"); should(kuzzle.pluginsManager.getStrategyMethod.callCount).be.eql(0); }); @@ -413,17 +413,17 @@ describe("Test: security controller - credentials", () => { should(result).be.deepEqual({ foo: "bar" }); should(kuzzle.pluginsManager.hasStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1], ).be.eql("getById"); should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1], ).be.eql("getById"); should(methodStub).be.calledOnce(); should(methodStub.firstCall.args[0]).be.eql(request); @@ -447,10 +447,10 @@ describe("Test: security controller - credentials", () => { should(result).be.deepEqual({}); should(kuzzle.pluginsManager.hasStrategyMethod).be.calledOnce(); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1] + kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1], ).be.eql("getById"); should(kuzzle.pluginsManager.getStrategyMethod.callCount).be.eql(0); }); @@ -473,7 +473,7 @@ describe("Test: security controller - credentials", () => { should(result).be.deepEqual(["aField", "anotherField"]); should(kuzzle.pluginsManager.getStrategyFields).be.calledOnce(); should( - kuzzle.pluginsManager.getStrategyFields.firstCall.args[0] + kuzzle.pluginsManager.getStrategyFields.firstCall.args[0], ).be.eql("someStrategy"); }); }); @@ -504,10 +504,10 @@ describe("Test: security controller - credentials", () => { }); should(kuzzle.pluginsManager.getStrategyFields).be.calledTwice(); should( - kuzzle.pluginsManager.getStrategyFields.firstCall.args[0] + kuzzle.pluginsManager.getStrategyFields.firstCall.args[0], ).be.eql("someStrategy"); should( - kuzzle.pluginsManager.getStrategyFields.secondCall.args[0] + kuzzle.pluginsManager.getStrategyFields.secondCall.args[0], ).be.eql("someOtherStrategy"); }); }); diff --git a/test/api/controllers/securityController/profiles.test.js b/test/api/controllers/securityController/profiles.test.js index e44e6a8af3..882e7977fa 100644 --- a/test/api/controllers/securityController/profiles.test.js +++ b/test/api/controllers/securityController/profiles.test.js @@ -21,7 +21,7 @@ describe("Test: security controller - profiles", () => { beforeEach(() => { request = new Request( { controller: "security" }, - { user: { _id: "userId" } } + { user: { _id: "userId" } }, ); kuzzle = new KuzzleMock(); kuzzle.ask.withArgs("core:storage:private:document:get").resolves({}); @@ -62,7 +62,7 @@ describe("Test: security controller - profiles", () => { "core:storage:private:mappings:update", kuzzle.internalIndex.index, "profiles", - request.input.body + request.input.body, ); should(response).be.instanceof(Object); @@ -81,7 +81,7 @@ describe("Test: security controller - profiles", () => { should(kuzzle.ask).be.calledWith( "core:storage:private:mappings:get", kuzzle.internalIndex.index, - "profiles" + "profiles", ); should(response).be.instanceof(Object); @@ -109,7 +109,7 @@ describe("Test: security controller - profiles", () => { createOrReplaceEvent, request.input.args._id, request.input.body, - { refresh: "wait_for", userId: "userId" } + { refresh: "wait_for", userId: "userId" }, ); should(response).be.an.Object().and.not.instanceof(Profile); @@ -128,7 +128,7 @@ describe("Test: security controller - profiles", () => { createOrReplaceStub.rejects(error); await should( - securityController.createOrReplaceProfile(request) + securityController.createOrReplaceProfile(request), ).be.rejectedWith(error); should(createOrReplaceStub).calledOnce(); @@ -144,7 +144,7 @@ describe("Test: security controller - profiles", () => { createOrReplaceEvent, request.input.args._id, request.input.body, - { refresh: "false", userId: "userId" } + { refresh: "false", userId: "userId" }, ); } }); @@ -159,7 +159,7 @@ describe("Test: security controller - profiles", () => { createOrReplaceEvent, request.input.args._id, request.input.body, - { strict: false, userId: "userId" } + { strict: false, userId: "userId" }, ); } @@ -170,19 +170,19 @@ describe("Test: security controller - profiles", () => { createOrReplaceEvent, request.input.args._id, request.input.body, - { strict: true, userId: "userId" } + { strict: true, userId: "userId" }, ); }); it("should throw if an invalid profile format is provided", async () => { request.input.body = null; await should( - securityController.createOrReplaceProfile(request) + securityController.createOrReplaceProfile(request), ).rejectedWith(BadRequestError, { id: "api.assert.body_required" }); request.input.body = {}; await should( - securityController.createOrReplaceProfile(request) + securityController.createOrReplaceProfile(request), ).rejectedWith(BadRequestError, { id: "api.assert.missing_argument", message: 'Missing argument "body.policies".', @@ -195,7 +195,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.invalid_type", message: 'Wrong type for argument "body.policies" (expected: array)', - } + }, ); should(createOrReplaceStub).not.called(); @@ -206,7 +206,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.missing_argument", message: 'Missing argument "_id".', - } + }, ); should(createOrReplaceStub).not.called(); }); @@ -228,7 +228,7 @@ describe("Test: security controller - profiles", () => { createStub.rejects(error); await should(securityController.createProfile(request)).be.rejectedWith( - error + error, ); }); @@ -239,7 +239,7 @@ describe("Test: security controller - profiles", () => { createEvent, request.input.args._id, request.input.body, - { refresh: "wait_for", userId: "userId" } + { refresh: "wait_for", userId: "userId" }, ); should(response).be.an.Object().and.not.instanceof(Profile); @@ -256,7 +256,7 @@ describe("Test: security controller - profiles", () => { request.input.body = null; await should(securityController.createProfile(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); request.input.body = {}; @@ -265,7 +265,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.missing_argument", message: 'Missing argument "body.policies".', - } + }, ); should(createStub).not.called(); @@ -275,7 +275,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.invalid_type", message: 'Wrong type for argument "body.policies" (expected: array)', - } + }, ); should(createStub).not.called(); @@ -286,7 +286,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.missing_argument", message: 'Missing argument "_id".', - } + }, ); should(createStub).not.called(); }); @@ -301,7 +301,7 @@ describe("Test: security controller - profiles", () => { createStub, request.input.args._id, request.input.body, - { refresh: "false", userId: "userId" } + { refresh: "false", userId: "userId" }, ); } }); @@ -316,7 +316,7 @@ describe("Test: security controller - profiles", () => { createEvent, request.input.args._id, request.input.body, - { strict: false, userId: "userId" } + { strict: false, userId: "userId" }, ); } @@ -327,7 +327,7 @@ describe("Test: security controller - profiles", () => { createEvent, request.input.args._id, request.input.body, - { strict: true, userId: "userId" } + { strict: true, userId: "userId" }, ); }); @@ -335,7 +335,7 @@ describe("Test: security controller - profiles", () => { request.input.body = null; await should(securityController.createProfile(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); request.input.body = {}; @@ -344,7 +344,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.missing_argument", message: 'Missing argument "body.policies".', - } + }, ); request.input.body = { policies: "foobar" }; @@ -353,7 +353,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.invalid_type", message: 'Wrong type for argument "body.policies" (expected: array)', - } + }, ); request.input.args._id = null; @@ -363,7 +363,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.missing_argument", message: 'Missing argument "_id".', - } + }, ); }); }); @@ -399,7 +399,7 @@ describe("Test: security controller - profiles", () => { await should(securityController.getProfile(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); should(getStub).not.be.called(); @@ -411,7 +411,7 @@ describe("Test: security controller - profiles", () => { getStub.rejects(error); await should(securityController.getProfile(request)).be.rejectedWith( - error + error, ); should(getStub).calledWith(getEvent, request.input.args._id); @@ -432,7 +432,7 @@ describe("Test: security controller - profiles", () => { await should(securityController.mGetProfiles(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); should(mGetStub).not.called(); @@ -444,7 +444,7 @@ describe("Test: security controller - profiles", () => { mGetStub.rejects(error); await should(securityController.mGetProfiles(request)).be.rejectedWith( - error + error, ); should(mGetStub).calledWith(mGetEvent, request.input.body.ids); @@ -499,7 +499,7 @@ describe("Test: security controller - profiles", () => { from: 13, size: 42, scroll: "duration", - } + }, ); should(response).be.an.Object(); @@ -524,7 +524,7 @@ describe("Test: security controller - profiles", () => { from: 0, size: kuzzle.config.limits.documentsFetchCount, scroll: undefined, - } + }, ); }); @@ -538,7 +538,7 @@ describe("Test: security controller - profiles", () => { SizeLimitError, { id: "services.storage.get_limit_exceeded", - } + }, ); should(searchStub).not.called(); @@ -550,7 +550,7 @@ describe("Test: security controller - profiles", () => { searchStub.rejects(error); return should(securityController.searchProfiles(request)).be.rejectedWith( - error + error, ); }); }); @@ -573,7 +573,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.missing_argument", message: 'Missing argument "scrollId".', - } + }, ); should(scrollStub).not.be.called(); @@ -634,7 +634,7 @@ describe("Test: security controller - profiles", () => { refresh: "wait_for", retryOnConflict: 10, userId: request.context.user._id, - } + }, ); should(response).be.an.Object().and.not.instanceof(Profile); @@ -655,7 +655,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.missing_argument", message: 'Missing argument "_id".', - } + }, ); should(updateStub).not.called(); @@ -666,7 +666,7 @@ describe("Test: security controller - profiles", () => { await should(securityController.updateProfile(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); }); @@ -686,7 +686,7 @@ describe("Test: security controller - profiles", () => { retryOnConflict: 123, strict: true, userId: request.context.user._id, - } + }, ); }); @@ -695,7 +695,7 @@ describe("Test: security controller - profiles", () => { updateStub.rejects(error); return should(securityController.updateProfile(request)).rejectedWith( - error + error, ); }); }); @@ -727,7 +727,7 @@ describe("Test: security controller - profiles", () => { deleteStub.rejects(error); return should(securityController.deleteProfile(request)).be.rejectedWith( - error + error, ); }); @@ -739,7 +739,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.missing_argument", message: 'Missing argument "_id".', - } + }, ); should(deleteStub).not.called(); @@ -794,7 +794,7 @@ describe("Test: security controller - profiles", () => { { id: "api.assert.missing_argument", message: 'Missing argument "_id".', - } + }, ); should(getStub).not.called(); @@ -805,7 +805,7 @@ describe("Test: security controller - profiles", () => { getStub.rejects(error); return should(securityController.getProfileRights(request)).rejectedWith( - error + error, ); }); }); diff --git a/test/api/controllers/securityController/roles.test.js b/test/api/controllers/securityController/roles.test.js index dcac9084b4..c0190320c2 100644 --- a/test/api/controllers/securityController/roles.test.js +++ b/test/api/controllers/securityController/roles.test.js @@ -29,11 +29,11 @@ describe("Test: security controller - roles", () => { it("should throw a BadRequestError if the body is missing", async () => { await should(securityController.updateRoleMapping(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); should( - kuzzle.ask.withArgs("core:storage:private:mappings:update") + kuzzle.ask.withArgs("core:storage:private:mappings:update"), ).not.called(); }); @@ -49,7 +49,7 @@ describe("Test: security controller - roles", () => { "core:storage:private:mappings:update", kuzzle.internalIndex.index, "roles", - request.input.body + request.input.body, ); should(response).match(request.input.body); @@ -67,7 +67,7 @@ describe("Test: security controller - roles", () => { should(kuzzle.ask).be.calledWith( "core:storage:private:mappings:get", kuzzle.internalIndex.index, - "roles" + "roles", ); should(response).match({ mapping: { foo: "bar" } }); @@ -103,7 +103,7 @@ describe("Test: security controller - roles", () => { force: false, refresh: "wait_for", userId: request.context.user._id, - } + }, ); should(response).be.an.Object().and.not.instanceof(Role); @@ -122,7 +122,7 @@ describe("Test: security controller - roles", () => { createOrReplaceStub.rejects(error); return should( - securityController.createOrReplaceRole(request) + securityController.createOrReplaceRole(request), ).be.rejectedWith(error); }); @@ -140,7 +140,7 @@ describe("Test: security controller - roles", () => { force: true, refresh: "false", userId: request.context.user._id, - } + }, ); }); @@ -148,7 +148,7 @@ describe("Test: security controller - roles", () => { request.input.args._id = null; await should( - securityController.createOrReplaceRole(request) + securityController.createOrReplaceRole(request), ).rejectedWith(BadRequestError, { id: "api.assert.missing_argument" }); should(createOrReplaceStub).not.called(); @@ -158,7 +158,7 @@ describe("Test: security controller - roles", () => { request.input.body = null; await should( - securityController.createOrReplaceRole(request) + securityController.createOrReplaceRole(request), ).rejectedWith(BadRequestError, { id: "api.assert.body_required" }); should(createOrReplaceStub).not.called(); @@ -194,7 +194,7 @@ describe("Test: security controller - roles", () => { force: false, refresh: "wait_for", userId: request.context.user._id, - } + }, ); should(response).be.an.Object().and.not.instanceof(Role); @@ -213,7 +213,7 @@ describe("Test: security controller - roles", () => { createStub.rejects(error); return should(securityController.createRole(request)).be.rejectedWith( - error + error, ); }); @@ -231,7 +231,7 @@ describe("Test: security controller - roles", () => { force: true, refresh: "false", userId: request.context.user._id, - } + }, ); }); @@ -240,7 +240,7 @@ describe("Test: security controller - roles", () => { await should(securityController.createRole(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); should(createStub).not.called(); @@ -251,7 +251,7 @@ describe("Test: security controller - roles", () => { await should(securityController.createRole(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); should(createStub).not.called(); @@ -301,7 +301,7 @@ describe("Test: security controller - roles", () => { await should(securityController.getRole(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); should(getStub).not.called(); @@ -323,7 +323,7 @@ describe("Test: security controller - roles", () => { await should(securityController.mGetRoles(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); should(mGetStub).not.called(); @@ -334,7 +334,7 @@ describe("Test: security controller - roles", () => { await should(securityController.mGetRoles(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); should(mGetStub).not.called(); @@ -345,7 +345,7 @@ describe("Test: security controller - roles", () => { await should(securityController.mGetRoles(request)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); should(mGetStub).not.called(); @@ -420,7 +420,7 @@ describe("Test: security controller - roles", () => { should(searchStub).calledWithMatch( searchEvent, { controllers: request.input.body.controllers }, - { from: 0, size: kuzzle.config.limits.documentsFetchCount } + { from: 0, size: kuzzle.config.limits.documentsFetchCount }, ); }); @@ -432,7 +432,7 @@ describe("Test: security controller - roles", () => { SizeLimitError, { id: "services.storage.get_limit_exceeded", - } + }, ); should(searchStub).not.called(); @@ -445,7 +445,7 @@ describe("Test: security controller - roles", () => { BadRequestError, { id: "api.assert.invalid_type", - } + }, ); should(searchStub).not.called(); @@ -459,7 +459,7 @@ describe("Test: security controller - roles", () => { BadRequestError, { id: "api.assert.invalid_type", - } + }, ); should(searchStub).not.called(); @@ -474,7 +474,7 @@ describe("Test: security controller - roles", () => { BadRequestError, { id: "api.assert.invalid_type", - } + }, ); should(searchStub).not.called(); @@ -489,7 +489,7 @@ describe("Test: security controller - roles", () => { should(searchStub).calledWithMatch( searchEvent, {}, - { from: 0, size: kuzzle.config.limits.documentsFetchCount } + { from: 0, size: kuzzle.config.limits.documentsFetchCount }, ); request.input.body = null; @@ -499,7 +499,7 @@ describe("Test: security controller - roles", () => { should(searchStub).calledWithMatch( searchEvent, {}, - { from: 0, size: kuzzle.config.limits.documentsFetchCount } + { from: 0, size: kuzzle.config.limits.documentsFetchCount }, ); }); @@ -509,7 +509,7 @@ describe("Test: security controller - roles", () => { searchStub.rejects(error); return should(securityController.searchRoles(request)).rejectedWith( - error + error, ); }); }); @@ -542,7 +542,7 @@ describe("Test: security controller - roles", () => { refresh: "wait_for", retryOnConflict: 10, userId: request.context.user._id, - } + }, ); should(response).be.an.Object().and.not.instanceof(Role); @@ -560,7 +560,7 @@ describe("Test: security controller - roles", () => { await should(securityController.updateRole(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); should(updateStub).not.called(); @@ -571,7 +571,7 @@ describe("Test: security controller - roles", () => { await should(securityController.updateRole(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); should(updateStub).not.called(); @@ -601,7 +601,7 @@ describe("Test: security controller - roles", () => { refresh: "false", retryOnConflict: 123, userId: request.context.user._id, - } + }, ); }); }); @@ -631,7 +631,7 @@ describe("Test: security controller - roles", () => { await should(securityController.deleteRole(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); should(deleteStub).not.called(); diff --git a/test/api/controllers/securityController/security.test.js b/test/api/controllers/securityController/security.test.js index 61a22a0364..61c85329bd 100644 --- a/test/api/controllers/securityController/security.test.js +++ b/test/api/controllers/securityController/security.test.js @@ -9,7 +9,7 @@ const { NativeController, } = require("../../../../lib/api/controllers/baseController"); const SecurityController = rewire( - "../../../../lib/api/controllers/securityController" + "../../../../lib/api/controllers/securityController", ); const { Request, @@ -52,7 +52,7 @@ describe("/api/controllers/securityController", () => { should(kuzzle.ask).calledWith( "core:storage:private:collection:refresh", kuzzle.internalIndex.index, - collection + collection, ); } }); @@ -65,7 +65,7 @@ describe("/api/controllers/securityController", () => { }); should( - kuzzle.ask.withArgs("core:storage:private:collection:refresh") + kuzzle.ask.withArgs("core:storage:private:collection:refresh"), ).not.be.called(); }); }); @@ -85,7 +85,7 @@ describe("/api/controllers/securityController", () => { return should(securityController._mDelete("type", request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); }); @@ -94,7 +94,7 @@ describe("/api/controllers/securityController", () => { return should(securityController._mDelete("type", request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -103,7 +103,7 @@ describe("/api/controllers/securityController", () => { return should(securityController._mDelete("type", request)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -114,7 +114,7 @@ describe("/api/controllers/securityController", () => { SizeLimitError, { id: "services.storage.write_limit_exceeded", - } + }, ); }); @@ -128,7 +128,7 @@ describe("/api/controllers/securityController", () => { should(deleteStub).calledWithMatch( `core:security:${type}:delete`, id, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); } } @@ -146,7 +146,7 @@ describe("/api/controllers/securityController", () => { should(deleteStub).calledWithMatch( `core:security:${type}:delete`, id, - { refresh: "false" } + { refresh: "false" }, ); } } diff --git a/test/api/controllers/securityController/users.test.js b/test/api/controllers/securityController/users.test.js index 879a4ec067..6adb916b12 100644 --- a/test/api/controllers/securityController/users.test.js +++ b/test/api/controllers/securityController/users.test.js @@ -132,7 +132,7 @@ describe("Test: security controller - users", () => { kuzzle.pluginsManager.listStrategies.returns(["oops"]); await should( - securityController._persistUser(request, profileIds, content) + securityController._persistUser(request, profileIds, content), ).be.rejectedWith(BadRequestError, { id: "security.credentials.unknown_strategy", }); @@ -145,7 +145,7 @@ describe("Test: security controller - users", () => { strategyExistsStub.resolves(true); await should( - securityController._persistUser(request, profileIds, content) + securityController._persistUser(request, profileIds, content), ).be.rejectedWith(PluginImplementationError, { id: "security.credentials.database_inconsistency", }); @@ -158,7 +158,7 @@ describe("Test: security controller - users", () => { strategyValidateStub.rejects(new Error("error")); await should( - securityController._persistUser(request, profileIds, content) + securityController._persistUser(request, profileIds, content), ).be.rejectedWith(BadRequestError, { id: "security.credentials.rejected", }); @@ -168,7 +168,7 @@ describe("Test: security controller - users", () => { request.input.args._id, profileIds, content, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(kuzzle.ask).calledWithMatch(deleteEvent, request.input.args._id, { @@ -180,7 +180,7 @@ describe("Test: security controller - users", () => { strategyCreateStub.rejects(new Error("some error")); await should( - securityController._persistUser(request, profileIds, content) + securityController._persistUser(request, profileIds, content), ).rejectedWith(PluginImplementationError, { id: "plugin.runtime.unexpected_error", }); @@ -195,7 +195,7 @@ describe("Test: security controller - users", () => { createStub.rejects(error); await should( - securityController._persistUser(request, profileIds, content) + securityController._persistUser(request, profileIds, content), ).rejectedWith(error); should(strategyCreateStub).not.called(); @@ -227,7 +227,7 @@ describe("Test: security controller - users", () => { request.input.body.credentials.foo = { firstname: "X Æ A-12" }; await should( - securityController._persistUser(request, profileIds, content) + securityController._persistUser(request, profileIds, content), ).rejectedWith(PluginImplementationError, { id: "plugin.runtime.unexpected_error", message: /.*oh noes\nsomeStrategy delete error\n.*/, @@ -236,7 +236,7 @@ describe("Test: security controller - users", () => { should(strategyDeleteStub).calledWithMatch( request, request.input.args._id, - "someStrategy" + "someStrategy", ); }); @@ -246,14 +246,14 @@ describe("Test: security controller - users", () => { strategyValidateStub.rejects(error); await should( - securityController._persistUser(request, profileIds, content) + securityController._persistUser(request, profileIds, content), ).be.rejectedWith(error); strategyValidateStub.resolves(); strategyCreateStub.rejects(error); await should( - securityController._persistUser(request, profileIds, content) + securityController._persistUser(request, profileIds, content), ).be.rejectedWith(error); }); }); @@ -264,7 +264,7 @@ describe("Test: security controller - users", () => { it("should reject if the body is missing", () => { return should(securityController.updateUserMapping(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); }); @@ -278,7 +278,7 @@ describe("Test: security controller - users", () => { "core:storage:private:mappings:update", kuzzle.internalIndex.index, "users", - request.input.body + request.input.body, ); should(response).eql(foo); @@ -296,7 +296,7 @@ describe("Test: security controller - users", () => { should(kuzzle.ask).calledWith( "core:storage:private:mappings:get", kuzzle.internalIndex.index, - "users" + "users", ); should(response).match({ mapping: { foo: "bar" } }); @@ -307,7 +307,7 @@ describe("Test: security controller - users", () => { it("should reject if no id is given", () => { return should(securityController.getUser(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -368,7 +368,7 @@ describe("Test: security controller - users", () => { { id: "api.assert.missing_argument", message: 'Missing argument "ids".', - } + }, ); should(mGetStub).not.called(); @@ -465,7 +465,7 @@ describe("Test: security controller - users", () => { from: request.input.args.from, size: request.input.args.size, scroll: request.input.args.scroll, - } + }, ); // highlight only @@ -480,7 +480,7 @@ describe("Test: security controller - users", () => { from: request.input.args.from, size: request.input.args.size, scroll: request.input.args.scroll, - } + }, ); // all in one @@ -504,7 +504,7 @@ describe("Test: security controller - users", () => { from: request.input.args.from, size: request.input.args.size, scroll: request.input.args.scroll, - } + }, ); }); @@ -516,7 +516,7 @@ describe("Test: security controller - users", () => { SizeLimitError, { id: "services.storage.get_limit_exceeded", - } + }, ); }); @@ -525,7 +525,7 @@ describe("Test: security controller - users", () => { searchStub.rejects(error); return should(securityController.searchUsers(request)).be.rejectedWith( - error + error, ); }); @@ -535,7 +535,7 @@ describe("Test: security controller - users", () => { return should(securityController.searchUsers(request)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_argument" } + { id: "api.assert.invalid_argument" }, ); }); @@ -570,7 +570,7 @@ describe("Test: security controller - users", () => { return should(securityController.scrollUsers(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -627,7 +627,7 @@ describe("Test: security controller - users", () => { { id: "api.assert.missing_argument", message: 'Missing argument "_id".', - } + }, ); should(deleteStub).not.called(); @@ -638,7 +638,7 @@ describe("Test: security controller - users", () => { deleteStub.rejects(error); return should( - securityController.deleteUser(new Request({ _id: "test" })) + securityController.deleteUser(new Request({ _id: "test" })), ).be.rejectedWith(error); }); @@ -680,7 +680,7 @@ describe("Test: security controller - users", () => { await should(securityController.createUser(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); should(securityController._persistUser).not.called(); @@ -694,7 +694,7 @@ describe("Test: security controller - users", () => { { id: "api.assert.missing_argument", message: 'Missing argument "body.content.profileIds".', - } + }, ); should(securityController._persistUser).not.called(); @@ -709,7 +709,7 @@ describe("Test: security controller - users", () => { id: "api.assert.invalid_type", message: 'Wrong type for argument "body.content.profileIds" (expected: array)', - } + }, ); should(securityController._persistUser).not.called(); @@ -740,7 +740,7 @@ describe("Test: security controller - users", () => { }); should( - securityController._persistUser.firstCall.args[2] + securityController._persistUser.firstCall.args[2], ).not.have.ownProperty("profileIds"); should(response).eql(createdUser); @@ -750,7 +750,7 @@ describe("Test: security controller - users", () => { request.input.body.content.profileIds = ["ohnoes"]; await should( - securityController.createRestrictedUser(request) + securityController.createRestrictedUser(request), ).rejectedWith(BadRequestError, { id: "api.assert.forbidden_argument", message: @@ -770,11 +770,11 @@ describe("Test: security controller - users", () => { .calledWithMatch( request, kuzzle.config.security.restrictedProfileIds, - {} + {}, ); should( - securityController._persistUser.firstCall.args[2] + securityController._persistUser.firstCall.args[2], ).not.have.ownProperty("profileIds"); should(response).eql(createdUser); @@ -814,7 +814,7 @@ describe("Test: security controller - users", () => { refresh: "wait_for", retryOnConflict: 10, userId: request.context.user._id, - } + }, ); should(response).be.an.Object().and.not.instanceof(User); @@ -832,7 +832,7 @@ describe("Test: security controller - users", () => { { id: "api.assert.missing_argument", message: 'Missing argument "_id".', - } + }, ); should(updateStub).not.called(); @@ -843,7 +843,7 @@ describe("Test: security controller - users", () => { await should(securityController.updateUser(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); should(updateStub).not.called(); @@ -864,7 +864,7 @@ describe("Test: security controller - users", () => { refresh: "false", retryOnConflict: 123, userId: request.context.user._id, - } + }, ); }); @@ -897,7 +897,7 @@ describe("Test: security controller - users", () => { kuzzle.ask .withArgs("core:security:user:update", request.input.args._id) .rejects( - kerror.get("security", "user", "not_found", request.input.args._id) + kerror.get("security", "user", "not_found", request.input.args._id), ); const response = await securityController.upsertUser(request); @@ -933,7 +933,7 @@ describe("Test: security controller - users", () => { kuzzle.ask .withArgs("core:security:user:update", request.input.args._id) .rejects( - kerror.get("security", "user", "not_found", request.input.args._id) + kerror.get("security", "user", "not_found", request.input.args._id), ); const response = await securityController.upsertUser(request); @@ -982,7 +982,7 @@ describe("Test: security controller - users", () => { refresh: "wait_for", retryOnConflict: 10, userId: request.context.user._id, - } + }, ); should(response).be.an.Object().and.not.instanceof(User); @@ -1014,7 +1014,7 @@ describe("Test: security controller - users", () => { await should(securityController.replaceUser(request)).rejectedWith( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); should(replaceStub).not.called(); @@ -1025,7 +1025,7 @@ describe("Test: security controller - users", () => { await should(securityController.replaceUser(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); should(replaceStub).not.called(); @@ -1036,7 +1036,7 @@ describe("Test: security controller - users", () => { await should(securityController.replaceUser(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -1045,7 +1045,7 @@ describe("Test: security controller - users", () => { await should(securityController.replaceUser(request)).rejectedWith( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -1067,7 +1067,7 @@ describe("Test: security controller - users", () => { Object.assign( replacedUser, { _id: request.input.args._id }, - replacedUserContent + replacedUserContent, ); const response = await securityController.replaceUser(request); @@ -1080,7 +1080,7 @@ describe("Test: security controller - users", () => { { refresh: "wait_for", userId: request.context.user._id, - } + }, ); should(response).be.an.Object().and.not.instanceof(User); @@ -1103,7 +1103,7 @@ describe("Test: security controller - users", () => { { refresh: "false", userId: request.context.user._id, - } + }, ); }); }); @@ -1154,7 +1154,7 @@ describe("Test: security controller - users", () => { getStub.withArgs(getEvent, request.input.args._id).rejects(error); await should(securityController.getUserStrategies(request)).rejectedWith( - error + error, ); }); @@ -1166,7 +1166,7 @@ describe("Test: security controller - users", () => { { id: "api.assert.missing_argument", message: 'Missing argument "_id".', - } + }, ); should(getStub).not.called(); @@ -1230,7 +1230,7 @@ describe("Test: security controller - users", () => { { id: "api.assert.missing_argument", message: 'Missing argument "_id".', - } + }, ); should(getStub).not.called(); @@ -1242,7 +1242,7 @@ describe("Test: security controller - users", () => { getStub.rejects(error); return should(securityController.getUserRights(request)).rejectedWith( - error + error, ); }); }); @@ -1252,7 +1252,7 @@ describe("Test: security controller - users", () => { sinon.stub(securityController, "_mDelete").resolves("foobar"); await should(securityController.mDeleteUsers(request)).fulfilledWith( - "foobar" + "foobar", ); should(securityController._mDelete) @@ -1271,7 +1271,7 @@ describe("Test: security controller - users", () => { should(kuzzle.ask).calledWithMatch( "core:security:token:deleteByKuid", - request.input.args._id + request.input.args._id, ); }); @@ -1280,7 +1280,7 @@ describe("Test: security controller - users", () => { await should(securityController.revokeTokens(request)).rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -1292,7 +1292,7 @@ describe("Test: security controller - users", () => { .rejects(error); return should(securityController.revokeTokens(request)).rejectedWith( - error + error, ); }); }); @@ -1313,7 +1313,7 @@ describe("Test: security controller - users", () => { createOrReplaceRoleStub = kuzzle.ask.withArgs(createOrReplaceRoleEvent); createOrReplaceProfileStub = kuzzle.ask.withArgs( - createOrReplaceProfileEvent + createOrReplaceProfileEvent, ); adminExistsStub = kuzzle.ask.withArgs(adminExistsEvent).resolves(false); @@ -1323,7 +1323,7 @@ describe("Test: security controller - users", () => { adminExistsStub.resolves(true); await should( - securityController.createFirstAdmin(request) + securityController.createFirstAdmin(request), ).be.rejectedWith(PreconditionError, { id: "api.process.admin_exists" }); should(securityController._persistUser).not.called(); @@ -1360,7 +1360,7 @@ describe("Test: security controller - users", () => { createOrReplaceRoleEvent, key, content, - { refresh: "wait_for", userId: request.context.user._id } + { refresh: "wait_for", userId: request.context.user._id }, ); } @@ -1369,7 +1369,7 @@ describe("Test: security controller - users", () => { createOrReplaceProfileEvent, key, content, - { refresh: "wait_for", userId: request.context.user._id } + { refresh: "wait_for", userId: request.context.user._id }, ); } }); diff --git a/test/api/controllers/serverController.test.js b/test/api/controllers/serverController.test.js index cb2fce9ff0..3bab0062f6 100644 --- a/test/api/controllers/serverController.test.js +++ b/test/api/controllers/serverController.test.js @@ -459,13 +459,13 @@ describe("ServerController", () => { const apiDefinition = serverController._buildApiDefinition( controllers, - routes + routes, ); const pluginApiDefinition = serverController._buildApiDefinition( pluginsControllers, pluginsRoutes, - "/" + "/", ); should(apiDefinition).match({ diff --git a/test/api/funnel/checkRights.test.js b/test/api/funnel/checkRights.test.js index d54e286542..c9637b6f98 100644 --- a/test/api/funnel/checkRights.test.js +++ b/test/api/funnel/checkRights.test.js @@ -71,7 +71,7 @@ describe("funnel.checkRights", () => { should(global.kuzzle.tokenManager.link).be.calledWith( request.context.token, - "connection-id" + "connection-id", ); }); diff --git a/test/api/funnel/execute.test.js b/test/api/funnel/execute.test.js index 8ab8b34f72..acf0049920 100644 --- a/test/api/funnel/execute.test.js +++ b/test/api/funnel/execute.test.js @@ -39,7 +39,7 @@ describe("funnelController.execute", () => { { connection: { id: "connectionid" }, token: null, - } + }, ); funnel = new FunnelController(); @@ -99,7 +99,7 @@ describe("funnelController.execute", () => { { connection: { id: "connectionid" }, token: null, - } + }, ); funnel.execute(request, (err, res) => { @@ -121,7 +121,7 @@ describe("funnelController.execute", () => { { connection: { id: "connectionid" }, token: null, - } + }, ); funnel.execute(request, (err, res) => { @@ -149,7 +149,7 @@ describe("funnelController.execute", () => { { connection: { id: "connectionid" }, token: null, - } + }, ); funnel.execute(request, (err, res) => { @@ -170,7 +170,7 @@ describe("funnelController.execute", () => { { connection: { id: "connectionid" }, token: null, - } + }, ); request.input.headers = { origin: "foobar", @@ -198,7 +198,7 @@ describe("funnelController.execute", () => { { connection: { id: "connectionid" }, token: null, - } + }, ); request.input.headers = { origin: "foo", @@ -227,7 +227,7 @@ describe("funnelController.execute", () => { { connection: { id: "connectionid" }, token: null, - } + }, ); request.input.headers = {}; @@ -269,7 +269,7 @@ describe("funnelController.execute", () => { { connection: { id: "connectionid" }, token: null, - } + }, ); funnel.execute(request, (err, res) => { try { @@ -293,7 +293,7 @@ describe("funnelController.execute", () => { should(kuzzle.asyncStore.run).be.calledOnce(); should(kuzzle.pipe).be.calledWithMatch( "request:beforeExecution", - request + request, ); should(kuzzle.asyncStore.set).be.calledWith("REQUEST", request); @@ -309,7 +309,7 @@ describe("funnelController.execute", () => { it("should fire the hook the first time Kuzzle is in overloaded state", () => { funnel.overloaded = true; funnel.pendingRequestsQueue = Array( - kuzzle.config.limits.requestsBufferWarningThreshold + 1 + kuzzle.config.limits.requestsBufferWarningThreshold + 1, ); funnel.execute(request, () => {}); @@ -351,10 +351,10 @@ describe("funnelController.execute", () => { should(funnel.pendingRequestsQueue.length).be.eql(1); should(funnel.pendingRequestsQueue.shift()).eql(request.internalId); should(funnel.pendingRequestsById.get(request.internalId)).be.instanceOf( - FunnelController.__get__("PendingRequest") + FunnelController.__get__("PendingRequest"), ); should(funnel.pendingRequestsById.get(request.internalId).request).be.eql( - request + request, ); should(funnel._playPendingRequests).be.calledOnce(); }); @@ -385,19 +385,19 @@ describe("funnelController.execute", () => { should(funnel.pendingRequestsQueue.shift()).be.eql(request.internalId); should(funnel.pendingRequestsById.get(request.internalId)).have.property( "request", - request + request, ); should(funnel.pendingRequestsById.get(request.internalId)).have.property( - "fn" + "fn", ); should( - funnel.pendingRequestsById.get(request.internalId).fn + funnel.pendingRequestsById.get(request.internalId).fn, ).is.not.null(); should(funnel.pendingRequestsById.get(request.internalId)).have.property( - "context" + "context", ); should( - funnel.pendingRequestsById.get(request.internalId).contex + funnel.pendingRequestsById.get(request.internalId).contex, ).is.not.null(); should(funnel._playPendingRequests).have.callCount(0); }); @@ -418,7 +418,7 @@ describe("funnelController.execute", () => { it("should discard the request if the requestsBufferSize property is reached", (done) => { funnel.concurrentRequests = kuzzle.config.limits.concurrentRequests; funnel.pendingRequestsQueue = Array( - kuzzle.config.limits.requestsBufferSize + kuzzle.config.limits.requestsBufferSize, ); funnel.overloaded = true; @@ -427,7 +427,7 @@ describe("funnelController.execute", () => { should(funnel._playPendingRequests).have.callCount(0); should(funnel.processRequest).not.be.called(); should(funnel.pendingRequestsQueue.length).be.eql( - kuzzle.config.limits.requestsBufferSize + kuzzle.config.limits.requestsBufferSize, ); should(err).be.instanceOf(ServiceUnavailableError); should(err.status).be.eql(503); @@ -442,7 +442,7 @@ describe("funnelController.execute", () => { kuzzle.router.isConnectionAlive.returns(false); funnel.checkRights.throws( - new Error("funnel.checkRights should not have been called") + new Error("funnel.checkRights should not have been called"), ); should(funnel.execute(request, cb)).be.eql(0); @@ -469,7 +469,7 @@ describe("funnelController.execute", () => { it("should play pending requests in order", (done) => { const serialized = request.serialize(), secondRequest = new Request( - Object.assign(serialized.data, { id: "req-2" }) + Object.assign(serialized.data, { id: "req-2" }), ), firstCallback = sinon.spy(), secondCallback = () => { diff --git a/test/api/funnel/handleProcessRequestError.test.js b/test/api/funnel/handleProcessRequestError.test.js index 054d058cda..9e02095dda 100644 --- a/test/api/funnel/handleProcessRequestError.test.js +++ b/test/api/funnel/handleProcessRequestError.test.js @@ -59,13 +59,13 @@ describe("funnel.processRequest", () => { kuzzle.pipe.onSecondCall().callsFake(() => Promise.resolve().then(() => { throw customError; - }) + }), ); const res = funnel.handleProcessRequestError( request, request, - originalError + originalError, ); return should(res).rejectedWith(PluginImplementationError, { diff --git a/test/api/funnel/init.test.js b/test/api/funnel/init.test.js index 904a2d34e3..91b455cf01 100644 --- a/test/api/funnel/init.test.js +++ b/test/api/funnel/init.test.js @@ -40,22 +40,22 @@ describe("funnel.init", () => { should(funnel.controllers.get("bulk")).be.instanceOf(BulkController); should(funnel.controllers.get("cluster")).be.instanceOf(ClusterController); should(funnel.controllers.get("collection")).be.instanceOf( - CollectionController + CollectionController, ); should(funnel.controllers.get("debug")).be.instanceOf(DebugController); should(funnel.controllers.get("document")).be.instanceOf( - DocumentController + DocumentController, ); should(funnel.controllers.get("index")).be.instanceOf(IndexController); should(funnel.controllers.get("memoryStorage")).be.instanceOf( - MemoryStorageController + MemoryStorageController, ); should(funnel.controllers.get("ms")).be.instanceOf(MemoryStorageController); should(funnel.controllers.get("realtime")).be.instanceOf( - RealtimeController + RealtimeController, ); should(funnel.controllers.get("security")).be.instanceOf( - SecurityController + SecurityController, ); should(funnel.controllers.get("server")).be.instanceOf(ServerController); should(funnel.controllers.get("admin")).be.instanceOf(AdminController); diff --git a/test/api/funnel/processRequest.test.js b/test/api/funnel/processRequest.test.js index 5098e0d047..8d99d7f9e2 100644 --- a/test/api/funnel/processRequest.test.js +++ b/test/api/funnel/processRequest.test.js @@ -31,7 +31,7 @@ describe("funnel.processRequest", () => { mockrequire.reRequire("../../../lib/core/plugin/pluginContext"); mockrequire.reRequire("../../../lib/core/plugin/privilegedContext"); const PluginsManager = mockrequire.reRequire( - "../../../lib/core/plugin/pluginsManager" + "../../../lib/core/plugin/pluginsManager", ); kuzzle = new KuzzleMock(); @@ -46,7 +46,7 @@ describe("funnel.processRequest", () => { funnel.controllers.set("document", new DocumentController()); pluginsManager.controllers.set( "fakePlugin/controller", - new MockBaseController() + new MockBaseController(), ); }); @@ -91,7 +91,7 @@ describe("funnel.processRequest", () => { should(kuzzle.pipe).not.calledWith("request:onError", request); should(kuzzle.pipe).not.calledWith( "fakeController:errorCreate", - request + request, ); should(kuzzle.statistics.startRequest).not.be.called(); }); @@ -108,7 +108,7 @@ describe("funnel.processRequest", () => { should(kuzzle.pipe).not.calledWith("request:onError", request); should(kuzzle.pipe).not.calledWith( "fakePlugin/controller:errorCreate", - request + request, ); should(kuzzle.statistics.startRequest).not.be.called(); }); @@ -180,7 +180,7 @@ describe("funnel.processRequest", () => { should(kuzzle.pipe).not.calledWith("request:onError", request); should(kuzzle.pipe).not.calledWith( "fakeController:errorSucceed", - request + request, ); should(kuzzle.statistics.startRequest).be.called(); should(kuzzle.statistics.completedRequest).be.called(); @@ -229,7 +229,7 @@ describe("funnel.processRequest", () => { { id: "plugin.runtime.unexpected_error", message: /Caught an unexpected plugin error: foobar.*/, - } + }, ); should(kuzzle.pipe).calledWith(`${controller}:beforeFail`); @@ -309,7 +309,7 @@ describe("funnel.processRequest", () => { should(() => funnel._checkSdkVersion(request)).not.throw( BadRequestError, - { id: "api.process.incompatible_sdk_version" } + { id: "api.process.incompatible_sdk_version" }, ); }); diff --git a/test/api/rateLimiter.test.js b/test/api/rateLimiter.test.js index 10c376ce1a..d7bda1b762 100644 --- a/test/api/rateLimiter.test.js +++ b/test/api/rateLimiter.test.js @@ -32,7 +32,7 @@ describe("#api.rateLimiter", () => { connection: { id: "qux", }, - } + }, ); profiles = [ diff --git a/test/api/request/request.test.js b/test/api/request/request.test.js index 5bfa3e31c8..69e50f4062 100644 --- a/test/api/request/request.test.js +++ b/test/api/request/request.test.js @@ -190,7 +190,7 @@ describe("#Request", () => { [42, [true, false], "bar", true].forEach((value) => { should(() => rq.setResult("foobar", { headers: value })).throw( BadRequestError, - { message: 'Attribute headers must be of type "object"' } + { message: 'Attribute headers must be of type "object"' }, ); }); }); @@ -393,7 +393,7 @@ describe("#Request", () => { connection: { protocol: "http", }, - } + }, ); }); @@ -485,20 +485,20 @@ describe("#Request", () => { describe("#getBodyArray", () => { it("should return the array of the body (lodash parameter)", () => { should(request.getBodyArray("relations.lebron")).exactly( - request.input.body.relations.lebron + request.input.body.relations.lebron, ); }); it("extracts the required parameter", () => { should(request.getBodyArray("names")).exactly( - request.input.body.names + request.input.body.names, ); }); it("should throw if the parameter is missing", () => { should(() => request.getBodyArray("childhood")).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -546,32 +546,32 @@ describe("#Request", () => { describe("#getBodyString", () => { it("should return the string of the body (lodash parameter)", () => { should(request.getBodyString("relatives.Peter")).exactly( - request.input.body.relatives.Peter + request.input.body.relatives.Peter, ); }); it("should return the string of an array (lodash parameter)", () => { should(request.getBodyString("names.0")).exactly( - request.input.body.names[0] + request.input.body.names[0], ); }); it("should return the string of an array (lodash parameter)", () => { should(request.getBodyString("relations.lebron[0]")).exactly( - request.input.body.relations.lebron[0] + request.input.body.relations.lebron[0], ); }); it("extracts the required parameter", () => { should(request.getBodyString("fullname")).exactly( - request.input.body.fullname + request.input.body.fullname, ); }); it("should throw if the parameter is missing", () => { should(() => request.getBodyString("childhood")).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -592,7 +592,7 @@ describe("#Request", () => { should(() => request.getBodyString("fullname")).throw( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); }); @@ -608,20 +608,20 @@ describe("#Request", () => { describe("#getBodyObject", () => { it("should return the object of the body (lodash parameter)", () => { should(request.getBodyObject("powers.fire")).exactly( - request.input.body.powers.fire + request.input.body.powers.fire, ); }); it("extracts the required parameter", () => { should(request.getBodyObject("relatives")).exactly( - request.input.body.relatives + request.input.body.relatives, ); }); it("should throw if the parameter is missing", () => { should(() => request.getBodyObject("childhood")).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -642,7 +642,7 @@ describe("#Request", () => { should(() => request.getBodyObject("relatives")).throw( BadRequestError, - { id: "api.assert.body_required" } + { id: "api.assert.body_required" }, ); }); @@ -658,13 +658,13 @@ describe("#Request", () => { request.context.connection.protocol = "ws"; should(() => request.getBodyObject("otherPowers")).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); request.context.connection.protocol = "http"; should(() => request.getBodyObject("otherPowers")).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); }); @@ -672,7 +672,7 @@ describe("#Request", () => { describe("#getBodyNumber", () => { it("should return the number of the body (lodash parameter)", () => { should(request.getBodyNumber("powers.fire.damage")).exactly( - request.input.body.powers.fire.damage + request.input.body.powers.fire.damage, ); }); it("extracts the required parameter and convert it", () => { @@ -684,7 +684,7 @@ describe("#Request", () => { it("should throw if the parameter is missing", () => { should(() => request.getBodyNumber("childhood")).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -697,7 +697,7 @@ describe("#Request", () => { it("should throw if the parameter is not a number", () => { should(() => request.getBodyNumber("fullname")).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -721,7 +721,7 @@ describe("#Request", () => { describe("#getBodyInteger", () => { it("should return the integer of the body (lodash parameter)", () => { should(request.getBodyInteger("powers.fire.mana")).exactly( - request.input.body.powers.fire.mana + request.input.body.powers.fire.mana, ); }); @@ -734,7 +734,7 @@ describe("#Request", () => { it("should throw if the parameter is missing", () => { should(() => request.getBodyInteger("childhood")).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -751,7 +751,7 @@ describe("#Request", () => { should(() => request.getBodyInteger("fullname")).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -851,14 +851,14 @@ describe("#Request", () => { it("extracts the required parameter", () => { should(request.getArrayLegacy("names")).exactly( - request.input.args.names + request.input.args.names, ); }); it("should throw if the parameter is missing", () => { should(() => request.getArrayLegacy("childhood")).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -893,7 +893,7 @@ describe("#Request", () => { describe("#getString", () => { it("extracts the required parameter", () => { should(request.getString("fullname")).exactly( - request.input.args.fullname + request.input.args.fullname, ); }); @@ -923,7 +923,7 @@ describe("#Request", () => { it("extracts the required parameter", () => { should(request.getObject("relatives")).exactly( - request.input.args.relatives + request.input.args.relatives, ); }); @@ -974,14 +974,14 @@ describe("#Request", () => { it("extracts the birthdate in custom format", () => { should(request.getDate("birthDateDay", "YYYY-MM-DD")).eql( - "2022-04-11" + "2022-04-11", ); }); it("should throw if the parameter is invalid date regarding custom date", () => { should(() => request.getDate("birthDate", "YYYY-MM-DD")).throw( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -1006,7 +1006,7 @@ describe("#Request", () => { it("should throw if the parameter is missing", () => { should(() => request.getTimestamp("anotherDate")).throw( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); }); @@ -1172,7 +1172,7 @@ describe("#Request", () => { user: { _id: "id", }, - } + }, ); }); @@ -1292,7 +1292,7 @@ describe("#Request", () => { {}, { connection: { protocol: "http", verb: "POST" }, - } + }, ); const { from, size, scrollTTL, query, searchBody } = diff --git a/test/api/request/requestContext.test.js b/test/api/request/requestContext.test.js index 7e6cdbc1ef..e879d66429 100644 --- a/test/api/request/requestContext.test.js +++ b/test/api/request/requestContext.test.js @@ -72,19 +72,19 @@ describe("#RequestContext", () => { for (const key of ["id", "protocol"]) { for (const val of [{}, [], 123, true, false]) { should(() => new RequestContext({ connection: { [key]: val } })).throw( - `Attribute connection.${key} must be of type "string"` + `Attribute connection.${key} must be of type "string"`, ); } } // invalid IPs arrays should(() => new RequestContext({ connection: { ips: "foobar" } })).throw( - 'Attribute connection.ips must be of type "array"' + 'Attribute connection.ips must be of type "array"', ); should( - () => new RequestContext({ connection: { ips: ["foo", 123, {}] } }) + () => new RequestContext({ connection: { ips: ["foo", 123, {}] } }), ).throw( - 'Attribute connection.ips must contain only values of type "string"' + 'Attribute connection.ips must contain only values of type "string"', ); }); diff --git a/test/api/request/requestResponse.test.js b/test/api/request/requestResponse.test.js index 4d562c56d8..5159e18598 100644 --- a/test/api/request/requestResponse.test.js +++ b/test/api/request/requestResponse.test.js @@ -129,7 +129,7 @@ describe("#RequestResponse", () => { should(response.headers[name]).be.exactly( "foobar9", - `Header tested: ${name}` + `Header tested: ${name}`, ); }); }); diff --git a/test/cluster/idCardHandler.test.js b/test/cluster/idCardHandler.test.js index 9d6caa7fe3..f1c02c28f3 100644 --- a/test/cluster/idCardHandler.test.js +++ b/test/cluster/idCardHandler.test.js @@ -81,7 +81,7 @@ describe("ClusterIdCardHandler", () => { should(idCardHandler.nodeId).be.String(); should(idCardHandler.nodeIdKey).be.eql( - `{cluster/node}/${idCardHandler.nodeId}` + `{cluster/node}/${idCardHandler.nodeId}`, ); should(idCardHandler.idCard.id).be.eql(idCardHandler.nodeId); should(idCardHandler.idCard.ip).be.eql("192.168.42.42"); @@ -93,13 +93,13 @@ describe("ClusterIdCardHandler", () => { { onlyIfNew: true, ttl: refreshDelay * 2, - } + }, ); should(kuzzle.ask).be.calledWith( "core:cache:internal:execute", "sadd", "{cluster/node}/id-cards-index", - `{cluster/node}/${idCardHandler.nodeId}` + `{cluster/node}/${idCardHandler.nodeId}`, ); }); @@ -118,7 +118,7 @@ describe("ClusterIdCardHandler", () => { const args1 = kuzzle.ask.getCall(1).args; should(args0[1]).not.eql(args1[1]); should(kuzzle.ask.getCall(2).args[0]).be.eql( - "core:cache:internal:execute" + "core:cache:internal:execute", ); }); @@ -174,7 +174,7 @@ describe("ClusterIdCardHandler", () => { should(kuzzle.ask).be.calledWith( "core:cache:internal:execute", "smembers", - "{cluster/node}/id-cards-index" + "{cluster/node}/id-cards-index", ); should(kuzzle.ask).be.calledWith("core:cache:internal:mget", [ "redis/id2", @@ -185,7 +185,7 @@ describe("ClusterIdCardHandler", () => { "core:cache:internal:execute", "srem", "{cluster/node}/id-cards-index", - "redis/id4" + "redis/id4", ); should(remoteCards).be.eql([idCard2, idCard3]); }); diff --git a/test/cluster/node.test.js b/test/cluster/node.test.js index 2bf471d4e8..7e924e572a 100644 --- a/test/cluster/node.test.js +++ b/test/cluster/node.test.js @@ -221,14 +221,14 @@ describe("#Cluster Node", () => { kuzzle.config.cluster.interface = "foobar"; should(() => new ClusterNode()).throw( - /^\[CLUSTER\] No suitable IP address found with the provided configuration/ + /^\[CLUSTER\] No suitable IP address found with the provided configuration/, ); }); it("should throw if the only available address is an APIPA", () => { kuzzle.config.cluster.interface = "apipa"; should(() => new ClusterNode()).throw( - /^\[CLUSTER\] No suitable IP address found with the provided configuration/ + /^\[CLUSTER\] No suitable IP address found with the provided configuration/, ); }); }); @@ -288,13 +288,13 @@ describe("#Cluster Node", () => { await new Promise((resolve) => setTimeout(resolve, 300)); await should(Promise.race([initPromise, resolved])).fulfilledWith( - "init_waiting" + "init_waiting", ); node.countActiveNodes.returns(3); await new Promise((resolve) => setTimeout(resolve, 100)); await should(Promise.race([initPromise, resolved])).fulfilledWith( - "foonode" + "foonode", ); }); }); @@ -779,7 +779,7 @@ describe("#Cluster Node", () => { should(node.fullState.loadFullState).not.called(); should(kuzzle.log.error).calledWithMatch( - /Another node share the same IP address as this one \(2.3.4.2\): baz/ + /Another node share the same IP address as this one \(2.3.4.2\): baz/, ); should(kuzzle.shutdown).calledOnce(); }); @@ -933,7 +933,7 @@ describe("#Cluster Node", () => { should(subscriber.sync).calledOnce(); should(subscriber.sync.firstCall.args[0]).oneOf( "barmsgid", - "quxLastMessageId" + "quxLastMessageId", ); } @@ -950,7 +950,7 @@ describe("#Cluster Node", () => { it("should shutdown if unable to complete handshake before a timeout", async () => { kuzzle.config.cluster.joinTimeout = 10; node.idCardHandler.createIdCard.returns( - new Promise((resolve) => setTimeout(resolve, 100)) + new Promise((resolve) => setTimeout(resolve, 100)), ); node.handshake(); @@ -965,7 +965,7 @@ describe("#Cluster Node", () => { describe("#node addition", () => { it("should add the new node to the list and subscribe to it", async () => { await should( - node.addNode("foo", "1.2.3.4", Long.fromInt(23, true)) + node.addNode("foo", "1.2.3.4", Long.fromInt(23, true)), ).be.fulfilledWith(true); should(node.idCardHandler.addNode).calledOnce().calledWith("foo"); @@ -981,12 +981,12 @@ describe("#Cluster Node", () => { kuzzle.config.cluster.minimumNodes = 2; await should( - node.addNode("foo", "1.2.3.4", Long.fromInt(23, true)) + node.addNode("foo", "1.2.3.4", Long.fromInt(23, true)), ).be.fulfilledWith(true); should(kuzzle.state).eql(kuzzleStateEnum.RUNNING); should(kuzzle.log.warn).calledWithMatch( - /Minimum number of nodes reached/ + /Minimum number of nodes reached/, ); }); @@ -994,7 +994,7 @@ describe("#Cluster Node", () => { node.remoteNodes.set("foo", {}); await should( - node.addNode("foo", "1.2.3.4", Long.fromInt(23, true)) + node.addNode("foo", "1.2.3.4", Long.fromInt(23, true)), ).be.fulfilledWith(false); should(node.idCardHandler.addNode).not.called(); @@ -1038,7 +1038,7 @@ describe("#Cluster Node", () => { await node.evictNode("bar", { broadcast: true, reason: "because" }); should(kuzzle.log.warn).calledWith( - '[CLUSTER] Node "bar" evicted. Reason: because' + '[CLUSTER] Node "bar" evicted. Reason: because', ); should(node.activity[0]).match({ address: "1.2.3.4", @@ -1061,7 +1061,7 @@ describe("#Cluster Node", () => { await node.evictNode("bar", { reason: "because" }); should(kuzzle.log.warn).calledWith( - '[CLUSTER] Node "bar" evicted. Reason: because' + '[CLUSTER] Node "bar" evicted. Reason: because', ); should(node.activity[0]).match({ address: "1.2.3.4", @@ -1083,7 +1083,7 @@ describe("#Cluster Node", () => { await node.evictNode("bar", { reason: "because" }); should(kuzzle.log.warn).calledWith( - '[CLUSTER] Node "bar" evicted. Reason: because' + '[CLUSTER] Node "bar" evicted. Reason: because', ); should(node.activity[0]).match({ address: "1.2.3.4", diff --git a/test/cluster/publisher.test.js b/test/cluster/publisher.test.js index efdde90767..24008de516 100644 --- a/test/cluster/publisher.test.js +++ b/test/cluster/publisher.test.js @@ -53,7 +53,7 @@ describe("ClusterPublisher", () => { should(messageId).be.eql(publisher.lastMessageId); should(publisher.bufferSend).be.calledWith( "DumpRequest", - Buffer.from("08011206737566666978", "hex") + Buffer.from("08011206737566666978", "hex"), ); should(messageId > lastMessageId).be.true(); }); @@ -96,7 +96,7 @@ describe("ClusterPublisher", () => { const normalized = new NormalizedFilter( ["filters"], "roomId", - "index/collection" + "index/collection", ); const result = publisher.sendNewRealtimeRoom(normalized); @@ -159,7 +159,7 @@ describe("ClusterPublisher", () => { }; const result = publisher.sendDocumentNotification( ["rooms"], - notification + notification, ); should(result).be.eql("response"); @@ -203,7 +203,7 @@ describe("ClusterPublisher", () => { const result = publisher.sendNewAuthStrategy( "strategyName", "pluginName", - "strategy" + "strategy", ); should(result).be.eql("response"); @@ -219,7 +219,7 @@ describe("ClusterPublisher", () => { it("should send the appropriate command and payload", () => { const result = publisher.sendRemoveAuthStrategy( "strategyName", - "pluginName" + "pluginName", ); should(result).be.eql("response"); @@ -258,7 +258,7 @@ describe("ClusterPublisher", () => { const result = publisher.sendAddCollection( "scope", "index", - "collection" + "collection", ); should(result).be.eql("response"); @@ -287,7 +287,7 @@ describe("ClusterPublisher", () => { const result = publisher.sendRemoveCollection( "scope", "index", - "collection" + "collection", ); should(result).be.eql("response"); diff --git a/test/cluster/state.test.js b/test/cluster/state.test.js index 17b27f20fc..b28a49a9f5 100644 --- a/test/cluster/state.test.js +++ b/test/cluster/state.test.js @@ -35,14 +35,14 @@ describe("#Cluster Full State", () => { state.addRealtimeRoom("roomid", "index", "collection", filters, node); should(kuzzle.koncorde.store).calledWithMatch( - new NormalizedFilter(filters, "roomid", "index/collection") + new NormalizedFilter(filters, "roomid", "index/collection"), ); kuzzle.koncorde.store.resetHistory(); state.addRealtimeRoom("roomid2", "index", "collection", filters, node); should(kuzzle.koncorde.store).calledWithMatch( - new NormalizedFilter(filters, "roomid2", "index/collection") + new NormalizedFilter(filters, "roomid2", "index/collection"), ); kuzzle.koncorde.store.resetHistory(); @@ -57,7 +57,7 @@ describe("#Cluster Full State", () => { state.addRealtimeRoom("roomid3", "index", "collection", filters, node); should(kuzzle.koncorde.store).calledWithMatch( - new NormalizedFilter(filters, "roomid3", "index/collection") + new NormalizedFilter(filters, "roomid3", "index/collection"), ); should(state.serialize().rooms).match([ @@ -99,7 +99,7 @@ describe("#Cluster Full State", () => { state.addRealtimeRoom("roomid", "index", "collection", filters, node); should(() => - state.addRealtimeRoom("roomid", "index", "collection", filters, node) + state.addRealtimeRoom("roomid", "index", "collection", filters, node), ).throw({ id: "cluster.fatal.desync", message: /duplicate node/, @@ -116,7 +116,7 @@ describe("#Cluster Full State", () => { messageId: 456, nodeId: "nodeid", subscribers: 123, - } + }, ); state.addRealtimeRoom( @@ -128,7 +128,7 @@ describe("#Cluster Full State", () => { messageId: 456, nodeId: "nodeid2", subscribers: 123, - } + }, ); state.removeRealtimeRoom("roomid", "nodeid"); @@ -152,7 +152,7 @@ describe("#Cluster Full State", () => { messageId: 12, nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -164,7 +164,7 @@ describe("#Cluster Full State", () => { messageId: 45, nodeId: "nodeid2", subscribers: 56, - } + }, ); state.addRealtimeRoom( @@ -176,7 +176,7 @@ describe("#Cluster Full State", () => { messageId: 67, nodeId: "nodeid3", subscribers: 78, - } + }, ); state.removeRealtimeRoom("roomid", "nodeid2"); @@ -205,7 +205,7 @@ describe("#Cluster Full State", () => { }); should(state.getNormalizedFilters("roomid")).match( - new NormalizedFilter(filters, "roomid", "index/collection") + new NormalizedFilter(filters, "roomid", "index/collection"), ); should(state.getNormalizedFilters("ohnoes")).be.null(); @@ -221,7 +221,7 @@ describe("#Cluster Full State", () => { messageId: 12, nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -233,7 +233,7 @@ describe("#Cluster Full State", () => { messageId: 12, nodeId: "nodeid2", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -245,7 +245,7 @@ describe("#Cluster Full State", () => { messageId: 12, nodeId: "nodeid2", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -257,7 +257,7 @@ describe("#Cluster Full State", () => { messageId: 12, nodeId: "nodeid3", subscribers: 23, - } + }, ); should(state.countRealtimeSubscriptions("roomid")).be.eql(3 * 23); @@ -275,7 +275,7 @@ describe("#Cluster Full State", () => { messageId: 12, nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -287,7 +287,7 @@ describe("#Cluster Full State", () => { messageId: 12, nodeId: "nodeid2", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -299,7 +299,7 @@ describe("#Cluster Full State", () => { messageId: 12, nodeId: "nodeid2", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -311,7 +311,7 @@ describe("#Cluster Full State", () => { messageId: 12, nodeId: "nodeid3", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -323,7 +323,7 @@ describe("#Cluster Full State", () => { messageId: 12, nodeId: "nodeid3", subscribers: 23, - } + }, ); should(state.listRealtimeRooms()).match({ @@ -351,7 +351,7 @@ describe("#Cluster Full State", () => { messageId: Long.fromInt(12, true), nodeId: "nodeid", subscribers: 23, - } + }, ); const newMessageId = Long.fromInt(14, true); @@ -372,7 +372,7 @@ describe("#Cluster Full State", () => { it("should throw when attempting to add a new subscription to a non-existing room", () => { should(() => - state.addRealtimeSubscription("roomid", "nodeid", Long.fromInt(1)) + state.addRealtimeSubscription("roomid", "nodeid", Long.fromInt(1)), ).throw(InternalError, { id: "cluster.fatal.desync", message: /room doesn't exist/, @@ -389,11 +389,11 @@ describe("#Cluster Full State", () => { messageId: Long.fromInt(12, true), nodeId: "nodeid", subscribers: 23, - } + }, ); should(() => - state.addRealtimeSubscription("roomid", "ohnoes", Long.fromInt(1)) + state.addRealtimeSubscription("roomid", "ohnoes", Long.fromInt(1)), ).throw(InternalError, { id: "cluster.fatal.desync", message: /unknown node ohnoes/, @@ -412,7 +412,7 @@ describe("#Cluster Full State", () => { messageId: messageId, nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeSubscription("roomid", "nodeid", Long.fromInt(11, true)); @@ -438,7 +438,7 @@ describe("#Cluster Full State", () => { messageId: Long.fromInt(12, true), nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -450,7 +450,7 @@ describe("#Cluster Full State", () => { messageId: Long.fromInt(12, true), nodeId: "nodeid2", subscribers: 42, - } + }, ); const newMessageId = Long.fromInt(14, true); @@ -478,7 +478,7 @@ describe("#Cluster Full State", () => { const newMessageId = Long.fromInt(14, true); should(() => - state.removeRealtimeSubscription("roomid", "nodeid", newMessageId) + state.removeRealtimeSubscription("roomid", "nodeid", newMessageId), ).throw(InternalError, { id: "cluster.fatal.desync", message: /room doesn't exist/, @@ -495,7 +495,7 @@ describe("#Cluster Full State", () => { messageId: Long.fromInt(12, true), nodeId: "nodeid", subscribers: 1, - } + }, ); let newMessageId = Long.fromInt(14, true); @@ -516,7 +516,7 @@ describe("#Cluster Full State", () => { newMessageId = newMessageId.add(1); should(() => - state.removeRealtimeSubscription("roomid", "nodeid", newMessageId) + state.removeRealtimeSubscription("roomid", "nodeid", newMessageId), ).throw(InternalError, { id: "cluster.fatal.desync", message: /negative subscribers count/, @@ -533,13 +533,13 @@ describe("#Cluster Full State", () => { messageId: Long.fromInt(12, true), nodeId: "nodeid", subscribers: 1, - } + }, ); const newMessageId = Long.fromInt(14, true); should(() => - state.removeRealtimeSubscription("roomid", "ohnoes", newMessageId) + state.removeRealtimeSubscription("roomid", "ohnoes", newMessageId), ).throw(InternalError, { id: "cluster.fatal.desync", message: /unknown node ohnoes/, @@ -558,13 +558,13 @@ describe("#Cluster Full State", () => { messageId: messageId, nodeId: "nodeid", subscribers: 23, - } + }, ); state.removeRealtimeSubscription( "roomid", "nodeid", - Long.fromInt(11, true) + Long.fromInt(11, true), ); should(state.serialize().rooms).match([ @@ -590,7 +590,7 @@ describe("#Cluster Full State", () => { messageId, nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -602,7 +602,7 @@ describe("#Cluster Full State", () => { messageId, nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -614,7 +614,7 @@ describe("#Cluster Full State", () => { messageId, nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -626,7 +626,7 @@ describe("#Cluster Full State", () => { messageId, nodeId: "nodeid", subscribers: 23, - } + }, ); state.removeNode("nodeid"); @@ -676,7 +676,7 @@ describe("#Cluster Full State", () => { messageId: Long.fromInt(12, true), nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -688,7 +688,7 @@ describe("#Cluster Full State", () => { messageId: Long.fromInt(12, true), nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -700,7 +700,7 @@ describe("#Cluster Full State", () => { messageId: Long.fromInt(12, true), nodeId: "nodeid", subscribers: 23, - } + }, ); state.addRealtimeRoom( @@ -712,7 +712,7 @@ describe("#Cluster Full State", () => { messageId: Long.fromInt(12, true), nodeId: "nodeid", subscribers: 23, - } + }, ); state.addAuthStrategy({ strategyName: "foo", foo: "bar" }); diff --git a/test/cluster/subscriber.test.js b/test/cluster/subscriber.test.js index b05db12417..56cce1570e 100644 --- a/test/cluster/subscriber.test.js +++ b/test/cluster/subscriber.test.js @@ -113,11 +113,11 @@ describe("ClusterSubscriber", () => { await subscriber.init(); await new Promise((resolve) => - setTimeout(resolve, localNode.heartbeatDelay * 1.6) + setTimeout(resolve, localNode.heartbeatDelay * 1.6), ); should(subscriber.protoroot).not.be.null(); should(subscriber.socket.connect).be.calledWith( - subscriber.remoteNodeAddress + subscriber.remoteNodeAddress, ); should(subscriber.socket.subscribe).be.calledOnce(); should(subscriber.listen).be.calledOnce(); @@ -187,7 +187,7 @@ describe("ClusterSubscriber", () => { { broadcast: true, reason: "you have been a very bad node", - } + }, ); }); }); @@ -222,7 +222,7 @@ describe("ClusterSubscriber", () => { }; const encodedMessage = Buffer.from( "0800120573636f70651a0773656e736f7273", - "hex" + "hex", ); beforeEach(() => { @@ -276,7 +276,7 @@ describe("ClusterSubscriber", () => { { broadcast: true, reason: `received an invalid message from ${subscriber.remoteNodeId} (unknown topic "AddPokedex")`, - } + }, ); }); @@ -315,7 +315,7 @@ describe("ClusterSubscriber", () => { { broadcast: true, reason: "heartbeat timeout", - } + }, ); }); @@ -326,7 +326,7 @@ describe("ClusterSubscriber", () => { await subscriber.checkHeartbeat(); should(subscriber.state).be.eql( - ClusterSubscriber.stateEnum.MISSING_HEARTBEAT + ClusterSubscriber.stateEnum.MISSING_HEARTBEAT, ); }); }); @@ -366,7 +366,7 @@ describe("ClusterSubscriber", () => { { broadcast: true, reason: 'invalid message received (missing "messageId" field)', - } + }, ); should(subscriber.state).be.eql(ClusterSubscriber.stateEnum.EVICTED); }); @@ -469,7 +469,7 @@ describe("ClusterSubscriber", () => { messageId: "messageId", nodeId: subscriber.remoteNodeId, subscribers: 0, - } + }, ); }); }); @@ -486,7 +486,7 @@ describe("ClusterSubscriber", () => { should(localNode.fullState.addRealtimeSubscription).be.calledWith( "roomId", subscriber.remoteNodeId, - "messageId" + "messageId", ); }); }); @@ -502,7 +502,7 @@ describe("ClusterSubscriber", () => { should(localNode.fullState.removeRealtimeRoom).be.calledWith( "roomId", - subscriber.remoteNodeId + subscriber.remoteNodeId, ); }); }); @@ -519,7 +519,7 @@ describe("ClusterSubscriber", () => { should(localNode.fullState.removeRealtimeSubscription).be.calledWith( "roomId", subscriber.remoteNodeId, - "messageId" + "messageId", ); }); }); @@ -601,7 +601,7 @@ describe("ClusterSubscriber", () => { should(kuzzle.pluginsManager.registerStrategy).be.calledWith( "pluginName", "strategyName", - "strategy" + "strategy", ); }); }); @@ -616,11 +616,11 @@ describe("ClusterSubscriber", () => { await subscriber.handleAuthStrategyRemoval(message); should(localNode.fullState.removeAuthStrategy).be.calledWith( - "strategyName" + "strategyName", ); should(kuzzle.pluginsManager.unregisterStrategy).be.calledWith( "pluginName", - "strategyName" + "strategyName", ); }); }); @@ -673,7 +673,7 @@ describe("ClusterSubscriber", () => { should(kuzzle.ask).be.calledWith( "core:security:profile:invalidate", - "profileId" + "profileId", ); }); }); @@ -688,7 +688,7 @@ describe("ClusterSubscriber", () => { should(kuzzle.ask).be.calledWith( "core:security:role:invalidate", - "roleId" + "roleId", ); }); }); @@ -704,7 +704,7 @@ describe("ClusterSubscriber", () => { should(kuzzle.ask).be.calledWith( "core:storage:scope:cache:addIndex", - "index" + "index", ); }); }); @@ -722,7 +722,7 @@ describe("ClusterSubscriber", () => { should(kuzzle.ask).be.calledWith( "core:storage:scope:cache:addCollection", "index", - "collection" + "collection", ); }); }); @@ -740,7 +740,7 @@ describe("ClusterSubscriber", () => { should(kuzzle.ask).be.calledWith( "core:storage:scope:cache:removeCollection", "index", - "collection" + "collection", ); }); }); diff --git a/test/cluster/workers/IDCardRenewer.test.js b/test/cluster/workers/IDCardRenewer.test.js index be134e4ac5..38689f4f3c 100644 --- a/test/cluster/workers/IDCardRenewer.test.js +++ b/test/cluster/workers/IDCardRenewer.test.js @@ -30,7 +30,7 @@ describe("ClusterIDCardRenewer", () => { { initTimeout: 42, }, - "foo" + "foo", ); }); diff --git a/test/config/index.test.js b/test/config/index.test.js index 0cfdb68c36..52bf190d9b 100644 --- a/test/config/index.test.js +++ b/test/config/index.test.js @@ -175,7 +175,7 @@ describe("lib/config/index.js", () => { it("should throw on negative limit values", () => { for (const limit of Object.keys(defaultConfig.default.limits).filter( - (l) => l !== "requestsRate" + (l) => l !== "requestsRate", )) { mockedConfigContent = getcfg({ limits: { @@ -197,7 +197,7 @@ describe("lib/config/index.js", () => { ]; for (const limit of Object.keys(defaultConfig.default.limits).filter( - (l) => l !== "requestsRate" + (l) => l !== "requestsRate", )) { mockedConfigContent = getcfg({ limits: { @@ -278,7 +278,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[http] "accessControlAllowOrigin" parameter: invalid value "${bad}" (array or string expected)` + `[http] "accessControlAllowOrigin" parameter: invalid value "${bad}" (array or string expected)`, ); } }); @@ -297,7 +297,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[http] "enabled" parameter: invalid value "${bad}" (boolean expected)` + `[http] "enabled" parameter: invalid value "${bad}" (boolean expected)`, ); } }); @@ -316,7 +316,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[http] "allowCompression" parameter: invalid value "${bad}" (boolean expected)` + `[http] "allowCompression" parameter: invalid value "${bad}" (boolean expected)`, ); } }); @@ -335,7 +335,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[http] "maxEncodingLayers" parameter: invalid value "${bad}" (integer >= 1 expected)` + `[http] "maxEncodingLayers" parameter: invalid value "${bad}" (integer >= 1 expected)`, ); } }); @@ -354,7 +354,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[http] "maxFormFileSize" parameter: cannot parse "${bad}"` + `[http] "maxFormFileSize" parameter: cannot parse "${bad}"`, ); } }); @@ -373,7 +373,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[http] "additionalContentTypes" parameter: invalid value "${bad}" (array of strings expected)` + `[http] "additionalContentTypes" parameter: invalid value "${bad}" (array of strings expected)`, ); } }); @@ -394,7 +394,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[websocket] "enabled" parameter: invalid value "${bad}" (boolean expected)` + `[websocket] "enabled" parameter: invalid value "${bad}" (boolean expected)`, ); } }); @@ -413,7 +413,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[websocket] "idleTimeout" parameter: invalid value "${bad}" (integer >= 1000 expected)` + `[websocket] "idleTimeout" parameter: invalid value "${bad}" (integer >= 1000 expected)`, ); } }); @@ -432,7 +432,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[websocket] "compression" parameter: invalid value "${bad}" (boolean expected)` + `[websocket] "compression" parameter: invalid value "${bad}" (boolean expected)`, ); } }); @@ -451,7 +451,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[websocket] "rateLimit" parameter: invalid value "${bad}" (integer >= 0 expected)` + `[websocket] "rateLimit" parameter: invalid value "${bad}" (integer >= 0 expected)`, ); } }); @@ -470,7 +470,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[websocket] "sendPingsAutomatically" parameter: invalid value "${bad}" (boolean expected)` + `[websocket] "sendPingsAutomatically" parameter: invalid value "${bad}" (boolean expected)`, ); } }); @@ -489,7 +489,7 @@ describe("lib/config/index.js", () => { // eslint-disable-next-line no-loop-func should(() => config.loadConfig()).throw( - `[websocket] "resetIdleTimeoutOnSend" parameter: invalid value "${bad}" (boolean expected)` + `[websocket] "resetIdleTimeoutOnSend" parameter: invalid value "${bad}" (boolean expected)`, ); } }); diff --git a/test/core/auth/passportWrapper.test.js b/test/core/auth/passportWrapper.test.js index c87bde4ef9..3b30653bcd 100644 --- a/test/core/auth/passportWrapper.test.js +++ b/test/core/auth/passportWrapper.test.js @@ -25,7 +25,7 @@ describe("Test the passport Wrapper", () => { mockrequire("passport", passportMock); PassportWrapper = mockrequire.reRequire( - "../../../lib/core/auth/passportWrapper" + "../../../lib/core/auth/passportWrapper", ); passportWrapper = new PassportWrapper(); @@ -69,7 +69,7 @@ describe("Test the passport Wrapper", () => { passportMock.authenticate.yields(null, user); return should(passportWrapper.authenticate("foo", "bar")).be.fulfilledWith( - user + user, ); }); @@ -78,7 +78,7 @@ describe("Test the passport Wrapper", () => { return should(passportWrapper.authenticate("foo", "bar")).be.rejectedWith( UnauthorizedError, - { message: "foobar" } + { message: "foobar" }, ); }); @@ -87,7 +87,7 @@ describe("Test the passport Wrapper", () => { passportMock.authenticate.yields(err); return should(passportWrapper.authenticate("foo", "bar")).be.rejectedWith( - err + err, ); }); @@ -125,7 +125,7 @@ describe("Test the passport Wrapper", () => { mockrequire("passport", passport); PassportWrapper = mockrequire.reRequire( - "../../../lib/core/auth/passportWrapper" + "../../../lib/core/auth/passportWrapper", ); passportWrapper = new PassportWrapper(); passportWrapper.use(new MockupStrategy("mockup", stub)); @@ -142,7 +142,7 @@ describe("Test the passport Wrapper", () => { passportMock.authenticate.throws(new ForbiddenError("foobar")); return should(passportWrapper.authenticate("foo", "bar")).be.rejectedWith( - "foobar" + "foobar", ); }); @@ -151,7 +151,7 @@ describe("Test the passport Wrapper", () => { return should(passportWrapper.authenticate("foo", "bar")).be.rejectedWith( PluginImplementationError, - { id: "plugin.runtime.unexpected_error" } + { id: "plugin.runtime.unexpected_error" }, ); }); }); diff --git a/test/core/auth/tokenManager.test.js b/test/core/auth/tokenManager.test.js index ecafa83eec..bf70eab846 100644 --- a/test/core/auth/tokenManager.test.js +++ b/test/core/auth/tokenManager.test.js @@ -311,11 +311,11 @@ describe("Test: token manager core component", () => { tokenManager.link( new Token({ _id: "bar", expiresAt: now + 1000000 }), - "connectionId1" + "connectionId1", ); tokenManager.link( new Token({ _id: "foo", expiresAt: now - 1000 }), - "connectionId2" + "connectionId2", ); runTimerStub.resetHistory(); @@ -339,7 +339,7 @@ describe("Test: token manager core component", () => { tokenManager.link( new Token({ _id: "api-key-1", expiresAt: -1 }), - "connectionId1" + "connectionId1", ); runTimerStub.resetHistory(); @@ -361,7 +361,7 @@ describe("Test: token manager core component", () => { tokenManager.link( new Token({ _id: "foo", expiresAt: now - 1000 }), - "connectionId2" + "connectionId2", ); runTimerStub.resetHistory(); @@ -472,12 +472,12 @@ describe("Test: token manager core component", () => { it("should do nothing if the provided token is not linked", () => { tokenManager.refresh( new Token({ _id: "i am the beyonder" }), - new Token({ _id: "i am the mountain" }) + new Token({ _id: "i am the mountain" }), ); should(tokenManager.tokens.array).have.length(1); should(tokenManager.tokens.array[0].idx).eql( - `${token.expiresAt};${token._id}` + `${token.expiresAt};${token._id}`, ); should(tokenManager.tokensByConnection.get("foo")).match({ @@ -491,7 +491,7 @@ describe("Test: token manager core component", () => { should(tokenManager.tokens.array).have.length(1); should(tokenManager.tokens.array[0].idx).eql( - `${newT.expiresAt};${newT._id}` + `${newT.expiresAt};${newT._id}`, ); should(tokenManager.tokensByConnection.get("foo")).match({ diff --git a/test/core/backend/Backend.test.js b/test/core/backend/Backend.test.js index 09a677db25..c9ff5326f9 100644 --- a/test/core/backend/Backend.test.js +++ b/test/core/backend/Backend.test.js @@ -112,10 +112,10 @@ describe("Backend", () => { should(options.vaultKey).be.eql(application._vaultKey); should(options.plugins).have.keys( "kuzzle-plugin-logger", - "kuzzle-plugin-auth-passport-local" + "kuzzle-plugin-auth-passport-local", ); should(options.installations).be.eql( - application._installationsWaitingList + application._installationsWaitingList, ); should(options.import).be.eql(application._import); should(options.support).be.eql(application._support); @@ -125,7 +125,7 @@ describe("Backend", () => { application.config.content.plugins.common.include = ["foo"]; await should(application.start()).rejectedWith( - /Cannot find module 'foo'.*/ + /Cannot find module 'foo'.*/, ); application.config.content.plugins.common.include = [ @@ -140,7 +140,7 @@ describe("Backend", () => { should(options.plugins).have.keys("kuzzle-plugin-logger"); should(options.plugins).not.have.keys( - "kuzzle-plugin-auth-passport-local" + "kuzzle-plugin-auth-passport-local", ); }); }); diff --git a/test/core/backend/BackendController.test.js b/test/core/backend/BackendController.test.js index b083e089ac..d426c3faa5 100644 --- a/test/core/backend/BackendController.test.js +++ b/test/core/backend/BackendController.test.js @@ -73,7 +73,7 @@ describe("Backend", () => { should(application._controllers.greeting).not.be.undefined(); should(application._controllers.greeting.actions.sayHello).be.eql( - definition.actions.sayHello + definition.actions.sayHello, ); }); @@ -120,7 +120,7 @@ describe("Backend", () => { should(application._controllers.greeting).not.be.undefined(); should( - application._controllers.greeting.actions.sayHello.handler.name + application._controllers.greeting.actions.sayHello.handler.name, ).be.eql("bound sayHello"); }); diff --git a/test/core/backend/BackendPipe.test.js b/test/core/backend/BackendPipe.test.js index 307fd9f099..a163dc08d2 100644 --- a/test/core/backend/BackendPipe.test.js +++ b/test/core/backend/BackendPipe.test.js @@ -67,7 +67,7 @@ describe("Backend", () => { should(global.kuzzle.pluginsManager.registerPipe).be.calledWith( global.kuzzle.pluginsManager.application, "kuzzle:state:ready", - handler + handler, ); }); }); @@ -84,7 +84,7 @@ describe("Backend", () => { application.pipe.unregister("unique-pipe-id"); should(global.kuzzle.pluginsManager.unregisterPipe).be.calledWith( - "unique-pipe-id" + "unique-pipe-id", ); }); diff --git a/test/core/backend/BackendStorage.test.js b/test/core/backend/BackendStorage.test.js index 8e184d4967..92aac0b6f9 100644 --- a/test/core/backend/BackendStorage.test.js +++ b/test/core/backend/BackendStorage.test.js @@ -32,7 +32,7 @@ describe("Backend", () => { const client = new application.storage.StorageClient({ maxRetries: 42 }); should(client).be.instanceOf(ElasticsearchClient); should(client.connectionPool.connections[0].url.toString()).be.eql( - "http://es:9200/" + "http://es:9200/", ); should(client.helpers.maxRetries).be.eql(42); }); @@ -47,10 +47,10 @@ describe("Backend", () => { should(application.storage._client).be.null(); should(application.storage.storageClient).be.instanceOf( - ElasticsearchClient + ElasticsearchClient, ); should( - application.storage.storageClient.connectionPool.connections[0].url.toString() + application.storage.storageClient.connectionPool.connections[0].url.toString(), ).be.eql("http://es:9200/"); }); }); diff --git a/test/core/backend/InternalLogger.test.js b/test/core/backend/InternalLogger.test.js index da183fe8e6..514982d221 100644 --- a/test/core/backend/InternalLogger.test.js +++ b/test/core/backend/InternalLogger.test.js @@ -39,7 +39,7 @@ describe("Backend", () => { should(global.kuzzle.log.warn).be.calledWith(util.inspect("warn")); should(global.kuzzle.log.error).be.calledWith(util.inspect("error")); should(global.kuzzle.log.verbose).be.calledWith( - util.inspect({ info: "verbose" }) + util.inspect({ info: "verbose" }), ); }); }); diff --git a/test/core/cache/cacheEngine.test.js b/test/core/cache/cacheEngine.test.js index 576be0ab3b..7d0103f0eb 100644 --- a/test/core/cache/cacheEngine.test.js +++ b/test/core/cache/cacheEngine.test.js @@ -73,7 +73,7 @@ describe("CacheEngine", () => { "core:cache:internal:script:define", "name", "keys", - "script" + "script", ); should(cacheEngine.internal.client.defineCommand).calledWith("name", { lua: "script", @@ -85,7 +85,7 @@ describe("CacheEngine", () => { "core:cache:internal:script:execute", "name", "foo", - "bar" + "bar", ); should(cacheEngine.internal.client.name).calledWith("foo", "bar"); }); diff --git a/test/core/debug/kuzzleDebugger.test.js b/test/core/debug/kuzzleDebugger.test.js index 3f5fb0c28e..61da6766de 100644 --- a/test/core/debug/kuzzleDebugger.test.js +++ b/test/core/debug/kuzzleDebugger.test.js @@ -45,7 +45,7 @@ describe("Test: Kuzzle Debugger", () => { { method: "notification", foo: "bar", - } + }, ); await should(kuzzleDebugger.notifyConnection) @@ -126,7 +126,7 @@ describe("Test: Kuzzle Debugger", () => { await should(kuzzleDebugger.post("Debugger.enable")).be.rejectedWith( PreconditionError, - { id: "core.debugger.not_enabled" } + { id: "core.debugger.not_enabled" }, ); }); @@ -137,7 +137,7 @@ describe("Test: Kuzzle Debugger", () => { await should(kuzzleDebugger.inspectorPost).be.calledWithMatch( "Debugger.enable", - {} + {}, ); }); }); @@ -150,14 +150,14 @@ describe("Test: Kuzzle Debugger", () => { it("should throw if the debugger is not enabled", async () => { kuzzleDebugger.debuggerStatus = false; await should( - kuzzleDebugger.addListener("EventMock.event_foo", "foobar") + kuzzleDebugger.addListener("EventMock.event_foo", "foobar"), ).be.rejectedWith(PreconditionError, { id: "core.debugger.not_enabled" }); }); it("should add the connectionId to the list of listener for the requested event", async () => { await kuzzleDebugger.addListener("EventMock.event_foo", "foobar"); should(kuzzleDebugger.events.get("EventMock.event_foo")).be.eql( - new Set(["foobar"]) + new Set(["foobar"]), ); }); }); @@ -170,7 +170,7 @@ describe("Test: Kuzzle Debugger", () => { it("should throw if the debugger is not enabled", async () => { kuzzleDebugger.debuggerStatus = false; await should( - kuzzleDebugger.removeListener("EventMock.event_foo", "foobar") + kuzzleDebugger.removeListener("EventMock.event_foo", "foobar"), ).be.rejectedWith(PreconditionError, { id: "core.debugger.not_enabled" }); }); @@ -180,7 +180,7 @@ describe("Test: Kuzzle Debugger", () => { ]); await kuzzleDebugger.removeListener("EventMock.event_foo", "foobar"); should(kuzzleDebugger.events.get("EventMock.event_foo")).be.eql( - new Set([]) + new Set([]), ); }); }); @@ -194,7 +194,7 @@ describe("Test: Kuzzle Debugger", () => { kuzzleDebugger.debuggerStatus = false; await should(kuzzleDebugger.inspectorPost("method", {})).be.rejectedWith( PreconditionError, - { id: "core.debugger.not_enabled" } + { id: "core.debugger.not_enabled" }, ); }); @@ -264,12 +264,12 @@ describe("Test: Kuzzle Debugger", () => { should(kuzzleDebugger.notifyConnection).be.calledWith( "foo", "kuzzle-debugger-event", - { event: "my-event", result: { foo: "bar" } } + { event: "my-event", result: { foo: "bar" } }, ); should(kuzzleDebugger.notifyConnection).be.calledWith( "bar", "kuzzle-debugger-event", - { event: "my-event", result: { foo: "bar" } } + { event: "my-event", result: { foo: "bar" } }, ); }); }); diff --git a/test/core/network/accessLogger.test.js b/test/core/network/accessLogger.test.js index 7b25c689d3..535ab86644 100644 --- a/test/core/network/accessLogger.test.js +++ b/test/core/network/accessLogger.test.js @@ -64,7 +64,7 @@ describe("#AccessLogger", () => { beforeEach(() => { ({ AccessLogger } = mockRequire.reRequire( - "../../../lib/core/network/accessLogger" + "../../../lib/core/network/accessLogger", )); accessLogger = new AccessLogger(); }); @@ -123,7 +123,7 @@ describe("#AccessLogger", () => { should(accessLogger.isActive).be.false(); should(workerArgs).be.null(); should(kuzzle.log.error).calledWith( - 'Failed to initialize logger transport "ohnoes": unsupported transport. Skipped.' + 'Failed to initialize logger transport "ohnoes": unsupported transport. Skipped.', ); }); @@ -249,7 +249,7 @@ describe("#AccessLogger", () => { mockRequire("winston-syslog", winstonTransportSyslog); ({ AccessLoggerWorker } = mockRequire.reRequire( - "../../../lib/core/network/accessLogger" + "../../../lib/core/network/accessLogger", )); }); @@ -269,7 +269,7 @@ describe("#AccessLogger", () => { accessLogIpOffset: 0, }, }, - "-1" + "-1", ); }); @@ -307,7 +307,7 @@ describe("#AccessLogger", () => { for (let i = 0; i < 3; i++) { accessLoggerWorker.config.logs.transports.push( - Object.assign({}, accessLoggerWorker.config.logs.access) + Object.assign({}, accessLoggerWorker.config.logs.access), ); } @@ -396,7 +396,7 @@ describe("#AccessLogger", () => { accessLoggerWorker.config.logs.transports = [Object.assign({}, config)]; accessLoggerWorker.config.logs.transports.push( - Object.assign({}, config) + Object.assign({}, config), ); Object.assign(accessLoggerWorker.config.logs.transports[0], { @@ -481,7 +481,7 @@ describe("#AccessLogger", () => { { referer: "http://referer.com", "user-agent": "user agent", - } + }, ); const extra = { method: "METHOD", url: "url" }; @@ -494,7 +494,7 @@ describe("#AccessLogger", () => { token: { userId: "admin", }, - } + }, ); request.status = 444; @@ -507,7 +507,7 @@ describe("#AccessLogger", () => { should(accessLoggerWorker.logger.info) .be.calledOnce() .be.calledWithMatch( - /^1\.1\.1\.1 - admin \[\d\d\/[A-Z][a-z]{2}\/\d{4}:\d\d:\d\d:\d\d [+-]\d{4}] "METHOD url HTTP\/1\.1" 444 327 "http:\/\/referer.com" "user agent"$/ + /^1\.1\.1\.1 - admin \[\d\d\/[A-Z][a-z]{2}\/\d{4}:\d\d:\d\d:\d\d [+-]\d{4}] "METHOD url HTTP\/1\.1" 444 327 "http:\/\/referer.com" "user agent"$/, ); }); @@ -523,7 +523,7 @@ describe("#AccessLogger", () => { token: { userId: "foobar", }, - } + }, ); const connection = new ClientConnection("websocket", ["ip"]); @@ -532,7 +532,7 @@ describe("#AccessLogger", () => { should(accessLoggerWorker.logger.info) .be.calledOnce() .be.calledWithMatch( - /^ip - foobar \[\d{2}\/\w{3}\/\d{4}:\d{2}:\d{2}:\d{2} [+-]\d{4}] "DO \/controller\/action\/index\/collection WEBSOCKET" 102 339 - -$/ + /^ip - foobar \[\d{2}\/\w{3}\/\d{4}:\d{2}:\d{2}:\d{2} [+-]\d{4}] "DO \/controller\/action\/index\/collection WEBSOCKET" 102 339 - -$/, ); }); }); @@ -561,7 +561,7 @@ describe("#AccessLogger", () => { "connection", sinon.match.instanceOf(KuzzleRequest), "123", - "extra" + "extra", ); }); }); diff --git a/test/core/network/clientConnection.test.js b/test/core/network/clientConnection.test.js index 768c2bdc13..4732ae18f3 100644 --- a/test/core/network/clientConnection.test.js +++ b/test/core/network/clientConnection.test.js @@ -15,7 +15,7 @@ describe("core/network/clientConnection", () => { it("should throw if ips is not an array", () => { return should(() => new ClientConnection("protocol", "ips")).throw( TypeError, - { message: "Expected ips to be an Array, got string" } + { message: "Expected ips to be an Array, got string" }, ); }); diff --git a/test/core/network/entryPoint.test.js b/test/core/network/entryPoint.test.js index 831308ba2f..173cf96156 100644 --- a/test/core/network/entryPoint.test.js +++ b/test/core/network/entryPoint.test.js @@ -88,7 +88,7 @@ describe("lib/core/core/network/entryPoint", () => { return Promise.reject(err); } return result; - }) + }), ), resolve: sinon.stub().resolves(), timeout: sinon.stub().resolves(), @@ -131,7 +131,7 @@ describe("lib/core/core/network/entryPoint", () => { it("should throw if the event is unknown", () => { return should(() => entrypoint.dispatch("foo", {})).throw( - KuzzleInternalError + KuzzleInternalError, ); }); }); @@ -174,7 +174,7 @@ describe("lib/core/core/network/entryPoint", () => { entrypoint.execute({}, request, (response) => { should(response.status).eql(503); should(response.content.error).be.an.instanceof( - ServiceUnavailableError + ServiceUnavailableError, ); done(); @@ -226,7 +226,7 @@ describe("lib/core/core/network/entryPoint", () => { { id: "network.entrypoint.invalid_port", message: "Invalid network port number: foobar.", - } + }, ); }); @@ -273,7 +273,7 @@ describe("lib/core/core/network/entryPoint", () => { .be.calledOnce() .be.calledWith("channel", "connectionId"); should(kuzzle.log.error).be.calledWith( - "[join] protocol protocol failed: test" + "[join] protocol protocol failed: test", ); }); }); @@ -314,7 +314,7 @@ describe("lib/core/core/network/entryPoint", () => { .be.calledOnce() .be.calledWith("channel", "connectionId"); should(kuzzle.log.error).be.calledWith( - "[leave channel] protocol protocol failed: test" + "[leave channel] protocol protocol failed: test", ); }); }); @@ -367,7 +367,7 @@ describe("lib/core/core/network/entryPoint", () => { Rewired.__with__({ require: requireStub })(() => { const ep = new Rewired(); return ep.loadMoreProtocols(); - }) + }), ).rejectedWith(PluginImplementationError, { id: "plugin.manifest.cannot_load", }); diff --git a/test/core/network/httpRouter/httpRouter.test.js b/test/core/network/httpRouter/httpRouter.test.js index 87a3912ab1..7207872a01 100644 --- a/test/core/network/httpRouter/httpRouter.test.js +++ b/test/core/network/httpRouter/httpRouter.test.js @@ -34,42 +34,42 @@ describe("core/network/httpRouter", () => { it("should add a GET route when asked to", () => { router.get("/foo/bar", handler); should(router.routes.GET.subparts.foo.subparts.bar.handler).be.eql( - handler + handler, ); }); it("should add a POST route when asked to", () => { router.post("/foo/bar", handler); should(router.routes.POST.subparts.foo.subparts.bar.handler).be.eql( - handler + handler, ); }); it("should add a PUT route when asked to", () => { router.put("/foo/bar", handler); should(router.routes.PUT.subparts.foo.subparts.bar.handler).be.eql( - handler + handler, ); }); it("should add a PATCH route when asked to", () => { router.patch("/foo/bar", handler); should(router.routes.PATCH.subparts.foo.subparts.bar.handler).be.eql( - handler + handler, ); }); it("should add a DELETE route when asked to", () => { router.delete("/foo/bar", handler); should(router.routes.DELETE.subparts.foo.subparts.bar.handler).be.eql( - handler + handler, ); }); it("should add a HEAD route when asked to", () => { router.head("/foo/bar", handler); should(router.routes.HEAD.subparts.foo.subparts.bar.handler).be.eql( - handler + handler, ); }); @@ -245,7 +245,7 @@ describe("core/network/httpRouter", () => { should(apiRequest.id).match(httpMessage.requestId); should(apiRequest.input.body).match({ foo: "bar" }); should(apiRequest.input.headers["content-type"]).eql( - "application/json" + "application/json", ); done(); } catch (e) { @@ -272,7 +272,7 @@ describe("core/network/httpRouter", () => { should(apiRequest.id).match(httpMessage.requestId); should(apiRequest.input.body).match({ foo: "bar" }); should(apiRequest.input.headers["content-type"]).eql( - "application/json" + "application/json", ); should(apiRequest.input.args.bar).eql("hello"); should(apiRequest.input.args.baz).eql("world"); @@ -301,7 +301,7 @@ describe("core/network/httpRouter", () => { should(apiRequest.id).match(httpMessage.requestId); should(apiRequest.input.body).match({ foo: "bar" }); should(apiRequest.input.headers["content-type"]).eql( - "application/json; charset=utf-8" + "application/json; charset=utf-8", ); should(apiRequest.input.args.bar).eql("hello"); should(apiRequest.input.args.baz).eql("%world"); @@ -349,7 +349,7 @@ describe("core/network/httpRouter", () => { .be.calledOnce() .be.calledWith("http:options", sinon.match.instanceOf(Request)); should(kuzzleMock.pipe.firstCall.args[1].input.headers.foo).eql( - "bar" + "bar", ); done(); @@ -519,15 +519,15 @@ describe("core/network/httpRouter", () => { mockrequire( "../../../../lib/core/network/httpRouter/routeHandler", - routeHandlerStub + routeHandlerStub, ); mockrequire.reRequire( - "../../../../lib/core/network/httpRouter/routePart" + "../../../../lib/core/network/httpRouter/routePart", ); const MockRouter = mockrequire.reRequire( - "../../../../lib/core/network/httpRouter" + "../../../../lib/core/network/httpRouter", ); router = new MockRouter(); diff --git a/test/core/network/protocols/http.test.js b/test/core/network/protocols/http.test.js index afcb80675c..627888f33b 100644 --- a/test/core/network/protocols/http.test.js +++ b/test/core/network/protocols/http.test.js @@ -26,7 +26,7 @@ describe("core/network/protocols/http", () => { before(() => { mockRequire("uWebSockets.js", uWSMock); HttpWs = mockRequire.reRequire( - "../../../../lib/core/network/protocols/httpwsProtocol" + "../../../../lib/core/network/protocols/httpwsProtocol", ); }); @@ -80,7 +80,7 @@ describe("core/network/protocols/http", () => { should(httpWs.server.any).not.called(); should(kuzzle.log.warn).calledWith( - "[http] no configuration found for http: disabling it" + "[http] no configuration found for http: disabling it", ); }); }); @@ -143,26 +143,26 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).calledWithMatch( Buffer.from("Access-Control-Allow-Headers"), - Buffer.from(kuzzle.config.http.accessControlAllowHeaders) + Buffer.from(kuzzle.config.http.accessControlAllowHeaders), ); should(response.writeHeader).calledWithMatch( Buffer.from("Access-Control-Allow-Methods"), - Buffer.from(kuzzle.config.http.accessControlAllowMethods) + Buffer.from(kuzzle.config.http.accessControlAllowMethods), ); should(response.writeHeader).calledWithMatch( Buffer.from("Access-Control-Allow-Origin"), - Buffer.from("foo") + Buffer.from("foo"), ); should(response.writeHeader).calledWithMatch( Buffer.from("Content-Type"), - Buffer.from("application/json") + Buffer.from("application/json"), ); should(response.writeHeader).not.be.calledWithMatch( - Buffer.from("Content-Length") + Buffer.from("Content-Length"), ); should(response.writeHeader.calledBefore(response.end)); @@ -257,7 +257,7 @@ describe("core/network/protocols/http", () => { request, response, new HttpStream(stream, { totalBytes: 5 }), - message + message, ); stream.write("Hello"); @@ -265,7 +265,7 @@ describe("core/network/protocols/http", () => { should(response.getWriteOffset).be.calledOnce(); should(response.tryEnd).be.calledWithMatch( Buffer.from("Hello").buffer.slice(0, 5), - 5 + 5, ); }); @@ -280,7 +280,7 @@ describe("core/network/protocols/http", () => { stream.end(); should(response.getWriteOffset).be.calledOnce(); should(response.write).be.calledWithMatch( - Buffer.from("Hello").buffer.slice(0, 5) + Buffer.from("Hello").buffer.slice(0, 5), ); }); @@ -296,7 +296,7 @@ describe("core/network/protocols/http", () => { request, response, new HttpStream(stream, { totalBytes: 5 }), - message + message, ); stream.write("Hello"); @@ -392,7 +392,7 @@ describe("core/network/protocols/http", () => { }); await httpWs.server._httpResponse._onData( - Buffer.from('{"ahah":"i am a h4ck3r"}') + Buffer.from('{"ahah":"i am a h4ck3r"}'), ); should(entryPoint.newConnection).not.called(); @@ -530,9 +530,9 @@ describe("core/network/protocols/http", () => { await httpWs.server._httpResponse._onData( Buffer.from( - '--foo\r\nContent-Disposition: form-data; name="t"\r\n\r\nvalue\r\n--foo\r\nContent-Disposition: form-data; name="f"; filename="filename"\r\nContent-Type: application/octet-stream\r\n\r\nfoobar\r\n--foo--' + '--foo\r\nContent-Disposition: form-data; name="t"\r\n\r\nvalue\r\n--foo\r\nContent-Disposition: form-data; name="f"; filename="filename"\r\nContent-Type: application/octet-stream\r\n\r\nfoobar\r\n--foo--', ), - true + true, ); should(httpWs.httpProcessRequest) @@ -558,7 +558,7 @@ describe("core/network/protocols/http", () => { await httpWs.server._httpResponse._onData( Buffer.from("--foo\r\nContent-Disposition: form-data; --foo--"), - true + true, ); should(httpWs.httpProcessRequest) @@ -577,9 +577,9 @@ describe("core/network/protocols/http", () => { await httpWs.server._httpResponse._onData( Buffer.from( - '--foo\r\nContent-Disposition: form-data; name="t"\r\n\r\nvalue\r\n--foo\r\nContent-Disposition: form-data; name="f"; filename="filename"\r\nContent-Type: application/octet-stream\r\n\r\nfoobar\r\n--foo--' + '--foo\r\nContent-Disposition: form-data; name="t"\r\n\r\nvalue\r\n--foo\r\nContent-Disposition: form-data; name="f"; filename="filename"\r\nContent-Type: application/octet-stream\r\n\r\nfoobar\r\n--foo--', ), - true + true, ); should(httpWs.httpSendError) @@ -598,7 +598,7 @@ describe("core/network/protocols/http", () => { await httpWs.server._httpResponse._onData( Buffer.from("foo=bar&baz=qux"), - true + true, ); should(httpWs.httpProcessRequest) @@ -619,7 +619,7 @@ describe("core/network/protocols/http", () => { httpWs.server._httpOnMessage("get", "/", "", { origin: "foo" }); await httpWs.server._httpResponse._onData( Buffer.from('{"controller":"foo","action":"bar"}'), - true + true, ); should(entryPoint.newConnection).calledOnce(); @@ -635,27 +635,27 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).calledWithMatch( Buffer.from("Access-Control-Allow-Headers"), - Buffer.from(kuzzle.config.http.accessControlAllowHeaders) + Buffer.from(kuzzle.config.http.accessControlAllowHeaders), ); should(response.writeHeader).calledWithMatch( Buffer.from("Access-Control-Allow-Methods"), - Buffer.from(kuzzle.config.http.accessControlAllowMethods) + Buffer.from(kuzzle.config.http.accessControlAllowMethods), ); should(response.writeHeader).calledWithMatch( Buffer.from("Access-Control-Allow-Origin"), - Buffer.from("foo") + Buffer.from("foo"), ); should(response.writeHeader).calledWithMatch( Buffer.from("Content-Type"), - Buffer.from("application/json") + Buffer.from("application/json"), ); should(response.writeHeader).calledWithMatch( Buffer.from("Content-Encoding"), - Buffer.from("identity") + Buffer.from("identity"), ); should(response.writeHeader.calledBefore(response.tryEnd)); @@ -685,7 +685,7 @@ describe("core/network/protocols/http", () => { httpWs.server._httpOnMessage("get", "/", "", { origin: "foobar" }); await httpWs.server._httpResponse._onData( Buffer.from('{"controller":"foo","action":"bar"}'), - true + true, ); should(entryPoint.newConnection).calledOnce(); @@ -701,47 +701,47 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).not.be.calledWithMatch( Buffer.from("Access-Control-Allow-Headers"), - Buffer.from(kuzzle.config.http.accessControlAllowHeaders) + Buffer.from(kuzzle.config.http.accessControlAllowHeaders), ); should(response.writeHeader).be.calledWithMatch( Buffer.from("Access-Control-Allow-Headers"), - Buffer.from("foo") + Buffer.from("foo"), ); should(response.writeHeader).not.be.calledWithMatch( Buffer.from("Access-Control-Allow-Methods"), - Buffer.from(kuzzle.config.http.accessControlAllowMethods) + Buffer.from(kuzzle.config.http.accessControlAllowMethods), ); should(response.writeHeader).be.calledWithMatch( Buffer.from("Access-Control-Allow-Methods"), - Buffer.from("foo") + Buffer.from("foo"), ); should(response.writeHeader).not.be.calledWithMatch( Buffer.from("Access-Control-Allow-Origin"), - Buffer.from("foobar") + Buffer.from("foobar"), ); should(response.writeHeader).not.be.calledWithMatch( Buffer.from("Vary"), - Buffer.from("Origin") + Buffer.from("Origin"), ); should(response.writeHeader).be.calledWithMatch( Buffer.from("Access-Control-Allow-Origin"), - Buffer.from("foo") + Buffer.from("foo"), ); should(response.writeHeader).not.be.calledWithMatch( Buffer.from("Content-Type"), - Buffer.from("application/json") + Buffer.from("application/json"), ); should(response.writeHeader).be.calledWithMatch( Buffer.from("Content-Type"), - Buffer.from("foo") + Buffer.from("foo"), ); should(response.writeHeader.calledBefore(response.tryEnd)); @@ -768,7 +768,7 @@ describe("core/network/protocols/http", () => { httpWs.server._httpOnMessage("get", "/", "", { origin: "foobar" }); await httpWs.server._httpResponse._onData( Buffer.from('{"controller":"foo","action":"bar"}'), - true + true, ); const response = httpWs.server._httpResponse; @@ -782,7 +782,7 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).be.calledWithMatch( Buffer.from("X-Kuzzle-Request-Id"), - Buffer.from("my-custom-id-42") + Buffer.from("my-custom-id-42"), ); }); @@ -817,7 +817,7 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).calledWithMatch( Buffer.from("Content-Encoding"), - Buffer.from("gzip") + Buffer.from("gzip"), ); }); @@ -852,7 +852,7 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).calledWithMatch( Buffer.from("Content-Encoding"), - Buffer.from("deflate") + Buffer.from("deflate"), ); }); @@ -887,7 +887,7 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).calledWithMatch( Buffer.from("Content-Encoding"), - Buffer.from("gzip") + Buffer.from("gzip"), ); }); @@ -922,7 +922,7 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).calledWithMatch( Buffer.from("Content-Encoding"), - Buffer.from("deflate") + Buffer.from("deflate"), ); }); @@ -954,7 +954,7 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).calledWithMatch( Buffer.from("Content-Encoding"), - Buffer.from("identity") + Buffer.from("identity"), ); }); @@ -963,7 +963,7 @@ describe("core/network/protocols/http", () => { gzip: sinon.stub().yields(new Error("foo")), }); HttpWs = mockRequire.reRequire( - "../../../../lib/core/network/protocols/httpwsProtocol" + "../../../../lib/core/network/protocols/httpwsProtocol", ); const protocol = new HttpWs(); await protocol.init(entryPoint); @@ -996,12 +996,12 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).calledWithMatch( Buffer.from("Content-Encoding"), - Buffer.from("identity") + Buffer.from("identity"), ); } finally { mockRequire.stop("zlib"); HttpWs = mockRequire.reRequire( - "../../../../lib/core/network/protocols/httpwsProtocol" + "../../../../lib/core/network/protocols/httpwsProtocol", ); clearInterval(protocol.nowInterval); } @@ -1012,7 +1012,7 @@ describe("core/network/protocols/http", () => { deflate: sinon.stub().yields(new Error("foo")), }); HttpWs = mockRequire.reRequire( - "../../../../lib/core/network/protocols/httpwsProtocol" + "../../../../lib/core/network/protocols/httpwsProtocol", ); const protocol = new HttpWs(); await protocol.init(entryPoint); @@ -1045,12 +1045,12 @@ describe("core/network/protocols/http", () => { should(response.writeHeader).calledWithMatch( Buffer.from("Content-Encoding"), - Buffer.from("identity") + Buffer.from("identity"), ); } finally { mockRequire.stop("zlib"); HttpWs = mockRequire.reRequire( - "../../../../lib/core/network/protocols/httpwsProtocol" + "../../../../lib/core/network/protocols/httpwsProtocol", ); clearInterval(protocol.nowInterval); } @@ -1124,7 +1124,7 @@ describe("core/network/protocols/http", () => { should(response.tryEnd).calledOnce(); should(response.tryEnd.firstCall.args[0].toString()).eql( - JSON.stringify(Buffer.from("foobar")) + JSON.stringify(Buffer.from("foobar")), ); }); diff --git a/test/core/network/protocols/internal.test.js b/test/core/network/protocols/internal.test.js index aecf43b4ba..6a27acbc10 100644 --- a/test/core/network/protocols/internal.test.js +++ b/test/core/network/protocols/internal.test.js @@ -34,7 +34,7 @@ describe("/lib/core/network/protocols/internalProtocol", () => { should(kuzzle.onAsk).be.calledOnce(); should(kuzzle.onAsk.getCall(0).args[0]).be.eql( - "core:network:internal:connectionId:get" + "core:network:internal:connectionId:get", ); }); }); diff --git a/test/core/network/protocols/mqtt.test.js b/test/core/network/protocols/mqtt.test.js index e4f02b0ca6..3b73da6006 100644 --- a/test/core/network/protocols/mqtt.test.js +++ b/test/core/network/protocols/mqtt.test.js @@ -49,7 +49,7 @@ describe("/lib/core/network/entryPoint/protocols/mqttProtocol", () => { mockrequire("aedes", { Server: AedesMock }); MqttProtocol = mockrequire.reRequire( - "../../../../lib/core/network/protocols/mqttProtocol" + "../../../../lib/core/network/protocols/mqttProtocol", ); }); @@ -310,7 +310,7 @@ describe("/lib/core/network/entryPoint/protocols/mqttProtocol", () => { topic: protocol.config.requestTopic, payload: "payload", }, - new FakeClient(null) + new FakeClient(null), ); should(entrypoint.execute).have.callCount(0); @@ -322,7 +322,7 @@ describe("/lib/core/network/entryPoint/protocols/mqttProtocol", () => { topic: protocol.config.requestTopic, payload: "payload", }, - fakeClient + fakeClient, ); should(entrypoint.execute).have.callCount(0); @@ -343,7 +343,7 @@ describe("/lib/core/network/entryPoint/protocols/mqttProtocol", () => { payload: Buffer.from(JSON.stringify({ foo: "bar" })), topic: protocol.config.requestTopic, }, - fakeClient + fakeClient, ); should(entrypoint.execute).be.calledOnce(); @@ -386,14 +386,14 @@ describe("/lib/core/network/entryPoint/protocols/mqttProtocol", () => { payload: Buffer.from("invalid"), topic: protocol.config.requestTopic, }, - client + client, ); const matcher = errorMatcher.fromMessage( "network", "mqtt", "unexpected_error", - "Unexpected token i in JSON at position 0" + "Unexpected token i in JSON at position 0", ); should(protocol._respond) @@ -419,7 +419,7 @@ describe("/lib/core/network/entryPoint/protocols/mqttProtocol", () => { payload: Buffer.from(JSON.stringify({ requestId: 42 })), topic: protocol.config.requestTopic, }, - fakeClient + fakeClient, ); should(protocol._respond).be.calledOnce().be.calledWith(fakeClient); diff --git a/test/core/network/protocols/websocket.test.js b/test/core/network/protocols/websocket.test.js index 24f4aadeb3..2e81169715 100644 --- a/test/core/network/protocols/websocket.test.js +++ b/test/core/network/protocols/websocket.test.js @@ -25,7 +25,7 @@ describe("core/network/protocols/websocket", () => { before(() => { mockRequire("uWebSockets.js", uWSMock); HttpWs = mockRequire.reRequire( - "../../../../lib/core/network/protocols/httpwsProtocol" + "../../../../lib/core/network/protocols/httpwsProtocol", ); }); @@ -71,7 +71,7 @@ describe("core/network/protocols/websocket", () => { should(httpWs.server.ws).not.called(); should(kuzzle.log.warn).calledWith( - "[websocket] no configuration found for websocket: disabling it" + "[websocket] no configuration found for websocket: disabling it", ); }); @@ -87,7 +87,7 @@ describe("core/network/protocols/websocket", () => { }); should(kuzzle.log.warn).calledWith( - '[websocket] The "idleTimeout" parameter can neither be deactivated or be set with a value lower than 1000. Defaulted to 60000.' + '[websocket] The "idleTimeout" parameter can neither be deactivated or be set with a value lower than 1000. Defaulted to 60000.', ); } }); @@ -102,7 +102,7 @@ describe("core/network/protocols/websocket", () => { await httpWs.init(entryPoint); should(kuzzle.log.warn).calledWith( - '[websocket] The "heartbeat" parameter has been deprecated and is now ignored. The "idleTimeout" parameter should now be configured instead.' + '[websocket] The "heartbeat" parameter has been deprecated and is now ignored. The "idleTimeout" parameter should now be configured instead.', ); }); @@ -178,7 +178,7 @@ describe("core/network/protocols/websocket", () => { "websocket-key", "websocket-protocol", "websocket-extension", - context + context, ); }); }); @@ -202,12 +202,12 @@ describe("core/network/protocols/websocket", () => { should(httpWs.connectionBySocket).have.value( httpWs.server._wsSocket, - clientConnection + clientConnection, ); should(httpWs.socketByConnectionId).have.value( clientConnection.id, - httpWs.server._wsSocket + httpWs.server._wsSocket, ); should(httpWs.backpressureBuffer).have.value(httpWs.server._wsSocket, []); @@ -236,20 +236,20 @@ describe("core/network/protocols/websocket", () => { should(httpWs.connectionBySocket).have.value( openedSocket, - openedClientConnection + openedClientConnection, ); should(httpWs.connectionBySocket).not.have.value( closedSocket, - closedClientConnection + closedClientConnection, ); should(httpWs.socketByConnectionId).have.value( openedClientConnection.id, - openedSocket + openedSocket, ); should(httpWs.socketByConnectionId).not.have.value( closedClientConnection.id, - closedSocket + closedSocket, ); should(httpWs.backpressureBuffer).have.value(openedSocket, []); @@ -377,7 +377,7 @@ describe("core/network/protocols/websocket", () => { should(payload.toString()).eql('{"p":2}'); await httpWs.server._wsOnMessage( - '{"p":1, "controller": "foo", "action":"bar"}' + '{"p":1, "controller": "foo", "action":"bar"}', ); should(entryPoint.execute).calledOnce(); @@ -444,7 +444,7 @@ describe("core/network/protocols/websocket", () => { .calledOnce() .calledWithMatch( 1011, - Buffer.from("too much backpressure: client is too slow") + Buffer.from("too much backpressure: client is too slow"), ); }); @@ -485,7 +485,7 @@ describe("core/network/protocols/websocket", () => { should(socket.end).calledWithMatch( 1011, - Buffer.from("Connection closed by remote host") + Buffer.from("Connection closed by remote host"), ); }); @@ -563,7 +563,7 @@ describe("core/network/protocols/websocket", () => { for (const channel of channels) { should(socket.send).calledWithMatch( - Buffer.from(JSON.stringify({ foo: "bar", room: channel })) + Buffer.from(JSON.stringify({ foo: "bar", room: channel })), ); } }); @@ -588,7 +588,7 @@ describe("core/network/protocols/websocket", () => { for (const channel of channels) { should(httpWs.server.publish).calledWithMatch( `realtime/${channel}`, - Buffer.from(JSON.stringify({ foo: "bar", room: channel })) + Buffer.from(JSON.stringify({ foo: "bar", room: channel })), ); } }); diff --git a/test/core/network/router/httpRequest.test.js b/test/core/network/router/httpRequest.test.js index ed80cfc013..0c5faa33cc 100644 --- a/test/core/network/router/httpRequest.test.js +++ b/test/core/network/router/httpRequest.test.js @@ -40,7 +40,7 @@ describe("Test: router.httpRequest", () => { undefined, { origin: "foobar", - } + }, ); const httpMessage = new HttpMessage(connection, req); @@ -50,10 +50,10 @@ describe("Test: router.httpRequest", () => { should(request.input.action).be.eql("getrange"); should(request.response.requestId).be.eql(httpMessage.requestId); should(request.response.headers["content-type"]).be.eql( - "application/json" + "application/json", ); should(request.response.headers["Access-Control-Allow-Origin"]).be.eql( - "foobar" + "foobar", ); should(request.response.status).be.eql(1234); should(kuzzle.pipe).be.calledOnce(); @@ -77,7 +77,7 @@ describe("Test: router.httpRequest", () => { should(request.input.action).be.eql("count"); should(request.response.requestId).be.eql(httpMessage.requestId); should(request.response.headers["content-type"]).be.eql( - "application/json" + "application/json", ); should(request.response.status).be.eql(1234); should(kuzzle.pipe).be.calledOnce(); @@ -101,7 +101,7 @@ describe("Test: router.httpRequest", () => { should(request.input.action).be.eql("updateSelf"); should(request.response.requestId).be.eql(httpMessage.requestId); should(request.response.headers["content-type"]).be.eql( - "application/json" + "application/json", ); should(request.response.status).be.eql(1234); should(kuzzle.pipe).be.calledOnce(); @@ -124,7 +124,7 @@ describe("Test: router.httpRequest", () => { should(request.input.action).be.eql("delete"); should(request.response.requestId).be.eql(httpMessage.requestId); should(request.response.headers["content-type"]).be.eql( - "application/json" + "application/json", ); should(request.response.status).be.eql(1234); should(kuzzle.pipe).be.calledOnce(); @@ -147,7 +147,7 @@ describe("Test: router.httpRequest", () => { should(request.input.action).be.eql("info"); should(request.response.requestId).be.eql(httpMessage.requestId); should(request.response.headers["content-type"]).be.eql( - "application/json" + "application/json", ); should(request.response.status).be.eql(1234); done(); @@ -167,7 +167,7 @@ describe("Test: router.httpRequest", () => { should(request.input.action).be.eql("bar"); should(request.response.requestId).be.eql(httpMessage.requestId); should(request.response.headers["content-type"]).be.eql( - "application/json" + "application/json", ); should(request.response.status).be.eql(1234); done(); @@ -185,11 +185,11 @@ describe("Test: router.httpRequest", () => { try { should(result.response.requestId).be.eql(httpMessage.requestId); should(result.response.headers["content-type"]).be.eql( - "application/json" + "application/json", ); should(result.response.status).be.eql(404); should(result.response.error.message).be.eql( - "API URL not found: /a/b/c/d." + "API URL not found: /a/b/c/d.", ); done(); } catch (e) { diff --git a/test/core/network/router/router.test.js b/test/core/network/router/router.test.js index 8ee19608ee..0318bb2120 100644 --- a/test/core/network/router/router.test.js +++ b/test/core/network/router/router.test.js @@ -139,10 +139,10 @@ describe("Test: router", () => { it("should return the metrics object", () => { // Fake connections router.newConnection( - new RequestContext({ connection: { id: "foo", protocol: "bar" } }) + new RequestContext({ connection: { id: "foo", protocol: "bar" } }), ); router.newConnection( - new RequestContext({ connection: { id: "foo2", protocol: "bar" } }) + new RequestContext({ connection: { id: "foo2", protocol: "bar" } }), ); should(router.metrics()).match({ diff --git a/test/core/plugin/context/context.test.js b/test/core/plugin/context/context.test.js index 4ee361f84e..1e998e2bf3 100644 --- a/test/core/plugin/context/context.test.js +++ b/test/core/plugin/context/context.test.js @@ -40,7 +40,7 @@ describe("Plugin Context", () => { beforeEach(() => { mockrequire("../../../../lib/util/mutex", { Mutex: MutexMock }); ({ PluginContext } = mockrequire.reRequire( - `${root}/lib/core/plugin/pluginContext` + `${root}/lib/core/plugin/pluginContext`, )); kuzzle = new KuzzleMock(); context = new PluginContext("pluginName"); @@ -72,7 +72,7 @@ describe("Plugin Context", () => { should(new context.constructors.Koncorde()).be.instanceOf(Koncorde); should( - new context.constructors.Request(new Request({}), {}) + new context.constructors.Request(new Request({}), {}), ).be.instanceOf(KuzzleRequest); should(new context.constructors.Mutex()).be.instanceOf(Mutex); @@ -110,7 +110,7 @@ describe("Plugin Context", () => { const storageClient = new context.constructors.ESClient(); should(storageClient.connectionPool.connections[0].url.origin).be.eql( - kuzzle.config.services.storageEngine.client.node + kuzzle.config.services.storageEngine.client.node, ); }); }); @@ -142,13 +142,13 @@ describe("Plugin Context", () => { { protocol: "protocol", connectionId: "connectionId", - } + }, ), pluginRequest = new context.constructors.Request(request, {}); should(pluginRequest.context.protocol).be.eql(request.context.protocol); should(pluginRequest.context.connectionId).be.eql( - request.context.connectionId + request.context.connectionId, ); should(pluginRequest.result).be.null(); should(pluginRequest.error).be.null(); @@ -157,12 +157,12 @@ describe("Plugin Context", () => { should(pluginRequest.input.controller).be.null(); should(pluginRequest.input.jwt).be.eql(request.input.jwt); should(pluginRequest.input.args.foobar).be.eql( - request.input.args.foobar + request.input.args.foobar, ); should(pluginRequest.input.args._id).be.eql(request.input.args._id); should(pluginRequest.input.args.index).be.eql(request.input.args.index); should(pluginRequest.input.args.collection).be.eql( - request.input.args.collection + request.input.args.collection, ); should(pluginRequest.input.volatile).match({ foo: "bar" }); }); @@ -186,7 +186,7 @@ describe("Plugin Context", () => { { protocol: "protocol", connectionId: "connectionId", - } + }, ), pluginRequest = new context.constructors.Request(request, { action: "pluginAction", @@ -301,10 +301,10 @@ describe("Plugin Context", () => { const validation = context.accessors.validation; should(validation.addType).be.eql( - kuzzle.validation.addType.bind(kuzzle.validation) + kuzzle.validation.addType.bind(kuzzle.validation), ); should(validation.validate).be.eql( - kuzzle.validation.validate.bind(kuzzle.validation) + kuzzle.validation.validate.bind(kuzzle.validation), ); }); @@ -367,14 +367,14 @@ describe("Plugin Context", () => { }, { connectionId: "superid", - } + }, ); await context.accessors.subscription.register( customRequest.context.connection.id, customRequest.input.index, customRequest.input.collection, - customRequest.input.body + customRequest.input.body, ); should(kuzzle.ask).be.calledWith( @@ -390,7 +390,7 @@ describe("Plugin Context", () => { collection: customRequest.input.collection, index: customRequest.input.index, }, - }) + }), ); }); @@ -398,14 +398,14 @@ describe("Plugin Context", () => { await context.accessors.subscription.unregister( "connectionId", "roomId", - false + false, ); should(kuzzle.ask).be.calledWithExactly( "core:realtime:unsubscribe", "connectionId", "roomId", - false + false, ); }); }); @@ -428,7 +428,7 @@ describe("Plugin Context", () => { should(result).be.eql("pipe chain result"); should(kuzzle.pipe).be.calledWithExactly( `plugin-pluginName:${eventName}`, - payload + payload, ); }); }); @@ -437,7 +437,7 @@ describe("Plugin Context", () => { it("should call the callback with a result if everything went well", (done) => { const request = new Request( { requestId: "request" }, - { connectionId: "connectionid" } + { connectionId: "connectionid" }, ), result = { foo: "bar" }, callback = sinon.spy((err, res) => { @@ -461,7 +461,7 @@ describe("Plugin Context", () => { it("should resolve a Promise with a result if everything went well", () => { const request = new Request( { requestId: "request" }, - { connectionId: "connectionid" } + { connectionId: "connectionid" }, ), result = { foo: "bar" }; @@ -481,7 +481,7 @@ describe("Plugin Context", () => { it("should call the callback with an error if something went wrong", (done) => { const request = new Request( { body: { some: "request" } }, - { connectionId: "connectionid" } + { connectionId: "connectionid" }, ), error = new Error("error"), callback = sinon.spy((err, res) => { @@ -504,7 +504,7 @@ describe("Plugin Context", () => { it("should reject a Promise with an error if something went wrong", () => { const request = new Request( { body: { some: "request" } }, - { connectionId: "connectionid" } + { connectionId: "connectionid" }, ), error = new Error("error"); @@ -523,7 +523,7 @@ describe("Plugin Context", () => { should(callback).be.calledOnce(); should(err).be.instanceOf(PluginImplementationError); should(err.message).startWith( - "Invalid argument: a Request object must be supplied" + "Invalid argument: a Request object must be supplied", ); should(res).be.undefined(); done(); @@ -537,13 +537,13 @@ describe("Plugin Context", () => { it("should reject if no Request object is provided", () => { return should(context.accessors.execute({})).be.rejectedWith( - /Invalid argument: a Request object must be supplied/ + /Invalid argument: a Request object must be supplied/, ); }); it("should reject if callback argument is not a function", () => { return should( - context.accessors.execute({ requestId: "request" }, "foo") + context.accessors.execute({ requestId: "request" }, "foo"), ).be.rejectedWith({ message: /^Invalid argument: Expected callback to be a function, received "string"/, @@ -558,8 +558,8 @@ describe("Plugin Context", () => { new Request({ controller: "realtime", action: "subscribe", - }) - ) + }), + ), ).be.rejectedWith(PluginImplementationError, { id: "plugin.context.unavailable_realtime", }); @@ -570,8 +570,8 @@ describe("Plugin Context", () => { new Request({ controller: "realtime", action: "unsubscribe", - }) - ) + }), + ), ).be.rejectedWith(PluginImplementationError, { id: "plugin.context.unavailable_realtime", }); @@ -594,7 +594,7 @@ describe("Plugin Context", () => { should(kuzzle.pluginsManager.registerStrategy).calledWith( "pluginName", "foo", - mockedStrategy + mockedStrategy, ); should(kuzzle.pipe).calledWith("core:auth:strategyAdded", { pluginName: "pluginName", @@ -621,7 +621,7 @@ describe("Plugin Context", () => { it("should throw if no authenticator is provided", () => { return should( - context.accessors.strategies.add("foo", null) + context.accessors.strategies.add("foo", null), ).rejectedWith(PluginImplementationError, { message: '[pluginName] Strategy foo: dynamic strategy registration can only be done using an "authenticator" option (see https://tinyurl.com/y7boozbk).\nThis is probably not a Kuzzle error, but a problem with a plugin implementation.', @@ -636,7 +636,7 @@ describe("Plugin Context", () => { return result.then(() => { should(kuzzle.pluginsManager.unregisterStrategy).calledWith( "pluginName", - "foo" + "foo", ); should(kuzzle.pipe).calledWith("core:auth:strategyRemoved", { pluginName: "pluginName", diff --git a/test/core/plugin/context/privilegedContext.test.js b/test/core/plugin/context/privilegedContext.test.js index 6651d59b81..09621cd8e4 100644 --- a/test/core/plugin/context/privilegedContext.test.js +++ b/test/core/plugin/context/privilegedContext.test.js @@ -10,7 +10,7 @@ describe("Privileged Plugin Context", () => { beforeEach(() => { mockrequire.reRequire("../../../../lib/core/plugin/pluginContext"); PrivilegedPluginContext = mockrequire.reRequire( - "../../../../lib/core/plugin/privilegedContext" + "../../../../lib/core/plugin/privilegedContext", ); }); diff --git a/test/core/plugin/plugin.test.js b/test/core/plugin/plugin.test.js index a3513e5d46..cf214a82f1 100644 --- a/test/core/plugin/plugin.test.js +++ b/test/core/plugin/plugin.test.js @@ -91,7 +91,7 @@ describe("Plugin", () => { plugin.init("lambda-core"); should(plugin._context.constructor.name).be.eql( - "PrivilegedPluginContext" + "PrivilegedPluginContext", ); }); @@ -224,7 +224,7 @@ describe("Plugin", () => { should(pluginErrors).have.ownProperty(plugin.manifest.name); should(pluginErrors[plugin.manifest.name]).have.ownProperty("errors"); should(pluginErrors[plugin.manifest.name].errors).be.deepEqual( - manifest.errors + manifest.errors, ); }); diff --git a/test/core/plugin/pluginManifest.test.js b/test/core/plugin/pluginManifest.test.js index c459d66a88..ab03f67c38 100644 --- a/test/core/plugin/pluginManifest.test.js +++ b/test/core/plugin/pluginManifest.test.js @@ -21,7 +21,7 @@ describe("Plugins manifest class", () => { new KuzzleMock(); mockrequire( "../../../lib/core/shared/abstractManifest", - AbstractManifestStub + AbstractManifestStub, ); Manifest = mockrequire.reRequire("../../../lib/core/plugin/pluginManifest"); manifest = new Manifest(pluginPath); diff --git a/test/core/plugin/pluginRepository.test.js b/test/core/plugin/pluginRepository.test.js index b9cb02174d..f05b0b3ca6 100644 --- a/test/core/plugin/pluginRepository.test.js +++ b/test/core/plugin/pluginRepository.test.js @@ -44,7 +44,7 @@ describe("core/plugin/pluginRepository", () => { delete copy._id; should(pluginRepository.serializeToDatabase(someObject)).be.deepEqual( - copy + copy, ); }); }); @@ -59,7 +59,7 @@ describe("core/plugin/pluginRepository", () => { should(args[1]).be.exactly(pluginRepository.index); should(args[2]).be.exactly(someCollection); should(args[3]).be.deepEqual( - pluginRepository.serializeToDatabase(someObject) + pluginRepository.serializeToDatabase(someObject), ); should(args[4]).match({ id: "someId" }); }); @@ -70,14 +70,14 @@ describe("core/plugin/pluginRepository", () => { await pluginRepository.createOrReplace(someObject); const args = kuzzle.ask.withArgs( - "core:storage:private:document:createOrReplace" + "core:storage:private:document:createOrReplace", ).firstCall.args; should(args[1]).be.exactly(pluginRepository.index); should(args[2]).be.exactly(someCollection); should(args[3]).be.exactly("someId"); should(args[4]).be.deepEqual( - pluginRepository.serializeToDatabase(someObject) + pluginRepository.serializeToDatabase(someObject), ); }); }); @@ -93,7 +93,7 @@ describe("core/plugin/pluginRepository", () => { should(args[2]).be.exactly(someCollection); should(args[3]).be.exactly("someId"); should(args[4]).be.deepEqual( - pluginRepository.serializeToDatabase(someObject) + pluginRepository.serializeToDatabase(someObject), ); }); }); @@ -109,7 +109,7 @@ describe("core/plugin/pluginRepository", () => { should(args[2]).be.exactly(someCollection); should(args[3]).be.exactly("someId"); should(args[4]).be.deepEqual( - pluginRepository.serializeToDatabase(someObject) + pluginRepository.serializeToDatabase(someObject), ); }); }); diff --git a/test/core/plugin/pluginsManager.test.js b/test/core/plugin/pluginsManager.test.js index e1b79d75be..7477ed798c 100644 --- a/test/core/plugin/pluginsManager.test.js +++ b/test/core/plugin/pluginsManager.test.js @@ -41,7 +41,7 @@ describe("Plugin", () => { mockrequire.reRequire("../../../lib/core/plugin/pluginContext"); mockrequire.reRequire("../../../lib/core/plugin/privilegedContext"); PluginsManager = mockrequire.reRequire( - "../../../lib/core/plugin/pluginsManager" + "../../../lib/core/plugin/pluginsManager", ); pluginsManager = new PluginsManager(); @@ -118,7 +118,7 @@ describe("Plugin", () => { new Map([ [loggerPlugin.name, loggerPlugin], [localPlugin.name, localPlugin], - ]) + ]), ); pluginsManager._plugins.set(plugin.name, plugin); pluginsManager.config.common.failsafeMode = true; @@ -137,7 +137,7 @@ describe("Plugin", () => { new Map([ [otherPlugin.name, otherPlugin], [application.name, application], - ]) + ]), ); pluginsManager._plugins.set(plugin.name, plugin); @@ -177,7 +177,7 @@ describe("Plugin", () => { should(plugin.instance.init).be.calledWith(plugin.config, plugin.context); should(application.instance.init).be.calledWith( application.config, - application.context + application.context, ); should(plugin.initCalled).be.true(); should(application.initCalled).be.true(); @@ -386,10 +386,10 @@ describe("Plugin", () => { pluginsManager._initControllers(plugin); should(pluginsManager.controllers.get("test-plugin/foo")).be.instanceof( - BaseController + BaseController, ); should( - pluginsManager.controllers.get("test-plugin/foo").actionName + pluginsManager.controllers.get("test-plugin/foo").actionName, ).be.eql(plugin.instance.functionName.bind(plugin.instance)); }); @@ -407,10 +407,10 @@ describe("Plugin", () => { pluginsManager._initControllers(plugin); should(pluginsManager.controllers.get("test-plugin/foo")).be.instanceof( - BaseController + BaseController, ); should( - pluginsManager.controllers.get("test-plugin/foo").actionName + pluginsManager.controllers.get("test-plugin/foo").actionName, ).be.eql(action); }); @@ -438,7 +438,7 @@ describe("Plugin", () => { should(pluginsManager.routes[0].verb).be.equal("get"); should(pluginsManager.routes[0].path).be.equal( - "/_plugin/test-plugin/bar/:name" + "/_plugin/test-plugin/bar/:name", ); should(pluginsManager.routes[0].controller).be.equal("test-plugin/foo"); should(pluginsManager.routes[0].action).be.equal("bar"); @@ -450,7 +450,7 @@ describe("Plugin", () => { should(pluginsManager.routes[2].verb).be.equal("head"); should(pluginsManager.routes[2].path).be.equal( - "/_plugin/test-plugin/bar/:name" + "/_plugin/test-plugin/bar/:name", ); should(pluginsManager.routes[2].controller).be.equal("test-plugin/foo"); should(pluginsManager.routes[2].action).be.equal("bar"); @@ -462,7 +462,7 @@ describe("Plugin", () => { should(pluginsManager.routes[4].verb).be.equal("post"); should(pluginsManager.routes[4].path).be.equal( - "/_plugin/test-plugin/bar" + "/_plugin/test-plugin/bar", ); should(pluginsManager.routes[4].controller).be.equal("test-plugin/foo"); should(pluginsManager.routes[4].action).be.equal("bar"); @@ -474,7 +474,7 @@ describe("Plugin", () => { should(pluginsManager.routes[6].verb).be.equal("put"); should(pluginsManager.routes[6].path).be.equal( - "/_plugin/test-plugin/bar" + "/_plugin/test-plugin/bar", ); should(pluginsManager.routes[6].controller).be.equal("test-plugin/foo"); should(pluginsManager.routes[6].action).be.equal("bar"); @@ -486,7 +486,7 @@ describe("Plugin", () => { should(pluginsManager.routes[8].verb).be.equal("delete"); should(pluginsManager.routes[8].path).be.equal( - "/_plugin/test-plugin/bar" + "/_plugin/test-plugin/bar", ); should(pluginsManager.routes[8].controller).be.equal("test-plugin/foo"); should(pluginsManager.routes[8].action).be.equal("bar"); @@ -498,7 +498,7 @@ describe("Plugin", () => { should(pluginsManager.routes[10].verb).be.equal("patch"); should(pluginsManager.routes[10].path).be.equal( - "/_plugin/test-plugin/bar" + "/_plugin/test-plugin/bar", ); should(pluginsManager.routes[10].controller).be.equal("test-plugin/foo"); should(pluginsManager.routes[10].action).be.equal("bar"); @@ -694,13 +694,13 @@ describe("Plugin", () => { describe("#hasStrategyMethod", () => { it("should return true if a method exists", () => { should( - pluginsManager.hasStrategyMethod("someStrategy", "exists") + pluginsManager.hasStrategyMethod("someStrategy", "exists"), ).be.true(); }); it("should false true if a method does not exist", () => { should( - pluginsManager.hasStrategyMethod("someStrategy", "notExists") + pluginsManager.hasStrategyMethod("someStrategy", "notExists"), ).be.false(); }); }); @@ -708,7 +708,7 @@ describe("Plugin", () => { describe("#getStrategyMethod", () => { it("should return a method", () => { should( - pluginsManager.getStrategyMethod("someStrategy", "exists") + pluginsManager.getStrategyMethod("someStrategy", "exists"), ).be.a.Function(); }); }); @@ -719,7 +719,7 @@ describe("Plugin", () => { plugin.instance.authenticators = authenticators; should(() => pluginsManager._initAuthenticators(plugin)).throw( PluginImplementationError, - { id: "plugin.authenticators.not_an_object" } + { id: "plugin.authenticators.not_an_object" }, ); }); }); @@ -729,7 +729,7 @@ describe("Plugin", () => { plugin.instance.authenticators.foo = ctor; should(() => pluginsManager._initAuthenticators(plugin)).throw( PluginImplementationError, - { id: "plugin.authenticators.invalid_authenticator" } + { id: "plugin.authenticators.invalid_authenticator" }, ); }); }); @@ -753,35 +753,35 @@ describe("Plugin", () => { pluginsManager._initStrategies(plugin); should(pluginsManager.strategies.someStrategy.strategy).be.deepEqual( - plugin.instance.strategies.someStrategy + plugin.instance.strategies.someStrategy, ); should( - pluginsManager.strategies.someStrategy.methods.afterRegister + pluginsManager.strategies.someStrategy.methods.afterRegister, ).be.Function(); should(plugin.instance.afterRegisterFunction).be.calledOnce(); should( - plugin.instance.afterRegisterFunction.firstCall.args[0] + plugin.instance.afterRegisterFunction.firstCall.args[0], ).be.instanceOf(plugin.instance.authenticators.SomeStrategy); should( - pluginsManager.strategies.someStrategy.methods.exists + pluginsManager.strategies.someStrategy.methods.exists, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.create + pluginsManager.strategies.someStrategy.methods.create, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.update + pluginsManager.strategies.someStrategy.methods.update, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.delete + pluginsManager.strategies.someStrategy.methods.delete, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.getById + pluginsManager.strategies.someStrategy.methods.getById, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.getInfo + pluginsManager.strategies.someStrategy.methods.getInfo, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.validate + pluginsManager.strategies.someStrategy.methods.validate, ).be.Function(); should(plugin.instance.authenticators.SomeStrategy) .calledOnce() @@ -816,7 +816,7 @@ describe("Plugin", () => { pluginsManager._initStrategies(plugin); should(pluginsManager.strategies.someStrategy.strategy).be.deepEqual( - plugin.instance.strategies.someStrategy + plugin.instance.strategies.someStrategy, ); should(plugin.instance.afterRegisterFunction).be.calledOnce(); }); @@ -828,29 +828,29 @@ describe("Plugin", () => { pluginsManager._initStrategies(plugin); should(pluginsManager.strategies.someStrategy.strategy).be.deepEqual( - plugin.instance.strategies.someStrategy + plugin.instance.strategies.someStrategy, ); should( - pluginsManager.strategies.someStrategy.methods.exists + pluginsManager.strategies.someStrategy.methods.exists, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.create + pluginsManager.strategies.someStrategy.methods.create, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.update + pluginsManager.strategies.someStrategy.methods.update, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.delete + pluginsManager.strategies.someStrategy.methods.delete, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.getInfo + pluginsManager.strategies.someStrategy.methods.getInfo, ).be.Function(); should( - pluginsManager.strategies.someStrategy.methods.validate + pluginsManager.strategies.someStrategy.methods.validate, ).be.Function(); return should( - pluginsManager.strategies.someStrategy.methods.exists(foo) + pluginsManager.strategies.someStrategy.methods.exists(foo), ).be.rejectedWith(PluginImplementationError); }); @@ -862,7 +862,7 @@ describe("Plugin", () => { plugin.instance.strategies = strategies; should(() => pluginsManager._initStrategies(plugin)).throw( PluginImplementationError, - { message } + { message }, ); }); }); @@ -874,7 +874,7 @@ describe("Plugin", () => { PluginImplementationError, { id: "plugin.strategy.invalid_description", - } + }, ); }); }); @@ -884,7 +884,7 @@ describe("Plugin", () => { plugin.instance.strategies.someStrategy.methods = methods; should(() => pluginsManager._initStrategies(plugin)).throw( PluginImplementationError, - { id: "plugin.strategy.invalid_methods" } + { id: "plugin.strategy.invalid_methods" }, ); }); }); @@ -892,12 +892,12 @@ describe("Plugin", () => { it("should throw if config is not an object", () => { [[], null, undefined, "foobar", 123, true].forEach((config) => { const message = new RegExp( - `\\[test-plugin\\] Strategy someStrategy: expected a "config" property of type "object", got: ${config}` + `\\[test-plugin\\] Strategy someStrategy: expected a "config" property of type "object", got: ${config}`, ); plugin.instance.strategies.someStrategy.config = config; should(() => pluginsManager._initStrategies(plugin)).throw( PluginImplementationError, - { message } + { message }, ); }); }); @@ -909,7 +909,7 @@ describe("Plugin", () => { PluginImplementationError, { id: "plugin.strategy.invalid_method_type", - } + }, ); }); }); @@ -925,11 +925,11 @@ describe("Plugin", () => { PluginImplementationError, { id: "plugin.strategy.missing_method_function", - } + }, ); plugin.instance[fnName] = sinon.stub(); - } + }, ); }); @@ -946,7 +946,7 @@ describe("Plugin", () => { PluginImplementationError, { id: "plugin.strategy.invalid_method_type", - } + }, ); } } @@ -962,7 +962,7 @@ describe("Plugin", () => { PluginImplementationError, { id: "plugin.strategy.missing_method_function", - } + }, ); plugin.instance[fnName] = sinon.stub(); @@ -978,7 +978,7 @@ describe("Plugin", () => { PluginImplementationError, { id: "plugin.strategy.invalid_authenticator", - } + }, ); }); }); @@ -989,7 +989,7 @@ describe("Plugin", () => { PluginImplementationError, { id: "plugin.strategy.unknown_authenticator", - } + }, ); }); @@ -1001,7 +1001,7 @@ describe("Plugin", () => { PluginImplementationError, { id: "plugin.strategy.invalid_option", - } + }, ); }); }); @@ -1015,7 +1015,7 @@ describe("Plugin", () => { PluginImplementationError, { id: "plugin.strategy.invalid_option", - } + }, ); }); }); @@ -1028,7 +1028,7 @@ describe("Plugin", () => { PluginImplementationError, { id: "plugin.strategy.invalid_fields", - } + }, ); }); }); @@ -1195,7 +1195,7 @@ describe("Plugin", () => { it("should throw if the strategy does not exist", () => { should(() => - pluginsManager.unregisterStrategy(plugin.name, "foobar") + pluginsManager.unregisterStrategy(plugin.name, "foobar"), ).throw(NotFoundError, { id: "plugin.strategy.strategy_not_found" }); }); @@ -1203,8 +1203,8 @@ describe("Plugin", () => { should(() => pluginsManager.unregisterStrategy( "Frank William Abagnale Jr.", - "someStrategy" - ) + "someStrategy", + ), ).throw(PluginImplementationError, { id: "plugin.strategy.unauthorized_removal", }); @@ -1491,7 +1491,7 @@ describe("Plugin", () => { return should(kuzzle.pipe("foo:bar")).be.rejectedWith( PluginImplementationError, - { id: "plugin.runtime.unexpected_error" } + { id: "plugin.runtime.unexpected_error" }, ); }); @@ -1510,7 +1510,7 @@ describe("Plugin", () => { should(fooStub).be.calledOnce(); should(kuzzle.log.warn).calledWithMatch( - /\[test-plugin\] pipe for event 'foo:bar' is slow \(\d+ms\)/ + /\[test-plugin\] pipe for event 'foo:bar' is slow \(\d+ms\)/, ); }); diff --git a/test/core/realtime/hotelClerk/disconnect.test.js b/test/core/realtime/hotelClerk/disconnect.test.js index 3ab2bec49d..dda7a90675 100644 --- a/test/core/realtime/hotelClerk/disconnect.test.js +++ b/test/core/realtime/hotelClerk/disconnect.test.js @@ -37,17 +37,17 @@ describe("Test: hotelClerk.removeConnection", () => { new Map([ ["foo", { volatile: "room foo" }], ["bar", { volatile: "room bar" }], - ]) - ) + ]), + ), ); hotelClerk.subscriptions.set( "a", - new ConnectionRooms(new Map([["foo", null]])) + new ConnectionRooms(new Map([["foo", null]])), ); hotelClerk.subscriptions.set( "b", - new ConnectionRooms(new Map([["foo", null]])) + new ConnectionRooms(new Map([["foo", null]])), ); hotelClerk.rooms.set( @@ -57,8 +57,8 @@ describe("Test: hotelClerk.removeConnection", () => { index, collection, new Map([["foobar", new Channel("foo")]]), - new Set([connectionId, "a", "b"]) - ) + new Set([connectionId, "a", "b"]), + ), ); hotelClerk.rooms.set( "bar", @@ -67,8 +67,8 @@ describe("Test: hotelClerk.removeConnection", () => { index, collection, new Map([["barfoo", new Channel("bar")]]), - new Set([connectionId]) - ) + new Set([connectionId]), + ), ); hotelClerk.roomsCount = 2; @@ -116,7 +116,7 @@ describe("Test: hotelClerk.removeConnection", () => { }, }, "out", - { count: 2 } + { count: 2 }, ); should(realtimeModule.notifier.notifyUser).calledWithMatch( @@ -130,7 +130,7 @@ describe("Test: hotelClerk.removeConnection", () => { }, }, "out", - { count: 0 } + { count: 0 }, ); }); diff --git a/test/core/realtime/hotelClerk/hotelClerk.test.js b/test/core/realtime/hotelClerk/hotelClerk.test.js index d91056b7f5..b744315402 100644 --- a/test/core/realtime/hotelClerk/hotelClerk.test.js +++ b/test/core/realtime/hotelClerk/hotelClerk.test.js @@ -24,11 +24,11 @@ describe("HotelClerk", () => { hotelClerk.subscriptions.set( "a", - new ConnectionRooms(new Map([["foo", null]])) + new ConnectionRooms(new Map([["foo", null]])), ); hotelClerk.subscriptions.set( "b", - new ConnectionRooms(new Map([["foo", null]])) + new ConnectionRooms(new Map([["foo", null]])), ); return hotelClerk.init(); diff --git a/test/core/realtime/hotelClerk/join.test.js b/test/core/realtime/hotelClerk/join.test.js index 56db897b84..196b5cd6c0 100644 --- a/test/core/realtime/hotelClerk/join.test.js +++ b/test/core/realtime/hotelClerk/join.test.js @@ -42,7 +42,7 @@ describe("Test: hotelClerk.join", () => { bar: ["foo", "bar", "baz", "qux"], }, }, - { connectionId, token: null } + { connectionId, token: null }, ); kuzzle.config.limits.subscriptionMinterms = 0; @@ -75,7 +75,7 @@ describe("Test: hotelClerk.join", () => { roomId, request, "in", - { count: 1 } + { count: 1 }, ); const request2 = new Request( @@ -86,7 +86,7 @@ describe("Test: hotelClerk.join", () => { action: "join", body: { roomId }, }, - { connectionId: "connection2", user: null } + { connectionId: "connection2", user: null }, ); request2.input.body = { roomId }; @@ -101,7 +101,7 @@ describe("Test: hotelClerk.join", () => { roomId, request2, "in", - { count: 2 } + { count: 2 }, ); }); @@ -114,7 +114,7 @@ describe("Test: hotelClerk.join", () => { action: "join", body: { roomId: "i-exist" }, }, - context + context, ); return should(hotelClerk.join(joinRequest)).be.rejectedWith(NotFoundError, { @@ -131,7 +131,7 @@ describe("Test: hotelClerk.join", () => { action: "join", body: { roomId: "i-exist" }, }, - context + context, ); const response = { cluster: false, channel: "foobar", subscribed: true }; hotelClerk.rooms.set("i-exist", {}); @@ -151,7 +151,7 @@ describe("Test: hotelClerk.join", () => { should(kuzzle.call).be.calledWith( "core:realtime:subscribe:after", - "i-exist" + "i-exist", ); }); }); diff --git a/test/core/realtime/hotelClerk/subscribe.test.js b/test/core/realtime/hotelClerk/subscribe.test.js index 1e0a2d0346..e9b50515ac 100644 --- a/test/core/realtime/hotelClerk/subscribe.test.js +++ b/test/core/realtime/hotelClerk/subscribe.test.js @@ -45,7 +45,7 @@ describe("Test: hotelClerk.subscribe", () => { bar: ["foo", "bar", "baz", "qux"], }, }, - { connectionId, token: null } + { connectionId, token: null }, ); kuzzle.koncorde.normalize.returns({ @@ -105,7 +105,7 @@ describe("Test: hotelClerk.subscribe", () => { "foobar", request, "in", - { count: 1 } + { count: 1 }, ); const roomId = hotelClerk.rooms.get(response.roomId).id; @@ -133,7 +133,7 @@ describe("Test: hotelClerk.subscribe", () => { "barfoo", request, "in", - { count: 1 } + { count: 1 }, ); should(kuzzle.call).be.calledWithMatch("core:realtime:room:create:after", { @@ -151,7 +151,7 @@ describe("Test: hotelClerk.subscribe", () => { roomId, connectionId, kuid: "Umraniye", - } + }, ); }); @@ -168,7 +168,7 @@ describe("Test: hotelClerk.subscribe", () => { secondResponse.roomId, request, "in", - { count: 1 } + { count: 1 }, ); }); @@ -203,7 +203,7 @@ describe("Test: hotelClerk.subscribe", () => { result.roomId, request, "in", - { count: 1 } + { count: 1 }, ); }); diff --git a/test/core/realtime/hotelClerk/unsubscribe.test.js b/test/core/realtime/hotelClerk/unsubscribe.test.js index 788eb3b18f..01bcb70280 100644 --- a/test/core/realtime/hotelClerk/unsubscribe.test.js +++ b/test/core/realtime/hotelClerk/unsubscribe.test.js @@ -46,8 +46,8 @@ describe("Test: hotelClerk.unsubscribe", () => { ["ch1", new Channel(roomId, { cluster: true })], ["ch2", new Channel(roomId, { cluster: true })], ]), - new Set([connectionId]) - ) + new Set([connectionId]), + ), ); hotelClerk.roomsCount = 1; @@ -81,7 +81,7 @@ describe("Test: hotelClerk.unsubscribe", () => { await should(hotelClerk.unsubscribe(connectionId, roomId)).rejectedWith( PreconditionError, - { id: "core.realtime.not_subscribed" } + { id: "core.realtime.not_subscribed" }, ); should(hotelClerk.rooms).have.key(roomId); @@ -92,7 +92,7 @@ describe("Test: hotelClerk.unsubscribe", () => { it("should reject if the room does not exist", () => { hotelClerk.subscriptions.set( connectionId, - new ConnectionRooms(new Map([["nowhere", null]])) + new ConnectionRooms(new Map([["nowhere", null]])), ); return hotelClerk @@ -106,7 +106,7 @@ describe("Test: hotelClerk.unsubscribe", () => { kuzzle.tokenManager.getKuidFromConnection.returns("Umraniye"); hotelClerk.subscriptions.set( connectionId, - new ConnectionRooms(new Map([[roomId, null]])) + new ConnectionRooms(new Map([[roomId, null]])), ); await hotelClerk.unsubscribe(connectionId, roomId); @@ -130,7 +130,7 @@ describe("Test: hotelClerk.unsubscribe", () => { }, }, "out", - { count: 0 } + { count: 0 }, ); should(kuzzle.emit).be.calledWithMatch( "core:realtime:user:unsubscribe:after", @@ -153,7 +153,7 @@ describe("Test: hotelClerk.unsubscribe", () => { connectionId, kuid: "Umraniye", }, - } + }, ); }); @@ -164,8 +164,8 @@ describe("Test: hotelClerk.unsubscribe", () => { new Map([ [roomId, null], ["anotherRoom", null], - ]) - ) + ]), + ), ); hotelClerk.rooms.set("anotherRoom", {}); @@ -192,18 +192,18 @@ describe("Test: hotelClerk.unsubscribe", () => { }, }, "out", - { count: 0 } + { count: 0 }, ); }); it("should remove a customer and notify other users in the room", async () => { hotelClerk.subscriptions.set( connectionId, - new ConnectionRooms(new Map([[roomId, null]])) + new ConnectionRooms(new Map([[roomId, null]])), ); hotelClerk.subscriptions.set( "foobar", - new ConnectionRooms(new Map([[roomId, null]])) + new ConnectionRooms(new Map([[roomId, null]])), ); hotelClerk.rooms.get(roomId).connections.add("foobar"); @@ -219,12 +219,12 @@ describe("Test: hotelClerk.unsubscribe", () => { roomId, sinon.match.instanceOf(Request), "out", - { count: 1 } + { count: 1 }, ); should(kuzzle.call).be.calledWithMatch( "core:realtime:unsubscribe:after", - roomId + roomId, ); }); }); diff --git a/test/core/realtime/notifier/notifyDocumentCreate.test.js b/test/core/realtime/notifier/notifyDocumentCreate.test.js index bbb554fef7..ae6e156121 100644 --- a/test/core/realtime/notifier/notifyDocumentCreate.test.js +++ b/test/core/realtime/notifier/notifyDocumentCreate.test.js @@ -38,14 +38,14 @@ describe("Test: notifier.notifyDocumentCreate", () => { should(kuzzle.koncorde.test).calledWith( { ..._source, _id }, - "index/collection" + "index/collection", ); should(notifier.notifyDocument).calledWithMatch( rooms, request, "in", "create", - { _id, _source } + { _id, _source }, ); should(result).match(rooms); }); diff --git a/test/core/realtime/notifier/notifyDocumentDelete.test.js b/test/core/realtime/notifier/notifyDocumentDelete.test.js index 066b728f45..d3fec540dd 100644 --- a/test/core/realtime/notifier/notifyDocumentDelete.test.js +++ b/test/core/realtime/notifier/notifyDocumentDelete.test.js @@ -38,14 +38,14 @@ describe("Test: notifier.notifyDocumentDelete", () => { should(kuzzle.koncorde.test).calledWith( { ..._source, _id }, - "index/collection" + "index/collection", ); should(notifier.notifyDocument).calledWithMatch( rooms, request, "out", "delete", - { _id, _source } + { _id, _source }, ); should(result).be.an.Array().and.be.empty(); }); diff --git a/test/core/realtime/notifier/notifyDocumentReplace.test.js b/test/core/realtime/notifier/notifyDocumentReplace.test.js index acb5d609d3..223acacdff 100644 --- a/test/core/realtime/notifier/notifyDocumentReplace.test.js +++ b/test/core/realtime/notifier/notifyDocumentReplace.test.js @@ -45,7 +45,7 @@ describe("Test: notifier.notifyDocumentReplace", () => { _id, _source: request.input.body, }, - JSON.stringify(["foo", "bar"]) + JSON.stringify(["foo", "bar"]), ); should(notifier.notifyDocument.callCount).be.eql(2); @@ -58,7 +58,7 @@ describe("Test: notifier.notifyDocumentReplace", () => { { _id, _source: request.input.body, - } + }, ); should(notifier.notifyDocument.getCall(1)).calledWith( @@ -66,7 +66,7 @@ describe("Test: notifier.notifyDocumentReplace", () => { request, "out", "replace", - { _id, _source: request.input.body } + { _id, _source: request.input.body }, ); should(result).match(["foo"]); @@ -81,7 +81,7 @@ describe("Test: notifier.notifyDocumentReplace", () => { _id: request.input.args._id, _source: request.input.body, }, - JSON.stringify(["foo", "bar"]) + JSON.stringify(["foo", "bar"]), ); should(rooms).be.an.Array().and.be.empty(); diff --git a/test/core/realtime/notifier/notifyDocumentUpdate.test.js b/test/core/realtime/notifier/notifyDocumentUpdate.test.js index c50bbd27f9..6c6a1cd1de 100644 --- a/test/core/realtime/notifier/notifyDocumentUpdate.test.js +++ b/test/core/realtime/notifier/notifyDocumentUpdate.test.js @@ -48,7 +48,7 @@ describe("Test: notifier.notifyDocumentUpdate", () => { _source: { foo: "bar" }, _updatedFields: ["foo"], }, - JSON.stringify(["foo", "bar"]) + JSON.stringify(["foo", "bar"]), ); should(kuzzle.koncorde.test) @@ -65,7 +65,7 @@ describe("Test: notifier.notifyDocumentUpdate", () => { _id, _source: { foo: "bar" }, _updatedFields: ["foo"], - } + }, ); should(notifier.notifyDocument.getCall(1)).calledWith( @@ -77,7 +77,7 @@ describe("Test: notifier.notifyDocumentUpdate", () => { _id, _source: { foo: "bar" }, _updatedFields: ["foo"], - } + }, ); should(rooms).match(["foo"]); @@ -92,7 +92,7 @@ describe("Test: notifier.notifyDocumentUpdate", () => { _id: request.input.args._id, _source: { foo: "bar" }, }, - JSON.stringify(["foo", "bar"]) + JSON.stringify(["foo", "bar"]), ); should(rooms).be.an.Array().and.be.empty(); diff --git a/test/core/realtime/notifier/notifyDocuments.test.js b/test/core/realtime/notifier/notifyDocuments.test.js index b605b04326..28fa7f8d1f 100644 --- a/test/core/realtime/notifier/notifyDocuments.test.js +++ b/test/core/realtime/notifier/notifyDocuments.test.js @@ -78,19 +78,19 @@ describe("#notifier.notifyDocuments", () => { "core:cache:internal:store", `{notif/${index}/${collection}}/foo`, JSON.stringify(rooms), - { ttl } + { ttl }, ) .calledWith( "core:cache:internal:store", `{notif/${index}/${collection}}/bar`, JSON.stringify(rooms), - { ttl } + { ttl }, ) .calledWith( "core:cache:internal:store", `{notif/${index}/${collection}}/baz`, JSON.stringify(rooms), - { ttl } + { ttl }, ); }); @@ -114,17 +114,17 @@ describe("#notifier.notifyDocuments", () => { .calledWith( "core:cache:internal:store", `{notif/${index}/${collection}}/foo`, - JSON.stringify(rooms) + JSON.stringify(rooms), ) .calledWith( "core:cache:internal:store", `{notif/${index}/${collection}}/bar`, - JSON.stringify(rooms) + JSON.stringify(rooms), ) .calledWith( "core:cache:internal:store", `{notif/${index}/${collection}}/baz`, - JSON.stringify(rooms) + JSON.stringify(rooms), ); }); @@ -146,7 +146,7 @@ describe("#notifier.notifyDocuments", () => { "core:cache:internal:store", `{notif/${index}/${collection}}/bar`, JSON.stringify(["foo", "bar"]), - { ttl } + { ttl }, ); should(kuzzle.ask.withArgs("core:cache:internal:del")) @@ -209,19 +209,19 @@ describe("#notifier.notifyDocuments", () => { should(notifier.notifyDocumentUpdate.firstCall).calledWith( request, { _id: "foo" }, - cacheResult[0] + cacheResult[0], ); should(notifier.notifyDocumentUpdate.secondCall).calledWith( request, { _id: "bar" }, - cacheResult[1] + cacheResult[1], ); should(notifier.notifyDocumentUpdate.thirdCall).calledWith( request, { _id: "baz" }, - cacheResult[2] + cacheResult[2], ); should(kuzzle.ask).calledWith("core:cache:internal:mget", [ @@ -249,19 +249,19 @@ describe("#notifier.notifyDocuments", () => { should(notifier.notifyDocumentReplace.firstCall).calledWith( request, { _id: "foo" }, - cacheResult[0] + cacheResult[0], ); should(notifier.notifyDocumentReplace.secondCall).calledWith( request, { _id: "bar" }, - cacheResult[1] + cacheResult[1], ); should(notifier.notifyDocumentReplace.thirdCall).calledWith( request, { _id: "baz" }, - cacheResult[2] + cacheResult[2], ); should(kuzzle.ask).calledWith("core:cache:internal:mget", [ @@ -301,7 +301,7 @@ describe("#notifier.notifyDocuments", () => { should(notifier.notifyDocumentReplace).calledWith( request, { _id: "bar", created: false }, - cacheResult[1] + cacheResult[1], ); should(kuzzle.ask).calledWith("core:cache:internal:mget", [ @@ -372,7 +372,7 @@ describe("#notifier.notifyDocuments", () => { should(notifier.notifyDocumentUpdate).calledWith( request, { _id: "bar", created: false, _updatedFields: ["toto"] }, - cacheResult[1] + cacheResult[1], ); should(kuzzle.ask).calledWith("core:cache:internal:mget", [ @@ -415,7 +415,7 @@ describe("#notifier.notifyDocuments", () => { it("should throw on an unknown action", () => { return should( - notifier.notifyDocuments(request, "ohnoes", [document]) + notifier.notifyDocuments(request, "ohnoes", [document]), ).rejectedWith(KuzzleInternalError, { id: "core.fatal.assertion_failed", }); diff --git a/test/core/realtime/notifier/notifyMethods.test.js b/test/core/realtime/notifier/notifyMethods.test.js index d0324e175e..b45bcf24f1 100644 --- a/test/core/realtime/notifier/notifyMethods.test.js +++ b/test/core/realtime/notifier/notifyMethods.test.js @@ -40,7 +40,7 @@ describe("notify methods", () => { controller: "controller", action: "action", }, - { protocol: "protocol" } + { protocol: "protocol" }, ); hotelClerk.rooms.set( @@ -98,8 +98,8 @@ describe("notify methods", () => { propagate: true, }), ], - ]) - ) + ]), + ), ); hotelClerk.rooms.set( @@ -113,8 +113,8 @@ describe("notify methods", () => { "foobar", new Channel("nonMatching", { scope: "none", propagate: true }), ], - ]) - ) + ]), + ), ); hotelClerk.rooms.set( @@ -140,8 +140,8 @@ describe("notify methods", () => { propagate: false, }), ], - ]) - ) + ]), + ), ); hotelClerk.rooms.set( @@ -155,8 +155,8 @@ describe("notify methods", () => { "always", new Channel("alwaysMatching", { scope: "all", propagate: true }), ], - ]) - ) + ]), + ), ); return notifier.init(); @@ -189,13 +189,13 @@ describe("notify methods", () => { request, "out", "update", - content + content, ); should(notifier._notifyDocument).be.calledWith( rooms, expectedNotification, - { fromCluster: false } + { fromCluster: false }, ); should(kuzzle.emit.callCount).be.eql(1); @@ -218,7 +218,7 @@ describe("notify methods", () => { "scope", "update", { some: "content" }, - { fromCluster: false } + { fromCluster: false }, ); should(kuzzle.entryPoint.dispatch).not.be.called(); @@ -232,7 +232,7 @@ describe("notify methods", () => { request, "out", "update", - content + content, ); await notifier._notifyDocument( @@ -244,7 +244,7 @@ describe("notify methods", () => { "cluster", ], documentNotification, - { fromCluster: false } + { fromCluster: false }, ); const dispatch = kuzzle.entryPoint.dispatch; @@ -261,7 +261,7 @@ describe("notify methods", () => { ]); should(dispatch.firstCall.args[1].payload).be.instanceof( - DocumentNotification + DocumentNotification, ); const notification = dispatch.firstCall.args[1].payload; @@ -319,7 +319,7 @@ describe("notify methods", () => { "not a scope", "create", content, - { fromCluster: false } + { fromCluster: false }, ); should(kuzzle.entryPoint.dispatch).not.be.called(); @@ -333,7 +333,7 @@ describe("notify methods", () => { request, "out", "create", - content + content, ); await notifier._notifyDocument( @@ -344,7 +344,7 @@ describe("notify methods", () => { "IAMERROR", "cluster", ], - documentNotification + documentNotification, ); const dispatch = kuzzle.entryPoint.dispatch; @@ -387,7 +387,7 @@ describe("notify methods", () => { ]); should(dispatch.firstCall.args[1].payload).be.instanceof( - UserNotification + UserNotification, ); const notification = dispatch.firstCall.args[1].payload; @@ -451,8 +451,8 @@ describe("notify methods", () => { new Map([ ["nonMatching", null], ["alwaysMatching", null], - ]) - ) + ]), + ), ); await notifier.notifyTokenExpired("foobar"); @@ -495,7 +495,7 @@ describe("notify methods", () => { "my-event", ["channel-foo"], { foo: "bar" }, - "connectionId" + "connectionId", ); should(kuzzle.entryPoint.dispatch) @@ -545,14 +545,14 @@ describe("notify methods", () => { alpha: "beta", }, }; - } + }, ); await notifier._dispatch( "my-event", ["channel-foo"], { foo: "bar" }, - "foobar" + "foobar", ); await should(kuzzle.pipe) diff --git a/test/core/security/profileRepository.test.js b/test/core/security/profileRepository.test.js index acf12f1483..d2a304da2d 100644 --- a/test/core/security/profileRepository.test.js +++ b/test/core/security/profileRepository.test.js @@ -76,13 +76,13 @@ describe("Test: security/profileRepository", () => { "core:storage:private:document:get", kuzzle.internalIndex.index, "profiles", - "idontexist" + "idontexist", ) .rejects(new NotFoundError("Not found")); return should(profileRepository.load("idontexist")).rejectedWith( NotFoundError, - { id: "security.profile.not_found" } + { id: "security.profile.not_found" }, ); }); @@ -119,7 +119,7 @@ describe("Test: security/profileRepository", () => { it("should reject if profileIds is not an array of strings", () => { return should( - profileRepository.loadProfiles(["a string", { foo: "bar" }]) + profileRepository.loadProfiles(["a string", { foo: "bar" }]), ).be.rejectedWith(BadRequestError, { id: "api.assert.invalid_type", message: 'Wrong type for argument "profileIds" (expected: string[])', @@ -191,7 +191,7 @@ describe("Test: security/profileRepository", () => { InternalError, { id: "security.profile.cannot_hydrate", - } + }, ); }); @@ -227,12 +227,12 @@ describe("Test: security/profileRepository", () => { userRepositoryMock.search.resolves({ total: 1 }); await should( - profileRepository.deleteById(testProfile._id) + profileRepository.deleteById(testProfile._id), ).be.rejectedWith(PreconditionError, { id: "security.profile.in_use" }); should(userRepositoryMock.search).calledWithMatch( { query: { terms: { profileIds: [testProfile._id] } } }, - { from: 0, size: 1 } + { from: 0, size: 1 }, ); should(kuzzle.emit).not.be.called(); @@ -248,7 +248,7 @@ describe("Test: security/profileRepository", () => { BadRequestError, { id: "security.profile.cannot_delete", - } + }, ); should(userRepositoryMock.search).not.called(); @@ -361,7 +361,7 @@ describe("Test: security/profileRepository", () => { .rejects(error); return should( - profileRepository.validateAndSaveProfile(invalidProfile) + profileRepository.validateAndSaveProfile(invalidProfile), ).be.rejectedWith(error); }); @@ -375,9 +375,8 @@ describe("Test: security/profileRepository", () => { .withArgs("core:storage:public:collection:exist") .resolves(true); - const result = await profileRepository.validateAndSaveProfile( - testProfile - ); + const result = + await profileRepository.validateAndSaveProfile(testProfile); should(result).be.exactly(testProfile); should(profileRepository.profiles).have.value("foo", testProfile); @@ -405,7 +404,7 @@ describe("Test: security/profileRepository", () => { profile.policies = [{ roleId: "test" }, { roleId: "another" }]; return should( - profileRepository.validateAndSaveProfile(profile) + profileRepository.validateAndSaveProfile(profile), ).be.rejectedWith(BadRequestError, { id: "security.profile.missing_anonymous_role", }); @@ -437,7 +436,7 @@ describe("Test: security/profileRepository", () => { Repository.prototype.loadOneFromDatabase.resolves("foo"); await should(profileRepository.loadOneFromDatabase("bar")).fulfilledWith( - "foo" + "foo", ); should(Repository.prototype.loadOneFromDatabase).calledWith("bar"); @@ -451,7 +450,7 @@ describe("Test: security/profileRepository", () => { return should(profileRepository.loadOneFromDatabase("foo")).rejectedWith( NotFoundError, - { id: "security.profile.not_found" } + { id: "security.profile.not_found" }, ); }); @@ -461,7 +460,7 @@ describe("Test: security/profileRepository", () => { Repository.prototype.loadOneFromDatabase.rejects(error); return should(profileRepository.loadOneFromDatabase("foo")).rejectedWith( - error + error, ); }); }); @@ -515,7 +514,7 @@ describe("Test: security/profileRepository", () => { { method: "create", refresh: "refresh", - } + }, ); const profile = @@ -536,7 +535,7 @@ describe("Test: security/profileRepository", () => { profileRepository.validateAndSaveProfile.resolves("foobar"); return should(profileRepository.create("foo", {}, {})).fulfilledWith( - "foobar" + "foobar", ); }); }); @@ -555,7 +554,7 @@ describe("Test: security/profileRepository", () => { "core:security:profile:createOrReplace", "foo", "bar", - "baz" + "baz", ); should(profileRepository.createOrReplace).calledWith("foo", "bar", "baz"); @@ -579,7 +578,7 @@ describe("Test: security/profileRepository", () => { { method: "createOrReplace", refresh: "refresh", - } + }, ); const profile = @@ -600,7 +599,7 @@ describe("Test: security/profileRepository", () => { profileRepository.validateAndSaveProfile.resolves("foobar"); return should( - profileRepository.createOrReplace("foo", {}, {}) + profileRepository.createOrReplace("foo", {}, {}), ).fulfilledWith("foobar"); }); }); @@ -626,7 +625,7 @@ describe("Test: security/profileRepository", () => { profileRepository.load.rejects(new Error("foo")); return should(profileRepository.update("foo", {}, {})).rejectedWith( - error + error, ); }); @@ -648,7 +647,7 @@ describe("Test: security/profileRepository", () => { { method: "update", refresh: "refresh", - } + }, ); const profile = @@ -667,7 +666,7 @@ describe("Test: security/profileRepository", () => { profileRepository.validateAndSaveProfile.resolves("foobar"); return should(profileRepository.update("foo", {}, {})).fulfilledWith( - "foobar" + "foobar", ); }); }); @@ -748,7 +747,7 @@ describe("Test: security/profileRepository", () => { restrictedTo: new Map( Object.entries({ foo: ["bar", "baz"], - }) + }), ), }); }); @@ -773,7 +772,7 @@ describe("Test: security/profileRepository", () => { restrictedTo: new Map( Object.entries({ foo: ["bar", "baz", "qux"], - }) + }), ), }); }); diff --git a/test/core/security/roleRepository.test.js b/test/core/security/roleRepository.test.js index 112cfc0365..61ee66925c 100644 --- a/test/core/security/roleRepository.test.js +++ b/test/core/security/roleRepository.test.js @@ -51,7 +51,7 @@ describe("Test: security/roleRepository", () => { Repository.prototype.loadOneFromDatabase.resolves("foo"); await should(roleRepository.loadOneFromDatabase("bar")).fulfilledWith( - "foo" + "foo", ); should(Repository.prototype.loadOneFromDatabase).calledWith("bar"); @@ -65,7 +65,7 @@ describe("Test: security/roleRepository", () => { return should(roleRepository.loadOneFromDatabase("foo")).rejectedWith( NotFoundError, - { id: "security.role.not_found" } + { id: "security.role.not_found" }, ); }); @@ -75,7 +75,7 @@ describe("Test: security/roleRepository", () => { Repository.prototype.loadOneFromDatabase.rejects(error); return should(roleRepository.loadOneFromDatabase("foo")).rejectedWith( - error + error, ); }); }); @@ -266,7 +266,7 @@ describe("Test: security/roleRepository", () => { result = await roleRepository.searchRole( { controllers: ["foo"] }, - { from: 1 } + { from: 1 }, ); should(result.total).be.exactly(3); should(result.hits.length).be.exactly(2); @@ -275,7 +275,7 @@ describe("Test: security/roleRepository", () => { result = await roleRepository.searchRole( { controllers: ["foo"] }, - { size: 2 } + { size: 2 }, ); should(result.total).be.exactly(3); should(result.hits.length).be.exactly(2); @@ -287,7 +287,7 @@ describe("Test: security/roleRepository", () => { { from: 1, size: 2, - } + }, ); should(result.total).be.exactly(4); should(result.hits.length).be.exactly(2); @@ -332,7 +332,7 @@ describe("Test: security/roleRepository", () => { await should(roleRepository.deleteById(id)).rejectedWith( BadRequestError, - { id: "security.role.cannot_delete" } + { id: "security.role.cannot_delete" }, ); should(kuzzle.emit).not.be.called(); @@ -348,7 +348,7 @@ describe("Test: security/roleRepository", () => { await should(roleRepository.deleteById(fakeRole._id)).rejectedWith( PreconditionError, - { id: "security.role.in_use" } + { id: "security.role.in_use" }, ); should(kuzzle.emit).not.be.called(); @@ -373,7 +373,7 @@ describe("Test: security/roleRepository", () => { roleRepository.load.withArgs(fakeRole._id).rejects(error); return should(roleRepository.deleteById(fakeRole._id)).rejectedWith( - error + error, ); }); }); @@ -417,7 +417,7 @@ describe("Test: security/roleRepository", () => { await should(roleRepository.validateAndSaveRole(fakeRole)).rejectedWith( BadRequestError, - { id: "security.role.login_required" } + { id: "security.role.login_required" }, ); }); @@ -435,7 +435,7 @@ describe("Test: security/roleRepository", () => { await should(roleRepository.validateAndSaveRole(fakeRole)).rejectedWith( BadRequestError, - { id: "security.role.login_required" } + { id: "security.role.login_required" }, ); }); @@ -453,7 +453,7 @@ describe("Test: security/roleRepository", () => { await should(roleRepository.validateAndSaveRole(fakeRole)).rejectedWith( BadRequestError, - { id: "security.role.login_required" } + { id: "security.role.login_required" }, ); }); @@ -512,11 +512,11 @@ describe("Test: security/roleRepository", () => { beforeEach(() => { kuzzle.funnel.controllers.set( "document", - new NativeController(["create", "delete"]) + new NativeController(["create", "delete"]), ); kuzzle.funnel.isNativeController.callsFake((ctrl) => - kuzzle.funnel.controllers.has(ctrl) + kuzzle.funnel.controllers.has(ctrl), ); }); @@ -645,7 +645,7 @@ describe("Test: security/roleRepository", () => { roleRepository.checkRolePluginsRights(role, { force: true }); should(kuzzle.log.warn).be.calledWith( - 'The role "test" gives access to the non-existing controller "invalid_controller".' + 'The role "test" gives access to the non-existing controller "invalid_controller".', ); }); @@ -669,7 +669,7 @@ describe("Test: security/roleRepository", () => { }); should(kuzzle.log.warn).be.calledWith( - 'The role "test" gives access to the non-existing controller "invalid_controller".' + 'The role "test" gives access to the non-existing controller "invalid_controller".', ); }); @@ -710,7 +710,7 @@ describe("Test: security/roleRepository", () => { roleRepository.checkRolePluginsRights(role, { force: true }); should(kuzzle.log.warn).be.calledWith( - 'The role "test" gives access to the non-existing action "iDontExist" for the controller "foobar".' + 'The role "test" gives access to the non-existing action "iDontExist" for the controller "foobar".', ); }); @@ -788,7 +788,7 @@ describe("Test: security/roleRepository", () => { { method: "create", refresh: "refresh", - } + }, ); const role = roleRepository.validateAndSaveRole.firstCall.args[0]; @@ -808,7 +808,7 @@ describe("Test: security/roleRepository", () => { roleRepository.validateAndSaveRole.resolves("foobar"); return should(roleRepository.create("foo", {}, {})).fulfilledWith( - "foobar" + "foobar", ); }); }); @@ -826,7 +826,7 @@ describe("Test: security/roleRepository", () => { "core:security:role:createOrReplace", "foo", "bar", - "baz" + "baz", ); should(roleRepository.createOrReplace).calledWith("foo", "bar", "baz"); @@ -850,7 +850,7 @@ describe("Test: security/roleRepository", () => { { method: "createOrReplace", refresh: "refresh", - } + }, ); const role = roleRepository.validateAndSaveRole.firstCall.args[0]; @@ -870,7 +870,7 @@ describe("Test: security/roleRepository", () => { roleRepository.validateAndSaveRole.resolves("foobar"); return should( - roleRepository.createOrReplace("foo", {}, {}) + roleRepository.createOrReplace("foo", {}, {}), ).fulfilledWith("foobar"); }); }); @@ -951,7 +951,7 @@ describe("Test: security/roleRepository", () => { { method: "replace", refresh: "refresh", - } + }, ); const role = roleRepository.validateAndSaveRole.firstCall.args[0]; @@ -969,7 +969,7 @@ describe("Test: security/roleRepository", () => { roleRepository.validateAndSaveRole.resolves("foobar"); return should(roleRepository.update("foo", {}, {})).fulfilledWith( - "foobar" + "foobar", ); }); }); diff --git a/test/core/security/securityLoader.test.js b/test/core/security/securityLoader.test.js index 8313f2ee61..05a9a67d4c 100644 --- a/test/core/security/securityLoader.test.js +++ b/test/core/security/securityLoader.test.js @@ -36,17 +36,17 @@ describe("security/securityLoader", () => { should(kuzzle.funnel.processRequest.callCount).be.eql(2); should(kuzzle.funnel.processRequest.getCall(1).args[0].input.action).be.eql( - "createOrReplaceRole" + "createOrReplaceRole", ); should( - kuzzle.funnel.processRequest.getCall(0).args[0].input.args._id + kuzzle.funnel.processRequest.getCall(0).args[0].input.args._id, ).be.eql("driver"); should( - kuzzle.funnel.processRequest.getCall(0).args[0].input.args.force + kuzzle.funnel.processRequest.getCall(0).args[0].input.args.force, ).be.eql(true); should( kuzzle.funnel.processRequest.getCall(0).args[0].input.body.controllers - .document.actions["*"] + .document.actions["*"], ).be.eql(true); }); @@ -75,7 +75,7 @@ describe("security/securityLoader", () => { BadRequestError, { id: "security.user.prevent_overwrite", - } + }, ); }); @@ -91,21 +91,21 @@ describe("security/securityLoader", () => { should(kuzzle.funnel.processRequest.callCount).be.eql(2); should(kuzzle.funnel.processRequest.getCall(0).args[0].input.action).be.eql( - "mGetUsers" + "mGetUsers", ); should( - kuzzle.funnel.processRequest.getCall(0).args[0].input.body.ids + kuzzle.funnel.processRequest.getCall(0).args[0].input.body.ids, ).be.eql(["gfreeman", "bcalhoun"]); should(kuzzle.funnel.processRequest.getCall(1).args[0].input.action).be.eql( - "createUser" + "createUser", ); should( - kuzzle.funnel.processRequest.getCall(1).args[0].input.args._id + kuzzle.funnel.processRequest.getCall(1).args[0].input.args._id, ).be.eql("bcalhoun"); should( kuzzle.funnel.processRequest.getCall(1).args[0].input.body.content - .profileIds + .profileIds, ).be.eql(["customer"]); }); @@ -118,34 +118,34 @@ describe("security/securityLoader", () => { await loader.load( { users: securities.users }, - { onExistingUsers: "overwrite" } + { onExistingUsers: "overwrite" }, ); should(kuzzle.funnel.processRequest.callCount).be.eql(4); should(kuzzle.funnel.processRequest.getCall(0).args[0].input.action).be.eql( - "mGetUsers" + "mGetUsers", ); should( - kuzzle.funnel.processRequest.getCall(0).args[0].input.body.ids + kuzzle.funnel.processRequest.getCall(0).args[0].input.body.ids, ).be.eql(["gfreeman", "bcalhoun"]); should(kuzzle.funnel.processRequest.getCall(1).args[0].input.action).be.eql( - "mDeleteUsers" + "mDeleteUsers", ); should( - kuzzle.funnel.processRequest.getCall(1).args[0].input.body.ids + kuzzle.funnel.processRequest.getCall(1).args[0].input.body.ids, ).be.eql(["gfreeman"]); should(kuzzle.funnel.processRequest.getCall(2).args[0].input.action).be.eql( - "createUser" + "createUser", ); should( - kuzzle.funnel.processRequest.getCall(2).args[0].input.args._id + kuzzle.funnel.processRequest.getCall(2).args[0].input.args._id, ).be.eql("gfreeman"); should( kuzzle.funnel.processRequest.getCall(2).args[0].input.body.content - .profileIds + .profileIds, ).be.eql(["driver"]); }); @@ -162,7 +162,7 @@ describe("security/securityLoader", () => { roles: { foo: 123 }, profiles: securities.profiles, users: securities.users, - }) + }), ).rejectedWith(BadRequestError, { id: "api.assert.invalid_argument", message: 'Invalid argument "123". Expected: object', @@ -175,7 +175,7 @@ describe("security/securityLoader", () => { roles: securities.roles, profiles: { foo: 123 }, users: securities.users, - }) + }), ).rejectedWith(BadRequestError, { id: "api.assert.invalid_argument", message: 'Invalid argument "123". Expected: object', @@ -190,7 +190,7 @@ describe("security/securityLoader", () => { roles: {}, profiles: {}, users: { foo: 123 }, - }) + }), ).rejectedWith(BadRequestError, { id: "api.assert.invalid_argument", message: 'Invalid argument "123". Expected: object', diff --git a/test/core/security/userRepository.test.js b/test/core/security/userRepository.test.js index 8da5eb5894..257e5b3909 100644 --- a/test/core/security/userRepository.test.js +++ b/test/core/security/userRepository.test.js @@ -71,7 +71,7 @@ describe("Test: security/userRepository", () => { profileRepositoryMock.loadProfiles.resolves([null]); return should( - userRepository.fromDTO({ _id: "foo", profileIds: ["nope"] }) + userRepository.fromDTO({ _id: "foo", profileIds: ["nope"] }), ).be.rejectedWith(KuzzleInternalError, { id: "security.user.cannot_hydrate", }); @@ -80,7 +80,7 @@ describe("Test: security/userRepository", () => { it("should reject if the user has no profile associated to it", () => { return should(userRepository.fromDTO({ _id: "foo" })).rejectedWith( KuzzleInternalError, - { id: "security.user.no_profile" } + { id: "security.user.no_profile" }, ); }); }); @@ -126,7 +126,7 @@ describe("Test: security/userRepository", () => { describe("#serializeToCache", () => { it("should return a valid plain object", () => { const result = userRepository.serializeToCache( - userRepository.anonymousUser + userRepository.anonymousUser, ); should(result).not.be.an.instanceOf(User); @@ -167,7 +167,7 @@ describe("Test: security/userRepository", () => { it("should reject if we try to remove the anonymous profile from the anonymous user", () => { return should( - userRepository.persist({ _id: "-1", profileIds: ["test"] }) + userRepository.persist({ _id: "-1", profileIds: ["test"] }), ).be.rejectedWith(BadRequestError, { id: "security.user.anonymous_profile_required", }); @@ -274,7 +274,7 @@ describe("Test: security/userRepository", () => { .calledWithMatch( { input: { resource: { _id: "foo" } } }, "foo", - "someStrategy" + "someStrategy", ); should(deleteMethod) @@ -282,7 +282,7 @@ describe("Test: security/userRepository", () => { .calledWithMatch( { input: { resource: { _id: "foo" } } }, "foo", - "someStrategy" + "someStrategy", ); }); @@ -336,7 +336,7 @@ describe("Test: security/userRepository", () => { "id", "profiles", "content", - "opts" + "opts", ); }); @@ -365,7 +365,7 @@ describe("Test: security/userRepository", () => { }); should( - userRepository.fromDTO.firstCall.args[0]._kuzzle_info.createdAt + userRepository.fromDTO.firstCall.args[0]._kuzzle_info.createdAt, ).approximately(Date.now(), 1000); should(userRepository.persist).calledWith(fakeUser, { @@ -385,7 +385,7 @@ describe("Test: security/userRepository", () => { { refresh: "wait_for", userId: "userId", - } + }, ); should(userRepository.persist).calledWith(fakeUser, { @@ -402,7 +402,7 @@ describe("Test: security/userRepository", () => { "id", [], {}, - { userId: "userId" } + { userId: "userId" }, ); should(ret).eql(fakeUser); @@ -414,14 +414,14 @@ describe("Test: security/userRepository", () => { userRepository.persist.rejects(error); await should(kuzzle.ask(createEvent, "id", [], {}, {})).rejectedWith( - error + error, ); error.id = "services.storage.document_already_exists"; await should(kuzzle.ask(createEvent, "id", [], {}, {})).rejectedWith( PreconditionError, - { id: "security.user.already_exists" } + { id: "security.user.already_exists" }, ); }); }); @@ -447,7 +447,7 @@ describe("Test: security/userRepository", () => { "id", "profiles", "content", - "opts" + "opts", ); }); @@ -475,7 +475,7 @@ describe("Test: security/userRepository", () => { }); should( - userRepository.fromDTO.firstCall.args[0]._kuzzle_info.createdAt + userRepository.fromDTO.firstCall.args[0]._kuzzle_info.createdAt, ).approximately(Date.now(), 1000); should(userRepository.persist).calledWith(fakeUser, { @@ -495,7 +495,7 @@ describe("Test: security/userRepository", () => { { refresh: "wait_for", userId: "userId", - } + }, ); should(userRepository.persist).calledWith(fakeUser, { @@ -514,7 +514,7 @@ describe("Test: security/userRepository", () => { {}, { userId: "userId", - } + }, ); should(ret).eql(fakeUser); @@ -525,7 +525,7 @@ describe("Test: security/userRepository", () => { userRepository.load.withArgs("id").rejects(error); await should(kuzzle.ask(replaceEvent, "id", [], {}, {})).rejectedWith( - error + error, ); }); }); @@ -559,7 +559,7 @@ describe("Test: security/userRepository", () => { "id", "profiles", "content", - "opts" + "opts", ); }); @@ -586,7 +586,7 @@ describe("Test: security/userRepository", () => { }); should( - userRepository.fromDTO.firstCall.args[0]._kuzzle_info.updatedAt + userRepository.fromDTO.firstCall.args[0]._kuzzle_info.updatedAt, ).approximately(Date.now(), 1000); should(userRepository.persist).calledWith(fakeUser, { @@ -623,7 +623,7 @@ describe("Test: security/userRepository", () => { }); should( - userRepository.fromDTO.firstCall.args[0]._kuzzle_info.updatedAt + userRepository.fromDTO.firstCall.args[0]._kuzzle_info.updatedAt, ).approximately(Date.now(), 1000); should(userRepository.persist).calledWith(fakeUser, { @@ -645,7 +645,7 @@ describe("Test: security/userRepository", () => { refresh: "wait_for", retryOnConflict: 123, userId: "userId", - } + }, ); should(userRepository.persist).calledWith(fakeUser, { @@ -665,7 +665,7 @@ describe("Test: security/userRepository", () => { {}, { userId: "userId", - } + }, ); should(ret).eql(fakeUser); @@ -676,7 +676,7 @@ describe("Test: security/userRepository", () => { userRepository.load.withArgs("id").rejects(error); await should(kuzzle.ask(updateEvent, "id", [], {}, {})).rejectedWith( - error + error, ); }); }); @@ -736,7 +736,7 @@ describe("Test: security/userRepository", () => { Repository.prototype.loadOneFromDatabase.resolves("foo"); await should(userRepository.loadOneFromDatabase("bar")).fulfilledWith( - "foo" + "foo", ); should(Repository.prototype.loadOneFromDatabase).calledWith("bar"); @@ -750,7 +750,7 @@ describe("Test: security/userRepository", () => { return should(userRepository.loadOneFromDatabase("foo")).rejectedWith( NotFoundError, - { id: "security.user.not_found" } + { id: "security.user.not_found" }, ); }); @@ -760,7 +760,7 @@ describe("Test: security/userRepository", () => { Repository.prototype.loadOneFromDatabase.rejects(error); return should(userRepository.loadOneFromDatabase("foo")).rejectedWith( - error + error, ); }); }); diff --git a/test/core/shared/repository.test.js b/test/core/shared/repository.test.js index 4c8873ab3a..ef02a7a6be 100644 --- a/test/core/shared/repository.test.js +++ b/test/core/shared/repository.test.js @@ -43,7 +43,7 @@ describe("Test: repositories/repository", () => { return should(repository.loadOneFromDatabase(-9999)).rejectedWith( NotFoundError, - { id: "services.storage.not_found" } + { id: "services.storage.not_found" }, ); }); @@ -54,7 +54,7 @@ describe("Test: repositories/repository", () => { return should(repository.loadOneFromDatabase("error")).rejectedWith( KuzzleInternalError, - { message: "error" } + { message: "error" }, ); }); @@ -145,7 +145,7 @@ describe("Test: repositories/repository", () => { KuzzleInternalError, { id: "services.cache.read_failed", - } + }, ); }); @@ -156,7 +156,7 @@ describe("Test: repositories/repository", () => { KuzzleInternalError, { id: "services.cache.read_failed", - } + }, ); }); @@ -195,7 +195,7 @@ describe("Test: repositories/repository", () => { return should(repository.load("error")).rejectedWith( KuzzleInternalError, - { message: "test" } + { message: "test" }, ); }); @@ -206,7 +206,7 @@ describe("Test: repositories/repository", () => { KuzzleInternalError, { id: "services.cache.read_failed", - } + }, ); }); @@ -273,7 +273,7 @@ describe("Test: repositories/repository", () => { kuzzle.internalIndex.index, repository.collection, "someId", - repository.serializeToDatabase(object) + repository.serializeToDatabase(object), ); }); }); @@ -286,7 +286,7 @@ describe("Test: repositories/repository", () => { "core:storage:private:document:delete", kuzzle.internalIndex.index, repository.collection, - "someId" + "someId", ); }); }); @@ -299,7 +299,7 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).calledWith( "core:cache:internal:del", - repository.getCacheKey("someId") + repository.getCacheKey("someId"), ); repository.cacheDb = cacheDbEnum.PUBLIC; @@ -308,7 +308,7 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).calledWith( "core:cache:public:del", - repository.getCacheKey("someId") + repository.getCacheKey("someId"), ); }); }); @@ -321,14 +321,14 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).calledWith( "core:cache:internal:del", - repository.getCacheKey("someId") + repository.getCacheKey("someId"), ); should(kuzzle.ask).calledWith( "core:storage:private:document:delete", kuzzle.internalIndex.index, repository.collection, - "someId" + "someId", ); }); }); @@ -343,7 +343,7 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).calledWith( "core:cache:internal:store", "someKey", - JSON.stringify(cachePojo) + JSON.stringify(cachePojo), ); }); @@ -354,7 +354,7 @@ describe("Test: repositories/repository", () => { "core:cache:internal:store", "someKey", JSON.stringify(cachePojo), - { ttl: 500 } + { ttl: 500 }, ); }); }); @@ -365,7 +365,7 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).calledWith( "core:cache:internal:persist", - repository.getCacheKey(cachePojo._id, repository.collection) + repository.getCacheKey(cachePojo._id, repository.collection), ); }); @@ -375,7 +375,7 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).calledWith( "core:cache:internal:expire", repository.getCacheKey(cachePojo._id, repository.collection), - 500 + 500, ); }); @@ -387,7 +387,7 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).calledWith( "core:cache:internal:expire", repository.getCacheKey(pojo._id, repository.collection), - 1234 + 1234, ); }); @@ -399,7 +399,7 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).calledWith( "core:cache:internal:expire", repository.getCacheKey(pojo._id, repository.collection), - 500 + 500, ); }); }); @@ -411,7 +411,7 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).calledWith( "core:cache:internal:expire", repository.getCacheKey(cachePojo._id, repository.collection), - -1 + -1, ); }); }); @@ -424,7 +424,7 @@ describe("Test: repositories/repository", () => { const serialized = repository.serializeToCache(object); should(Object.keys(serialized).length).be.exactly( - Object.keys(object).length + Object.keys(object).length, ); Object.keys(repository.serializeToCache(object)).forEach((key) => { should(object[key]).be.exactly(serialized[key]); @@ -458,7 +458,7 @@ describe("Test: repositories/repository", () => { kuzzle.internalIndex.index, repository.collection, { query: "noquery" }, - {} + {}, ); }); @@ -475,7 +475,7 @@ describe("Test: repositories/repository", () => { from: 13, scroll: "45s", size: 42, - } + }, ); should(response).be.an.Object(); @@ -487,7 +487,7 @@ describe("Test: repositories/repository", () => { kuzzle.internalIndex.index, repository.collection, { query: "noquery" }, - { from: 13, scroll: "45s", size: 42 } + { from: 13, scroll: "45s", size: 42 }, ); }); @@ -530,7 +530,7 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).be.calledWithMatch( "core:storage:private:document:scroll", "foo", - undefined + undefined, ); }); @@ -550,7 +550,7 @@ describe("Test: repositories/repository", () => { should(kuzzle.ask).be.calledWithMatch( "core:storage:private:document:scroll", "foo", - "bar" + "bar", ); }); diff --git a/test/core/shared/sdk/embeddedSdk.test.js b/test/core/shared/sdk/embeddedSdk.test.js index c4792214f1..6d0cc75a79 100644 --- a/test/core/shared/sdk/embeddedSdk.test.js +++ b/test/core/shared/sdk/embeddedSdk.test.js @@ -24,10 +24,10 @@ describe("EmbeddedSDK", () => { const SpyImpersonatedSdk = sinon.spy(); mockrequire( "../../../../lib/core/shared/sdk/impersonatedSdk", - SpyImpersonatedSdk + SpyImpersonatedSdk, ); const { EmbeddedSDK: MockEmbeddedSDK } = mockrequire.reRequire( - "../../../../lib/core/shared/sdk/embeddedSdk" + "../../../../lib/core/shared/sdk/embeddedSdk", ); try { @@ -53,7 +53,7 @@ describe("EmbeddedSDK", () => { }); should(() => embeddedSdk.as({ _id: 123 })).throw( PluginImplementationError, - { id: "plugin.context.invalid_user" } + { id: "plugin.context.invalid_user" }, ); }); }); @@ -83,7 +83,7 @@ describe("EmbeddedSDK", () => { should(() => embeddedSdk.query(forbiddenRequest)).throw( PluginImplementationError, - { id: "api.process.forbidden_embedded_sdk_action" } + { id: "api.process.forbidden_embedded_sdk_action" }, ); }); diff --git a/test/core/shared/sdk/funnelProtocol.test.js b/test/core/shared/sdk/funnelProtocol.test.js index b490c49ecf..6e0c01ea76 100644 --- a/test/core/shared/sdk/funnelProtocol.test.js +++ b/test/core/shared/sdk/funnelProtocol.test.js @@ -44,7 +44,7 @@ describe("Test: sdk/funnelProtocol", () => { try { should(kuzzle.on).be.calledOnce(); should(kuzzle.on.getCall(0).args[0]).be.eql( - "core:network:internal:message" + "core:network:internal:message", ); done(); @@ -105,11 +105,11 @@ describe("Test: sdk/funnelProtocol", () => { should( kuzzle.ask.withArgs( "core:security:user:get", - customUserRequest.__kuid__ - ) + customUserRequest.__kuid__, + ), ).be.calledOnce(); should(response.result.context.user._id).be.eql( - customUserRequest.__kuid__ + customUserRequest.__kuid__, ); }); }); @@ -134,7 +134,7 @@ describe("Test: sdk/funnelProtocol", () => { ForbiddenError, { id: "security.rights.forbidden", - } + }, ); }); @@ -151,7 +151,7 @@ describe("Test: sdk/funnelProtocol", () => { PluginImplementationError, { id: "plugin.context.invalid_user", - } + }, ); }); }); diff --git a/test/core/shared/sdk/impersonatedSdk.test.js b/test/core/shared/sdk/impersonatedSdk.test.js index 5c1ddf3648..2f32fb648a 100644 --- a/test/core/shared/sdk/impersonatedSdk.test.js +++ b/test/core/shared/sdk/impersonatedSdk.test.js @@ -66,7 +66,7 @@ describe("ImpersonatedSDK", () => { mockrequire.reRequire("../../../../lib/core/shared/sdk/impersonatedSdk"); ImpersonatedSdk = rewire( - "../../../../lib/core/shared/sdk/impersonatedSdk" + "../../../../lib/core/shared/sdk/impersonatedSdk", ); impersonatedSdk = new ImpersonatedSdk(impersonatedUserId); diff --git a/test/core/statistics/statistics.test.js b/test/core/statistics/statistics.test.js index ac8dfdd9e4..01e0138b31 100644 --- a/test/core/statistics/statistics.test.js +++ b/test/core/statistics/statistics.test.js @@ -410,7 +410,7 @@ describe("Test: statistics core component", () => { "core:cache:internal:store", "{stats/}" + stats.lastFrame, JSON.stringify(fakeStats), - { ttl: stats.ttl } + { ttl: stats.ttl }, ); }); diff --git a/test/core/storage/clientAdapter.test.js b/test/core/storage/clientAdapter.test.js index 3103564839..6152ad8526 100644 --- a/test/core/storage/clientAdapter.test.js +++ b/test/core/storage/clientAdapter.test.js @@ -25,10 +25,10 @@ describe("#core/storage/ClientAdapter", () => { mockRequire("../../../lib/util/mutex", { Mutex: MutexMock }); mockRequire( "../../../lib/service/storage/elasticsearch", - ElasticsearchMock + ElasticsearchMock, ); ClientAdapter = mockRequire.reRequire( - "../../../lib/core/storage/clientAdapter" + "../../../lib/core/storage/clientAdapter", ); }); @@ -50,7 +50,7 @@ describe("#core/storage/ClientAdapter", () => { [publicAdapter, privateAdapter].map((adapter) => { sinon.stub(adapter.cache); return adapter.init(); - }) + }), ); }); @@ -95,19 +95,19 @@ describe("#core/storage/ClientAdapter", () => { should(uninitializedAdapter.client.generateMissingAliases).calledOnce(); should(uninitializedAdapter.cache.addCollection).calledWith( "foo", - "foo1" + "foo1", ); should(uninitializedAdapter.cache.addCollection).calledWith( "foo", - "foo2" + "foo2", ); should(uninitializedAdapter.cache.addCollection).calledWith( "bar", - "bar1" + "bar1", ); should(uninitializedAdapter.cache.addCollection).calledWith( "bar", - "bar2" + "bar2", ); }); }); @@ -143,7 +143,7 @@ describe("#core/storage/ClientAdapter", () => { PreconditionError, { id: "services.storage.index_already_exists", - } + }, ); }); @@ -152,13 +152,13 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:index:create`, "foo", - { propagate: false } + { propagate: false }, ); should(adapter.client.createIndex).calledWith("foo"); should(adapter.cache.addIndex).calledWith("foo"); should(kuzzle.emit).not.be.calledWith( - "core:storage:index:create:after" + "core:storage:index:create:after", ); } }); @@ -168,7 +168,7 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:index:create`, "foo", - { indexCacheOnly: true } + { indexCacheOnly: true }, ); should(adapter.client.createIndex).not.be.called(); @@ -208,7 +208,7 @@ describe("#core/storage/ClientAdapter", () => { const res = await kuzzle.ask( `core:storage:${adapter.scope}:index:exist`, - "foo" + "foo", ); should(res).eql("bar"); @@ -221,7 +221,7 @@ describe("#core/storage/ClientAdapter", () => { adapter.cache.listIndexes.resolves("bar"); const res = await kuzzle.ask( - `core:storage:${adapter.scope}:index:list` + `core:storage:${adapter.scope}:index:list`, ); should(res).eql("bar"); @@ -234,7 +234,7 @@ describe("#core/storage/ClientAdapter", () => { adapter.client.stats.resolves("bar"); const res = await kuzzle.ask( - `core:storage:${adapter.scope}:index:stats` + `core:storage:${adapter.scope}:index:stats`, ); should(res).eql("bar"); @@ -251,7 +251,7 @@ describe("#core/storage/ClientAdapter", () => { const deleted = await kuzzle.ask( `core:storage:${adapter.scope}:index:mDelete`, - indexes + indexes, ); should(publicAdapter.client.deleteIndexes).calledWith(indexes); @@ -267,7 +267,7 @@ describe("#core/storage/ClientAdapter", () => { publicAdapter.cache.assertIndexExists.withArgs("bar").throws(err); await should( - publicAdapter.deleteIndexes(["foo", "bar", "baz"]) + publicAdapter.deleteIndexes(["foo", "bar", "baz"]), ).rejectedWith(err); should(publicAdapter.client.deleteIndexes).not.called(); @@ -284,7 +284,7 @@ describe("#core/storage/ClientAdapter", () => { `core:storage:${adapter.scope}:collection:create`, "foo", "bar", - "opts" + "opts", ); should(publicAdapter.client.createCollection) @@ -298,7 +298,7 @@ describe("#core/storage/ClientAdapter", () => { collection: "bar", index: "foo", scope: adapter.scope, - } + }, ); } }); @@ -310,7 +310,7 @@ describe("#core/storage/ClientAdapter", () => { "foo", "bar", "opts", - { propagate: false } + { propagate: false }, ); should(publicAdapter.client.createCollection) @@ -319,7 +319,7 @@ describe("#core/storage/ClientAdapter", () => { should(publicAdapter.cache.addCollection).calledWith("foo", "bar"); should(kuzzle.emit).not.be.calledWith( - "core:storage:collection:create:after" + "core:storage:collection:create:after", ); } }); @@ -331,7 +331,7 @@ describe("#core/storage/ClientAdapter", () => { "foo", "bar", "opts", - { indexCacheOnly: true } + { indexCacheOnly: true }, ); should(publicAdapter.client.createCollection).not.be.called(); @@ -343,7 +343,7 @@ describe("#core/storage/ClientAdapter", () => { collection: "bar", index: "foo", scope: adapter.scope, - } + }, ); } }); @@ -355,12 +355,12 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:collection:delete`, "foo", - "bar" + "bar", ); should(publicAdapter.client.deleteCollection).calledWith( "foo", - "bar" + "bar", ); should(publicAdapter.cache.removeCollection).calledWith("foo", "bar"); } @@ -372,7 +372,7 @@ describe("#core/storage/ClientAdapter", () => { publicAdapter.cache.assertCollectionExists.throws(err); await should(publicAdapter.deleteCollection("foo", "bar")).rejectedWith( - err + err, ); should(publicAdapter.client.deleteCollection).not.called(); @@ -385,7 +385,7 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:collection:exist`, "foo", - "bar" + "bar", ); should(adapter.cache.hasCollection) @@ -398,7 +398,7 @@ describe("#core/storage/ClientAdapter", () => { for (const adapter of [publicAdapter, privateAdapter]) { await kuzzle.ask( `core:storage:${adapter.scope}:collection:list`, - "foo" + "foo", ); should(adapter.cache.listCollections).calledOnce().calledWith("foo"); @@ -411,7 +411,7 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:collection:refresh`, "foo", - "bar" + "bar", ); should(adapter.client.refreshCollection) @@ -427,7 +427,7 @@ describe("#core/storage/ClientAdapter", () => { publicAdapter.cache.assertCollectionExists.throws(err); await should( - kuzzle.ask("core:storage:public:collection:refresh", "foo", "bar") + kuzzle.ask("core:storage:public:collection:refresh", "foo", "bar"), ).rejectedWith(err); should(publicAdapter.client.refreshCollection).not.called(); @@ -440,7 +440,7 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:collection:truncate`, "foo", - "bar" + "bar", ); should(adapter.cache.assertCollectionExists).calledWith("foo", "bar"); @@ -457,7 +457,7 @@ describe("#core/storage/ClientAdapter", () => { publicAdapter.cache.assertCollectionExists.throws(err); await should( - kuzzle.ask("core:storage:public:collection:truncate", "foo", "bar") + kuzzle.ask("core:storage:public:collection:truncate", "foo", "bar"), ).rejectedWith(err); should(publicAdapter.client.truncateCollection).not.called(); @@ -471,7 +471,7 @@ describe("#core/storage/ClientAdapter", () => { `core:storage:${adapter.scope}:collection:update`, "foo", "bar", - "changes" + "changes", ); should(adapter.cache.assertCollectionExists).calledWith("foo", "bar"); @@ -491,7 +491,7 @@ describe("#core/storage/ClientAdapter", () => { "core:storage:public:collection:update", "foo", "bar", - "changes" + "changes", ); await should(promise).rejectedWith(err); @@ -509,7 +509,7 @@ describe("#core/storage/ClientAdapter", () => { `core:storage:${adapter.scope}:mappings:get`, "foo", "bar", - "opts" + "opts", ); should(adapter.cache.assertCollectionExists).calledWith("foo", "bar"); @@ -529,7 +529,7 @@ describe("#core/storage/ClientAdapter", () => { "core:storage:public:mappings:get", "foo", "bar", - "opts" + "opts", ); await should(promise).rejectedWith(err); @@ -564,14 +564,14 @@ describe("#core/storage/ClientAdapter", () => { { propagate: true, indexCacheOnly: false, - } + }, ); should(adapter.client.createIndex).calledWith("index"); should(adapter.client.createCollection).calledWith( "index", "collection", - mappings.index.collection + mappings.index.collection, ); should(adapter.cache.addIndex).calledWith("index"); @@ -599,13 +599,13 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:mappings:import`, rawMappings, - { rawMappings: true } + { rawMappings: true }, ); should(adapter.client.createCollection).calledWith( "index", "collection", - mappings.index.collection + mappings.index.collection, ); } }); @@ -626,7 +626,7 @@ describe("#core/storage/ClientAdapter", () => { const result = kuzzle.ask( "core:storage:public:mappings:import", - mappings + mappings, ); await should(result).rejectedWith(BadRequestError, { @@ -641,7 +641,7 @@ describe("#core/storage/ClientAdapter", () => { publicAdapter.client.createIndex.rejects(err); return should( - kuzzle.ask("core:storage:public:mappings:import", mappings) + kuzzle.ask("core:storage:public:mappings:import", mappings), ).rejectedWith(err); }); @@ -654,7 +654,7 @@ describe("#core/storage/ClientAdapter", () => { publicAdapter.client.createIndex.onFirstCall().rejects(err); await should( - kuzzle.ask("core:storage:public:mappings:import", mappings) + kuzzle.ask("core:storage:public:mappings:import", mappings), ).fulfilled(); should(publicAdapter.client.createIndex).calledWith("index"); @@ -669,18 +669,18 @@ describe("#core/storage/ClientAdapter", () => { `core:storage:${adapter.scope}:mappings:update`, "index", "collection", - "mappings" + "mappings", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.updateMapping).calledWith( "index", "collection", - "mappings" + "mappings", ); } }); @@ -694,7 +694,7 @@ describe("#core/storage/ClientAdapter", () => { "core:storage:public:mappings:update", "index", "collection", - "mappings" + "mappings", ); await should(result).rejectedWith(err); @@ -713,19 +713,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.import).calledWith( "index", "collection", "documents", - "options" + "options", ); } }); @@ -740,7 +740,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); await should(result).rejectedWith(err); @@ -756,18 +756,18 @@ describe("#core/storage/ClientAdapter", () => { `core:storage:${adapter.scope}:document:count`, "index", "collection", - "filters" + "filters", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.count).calledWith( "index", "collection", - "filters" + "filters", ); } }); @@ -781,7 +781,7 @@ describe("#core/storage/ClientAdapter", () => { "core:storage:public:document:count", "index", "collection", - "filters" + "filters", ); await should(result).rejectedWith(err); @@ -798,19 +798,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "content", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.create).calledWith( "index", "collection", "content", - "options" + "options", ); } }); @@ -825,7 +825,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "content", - "options" + "options", ); await should(result).rejectedWith(err); @@ -843,12 +843,12 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "content", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.createOrReplace).calledWith( @@ -856,7 +856,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "content", - "options" + "options", ); } }); @@ -872,7 +872,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "content", - "options" + "options", ); await should(result).rejectedWith(err); @@ -889,19 +889,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "id", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.delete).calledWith( "index", "collection", "id", - "options" + "options", ); } }); @@ -916,7 +916,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "id", - "options" + "options", ); await should(result).rejectedWith(err); @@ -933,19 +933,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "query", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.deleteByQuery).calledWith( "index", "collection", "query", - "options" + "options", ); } }); @@ -960,7 +960,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "query", - "options" + "options", ); await should(result).rejectedWith(err); @@ -977,19 +977,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", ["query"], - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.deleteFields).calledWith( "index", "collection", ["query"], - "options" + "options", ); } }); @@ -1004,7 +1004,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "query", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1020,12 +1020,12 @@ describe("#core/storage/ClientAdapter", () => { `core:storage:${adapter.scope}:document:exist`, "index", "collection", - "id" + "id", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.exists).calledWith("index", "collection", "id"); @@ -1041,7 +1041,7 @@ describe("#core/storage/ClientAdapter", () => { "core:storage:public:document:exist", "index", "collection", - "id" + "id", ); await should(result).rejectedWith(err); @@ -1057,12 +1057,12 @@ describe("#core/storage/ClientAdapter", () => { `core:storage:${adapter.scope}:document:get`, "index", "collection", - "id" + "id", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.get).calledWith("index", "collection", "id"); @@ -1078,7 +1078,7 @@ describe("#core/storage/ClientAdapter", () => { "core:storage:public:document:get", "index", "collection", - "id" + "id", ); await should(result).rejectedWith(err); @@ -1104,13 +1104,13 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:document:import`, - fixtures + fixtures, ); should(adapter.client.import).calledWith( "index", "collection", - fixtures.index.collection + fixtures.index.collection, ); } }); @@ -1131,7 +1131,7 @@ describe("#core/storage/ClientAdapter", () => { const result = kuzzle.ask( "core:storage:public:document:import", - fixtures + fixtures, ); await should(result).rejectedWith(BadRequestError, { @@ -1144,7 +1144,7 @@ describe("#core/storage/ClientAdapter", () => { publicAdapter.client.import.resolves({ errors: ["oh", "noes"] }); await should( - kuzzle.ask("core:storage:public:document:import", fixtures) + kuzzle.ask("core:storage:public:document:import", fixtures), ).rejectedWith(PartialError, { id: "services.storage.import_failed" }); }); }); @@ -1157,19 +1157,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.mCreate).calledWith( "index", "collection", "documents", - "options" + "options", ); } }); @@ -1184,7 +1184,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1201,19 +1201,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.mCreateOrReplace).calledWith( "index", "collection", "documents", - "options" + "options", ); } }); @@ -1228,7 +1228,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1245,19 +1245,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "ids", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.mDelete).calledWith( "index", "collection", "ids", - "options" + "options", ); } }); @@ -1272,7 +1272,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "ids", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1289,19 +1289,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.mReplace).calledWith( "index", "collection", "documents", - "options" + "options", ); } }); @@ -1316,7 +1316,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1333,19 +1333,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.mUpdate).calledWith( "index", "collection", "documents", - "options" + "options", ); } }); @@ -1360,7 +1360,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1377,19 +1377,19 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.mUpsert).calledWith( "index", "collection", "documents", - "options" + "options", ); } }); @@ -1404,7 +1404,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "documents", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1422,12 +1422,12 @@ describe("#core/storage/ClientAdapter", () => { "collection", "query", "callback", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.mExecute).calledWith( @@ -1435,7 +1435,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "query", "callback", - "options" + "options", ); } }); @@ -1451,7 +1451,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "query", "callback", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1467,12 +1467,12 @@ describe("#core/storage/ClientAdapter", () => { `core:storage:${adapter.scope}:document:mGet`, "index", "collection", - "ids" + "ids", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.mGet).calledWith("index", "collection", "ids"); @@ -1489,7 +1489,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "ids", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1507,12 +1507,12 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "content", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.replace).calledWith( @@ -1520,7 +1520,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "content", - "options" + "options", ); } }); @@ -1536,7 +1536,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "content", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1551,7 +1551,7 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:document:scroll`, "id", - "options" + "options", ); should(adapter.client.scroll).calledWith("id", "options"); @@ -1567,12 +1567,12 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "query", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.search).calledWith( @@ -1581,7 +1581,7 @@ describe("#core/storage/ClientAdapter", () => { collection: "collection", searchBody: "query", }, - "options" + "options", ); } }); @@ -1596,7 +1596,7 @@ describe("#core/storage/ClientAdapter", () => { "index", "collection", "query", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1612,7 +1612,7 @@ describe("#core/storage/ClientAdapter", () => { `core:storage:${adapter.scope}:document:multiSearch`, [{ index: "index1", collections: ["collection1", "collection2"] }], "query", - "options" + "options", ); should(adapter.cache.assertCollectionExists) @@ -1629,7 +1629,7 @@ describe("#core/storage/ClientAdapter", () => { ], searchBody: "query", }, - "options" + "options", ); } }); @@ -1643,7 +1643,7 @@ describe("#core/storage/ClientAdapter", () => { "core:storage:public:document:multiSearch", [{ index: "index1", collections: ["collection1", "collection2"] }], "query", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1661,12 +1661,12 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "content", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.update).calledWith( @@ -1674,7 +1674,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "content", - "options" + "options", ); } }); @@ -1690,7 +1690,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "content", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1708,12 +1708,12 @@ describe("#core/storage/ClientAdapter", () => { "collection", "query", "changes", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.updateByQuery).calledWith( @@ -1721,7 +1721,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "query", "changes", - "options" + "options", ); } }); @@ -1737,7 +1737,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "query", "changes", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1755,12 +1755,12 @@ describe("#core/storage/ClientAdapter", () => { "collection", "query", "changes", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.bulkUpdateByQuery).calledWith( @@ -1768,7 +1768,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "query", "changes", - "options" + "options", ); } }); @@ -1784,7 +1784,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "query", "changes", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1802,12 +1802,12 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "changes", - "options" + "options", ); should(adapter.cache.assertCollectionExists).calledWith( "index", - "collection" + "collection", ); should(adapter.client.upsert).calledWith( @@ -1815,7 +1815,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "changes", - "options" + "options", ); } }); @@ -1831,7 +1831,7 @@ describe("#core/storage/ClientAdapter", () => { "collection", "id", "changes", - "options" + "options", ); await should(result).rejectedWith(err); @@ -1847,7 +1847,7 @@ describe("#core/storage/ClientAdapter", () => { for (const adapter of [publicAdapter, privateAdapter]) { await kuzzle.ask( `core:storage:${adapter.scope}:cache:addIndex`, - "index" + "index", ); should(adapter.cache.addIndex).calledWith("index"); @@ -1860,7 +1860,7 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:cache:addCollection`, "index", - "collection" + "collection", ); should(adapter.cache.addCollection).calledWith("index", "collection"); @@ -1873,7 +1873,7 @@ describe("#core/storage/ClientAdapter", () => { for (const adapter of [publicAdapter, privateAdapter]) { await kuzzle.ask( `core:storage:${adapter.scope}:cache:removeIndexes`, - ["index1", "index2", "index3"] + ["index1", "index2", "index3"], ); should(adapter.cache.removeIndex).calledWith("index1"); @@ -1887,13 +1887,13 @@ describe("#core/storage/ClientAdapter", () => { await kuzzle.ask( `core:storage:${adapter.scope}:cache:removeCollection`, "index", - "collection" + "collection", ); should(adapter.cache.removeIndex).not.called(); should(adapter.cache.removeCollection).calledWith( "index", - "collection" + "collection", ); } }); diff --git a/test/core/storage/indexCache.test.js b/test/core/storage/indexCache.test.js index 4b0f4b94e2..9c01ccebe8 100644 --- a/test/core/storage/indexCache.test.js +++ b/test/core/storage/indexCache.test.js @@ -132,7 +132,7 @@ describe("#core/storage/indexCache", () => { PreconditionError, { id: "services.storage.unknown_index", - } + }, ); }); @@ -143,12 +143,12 @@ describe("#core/storage/indexCache", () => { should(() => indexCache.assertCollectionExists("foo", "baz")).throw( PreconditionError, - { id: "services.storage.unknown_collection" } + { id: "services.storage.unknown_collection" }, ); should(() => indexCache.assertCollectionExists("fooz", "bar")).throw( PreconditionError, - { id: "services.storage.unknown_index" } + { id: "services.storage.unknown_index" }, ); }); }); diff --git a/test/core/storage/storageEngine.test.js b/test/core/storage/storageEngine.test.js index 29c08e485c..6878cb5e99 100644 --- a/test/core/storage/storageEngine.test.js +++ b/test/core/storage/storageEngine.test.js @@ -16,7 +16,7 @@ describe("#core/storage/StorageEngine", () => { before(() => { mockRequire("../../../lib/core/storage/clientAdapter", ClientAdapterMock); StorageEngine = mockRequire.reRequire( - "../../../lib/core/storage/storageEngine" + "../../../lib/core/storage/storageEngine", ); }); diff --git a/test/core/validation/baseType.test.js b/test/core/validation/baseType.test.js index 88024d6d34..0294c8bd64 100644 --- a/test/core/validation/baseType.test.js +++ b/test/core/validation/baseType.test.js @@ -40,19 +40,19 @@ describe("Test: validation/baseType", () => { it("should be true with proper arguments", () => { should( - baseType.checkAllowedProperties(genericMock, ["foo", "mod"]) + baseType.checkAllowedProperties(genericMock, ["foo", "mod"]), ).be.true(); }); it("should be false if the first argument is not an object", () => { should( - baseType.checkAllowedProperties("notAnObject", ["foo"]) + baseType.checkAllowedProperties("notAnObject", ["foo"]), ).be.false(); }); it("should be false if one of the property is not allowed", () => { should( - baseType.checkAllowedProperties({ foo: "bar", baz: "bar" }, ["foo"]) + baseType.checkAllowedProperties({ foo: "bar", baz: "bar" }, ["foo"]), ).be.false(); }); }); diff --git a/test/core/validation/init.test.js b/test/core/validation/init.test.js index 37ee43f698..92cefb34e5 100644 --- a/test/core/validation/init.test.js +++ b/test/core/validation/init.test.js @@ -58,7 +58,7 @@ describe("Test: validation initialization", () => { ].forEach((fileName) => { mockRequire( "../../../lib/core/validation/types/" + fileName, - validationStub + validationStub, ); }); @@ -184,7 +184,7 @@ describe("Test: validation initialization", () => { "anIndex", "aCollection", { a: "bad specification" }, - true + true, ) .then((result) => { should(curateCollectionSpecificationStub.callCount).be.eql(1); @@ -265,7 +265,7 @@ describe("Test: validation initialization", () => { validation.addType(validationType); } catch (error) { should(error.message).startWith( - 'The type "aType" must implement a function "validate".' + 'The type "aType" must implement a function "validate".', ); should(error.id).be.eql("validation.types.missing_function"); } @@ -282,7 +282,7 @@ describe("Test: validation initialization", () => { validation.addType(validationType); } catch (error) { should(error.message).startWith( - 'The type "aType" must implement a function "validateFieldSpecification".' + 'The type "aType" must implement a function "validateFieldSpecification".', ); should(error.id).be.eql("validation.types.missing_function"); } @@ -300,7 +300,7 @@ describe("Test: validation initialization", () => { validation.addType(validationType); } catch (error) { should(error.message).startWith( - 'The type "aType" must implement a function "getStrictness".' + 'The type "aType" must implement a function "getStrictness".', ); should(error.id).be.eql("validation.types.missing_function"); } @@ -328,7 +328,7 @@ describe("Test: validation initialization", () => { indexName, collectionName, collectionSpec, - dryRun + dryRun, ) .then((returnedSpec) => { should(returnedSpec).be.deepEqual(expectedReturn); @@ -350,8 +350,8 @@ describe("Test: validation initialization", () => { indexName, collectionName, collectionSpec, - dryRun - ) + dryRun, + ), ).be.rejectedWith(PreconditionError, { id: "validation.assert.unexpected_properties", }); @@ -374,13 +374,13 @@ describe("Test: validation initialization", () => { collectionName, collectionSpec, dryRun, - verboseErrors + verboseErrors, ) .then((response) => { should(response.isValid).be.false(); should(response.errors.length).be.eql(1); should(response.errors[0]).be.eql( - `The object "${indexName}.${collectionName}" contains unexpected properties (allowed: strict, fields, validators).` + `The object "${indexName}.${collectionName}" contains unexpected properties (allowed: strict, fields, validators).`, ); }); }); @@ -414,7 +414,7 @@ describe("Test: validation initialization", () => { indexName, collectionName, collectionSpec, - dryRun + dryRun, ) .then((returnedSpec) => { should(returnedSpec).be.deepEqual(expectedReturn); @@ -452,7 +452,7 @@ describe("Test: validation initialization", () => { collectionName, collectionSpec, dryRun, - verboseErrors + verboseErrors, ) .then((returnedSpec) => { should(returnedSpec).be.deepEqual(expectedReturn); @@ -481,8 +481,8 @@ describe("Test: validation initialization", () => { indexName, collectionName, collectionSpec, - dryRun - ) + dryRun, + ), ).be.rejectedWith("an error"); }); @@ -506,8 +506,8 @@ describe("Test: validation initialization", () => { indexName, collectionName, collectionSpec, - dryRun - ) + dryRun, + ), ).be.rejectedWith(BadRequestError, { id: "validation.assert.invalid_specifications", }); @@ -536,7 +536,7 @@ describe("Test: validation initialization", () => { collectionName, collectionSpec, dryRun, - verboseErrors + verboseErrors, ) .catch((error) => { should(error.message).be.exactly("an error"); @@ -567,14 +567,14 @@ describe("Test: validation initialization", () => { indexName, collectionName, collectionSpec, - dryRun + dryRun, ) .then((returnedSpec) => { should(returnedSpec).be.deepEqual(expectedReturn); should(curateValidatorFilterStub.args[0][0]).be.eql(indexName); should(curateValidatorFilterStub.args[0][1]).be.eql(collectionName); should(curateValidatorFilterStub.args[0][2]).be.eql( - collectionSpec.validators + collectionSpec.validators, ); should(curateValidatorFilterStub.args[0][3]).be.eql(dryRun); }); @@ -598,8 +598,8 @@ describe("Test: validation initialization", () => { indexName, collectionName, collectionSpec, - dryRun - ) + dryRun, + ), ).be.rejectedWith(BadRequestError, { id: "validation.assert.invalid_filters", }); @@ -646,14 +646,14 @@ describe("Test: validation initialization", () => { validation.curateFieldSpecification = curateFieldSpecificationStub; should( - validation.structureCollectionValidation(collectionSpec) + validation.structureCollectionValidation(collectionSpec), ).be.deepEqual(expectedRawFields); should(curateFieldSpecificationStub.callCount).be.eql(3); }); it("should return an empty object if no field is specified", () => { should( - validation.structureCollectionValidation({ fields: {} }) + validation.structureCollectionValidation({ fields: {} }), ).be.deepEqual({}); }); @@ -672,7 +672,7 @@ describe("Test: validation initialization", () => { validation.curateFieldSpecification = curateFieldSpecificationStub; should(() => - validation.structureCollectionValidation(collectionSpec) + validation.structureCollectionValidation(collectionSpec), ).throw("an error"); should(curateFieldSpecificationStub.callCount).be.eql(1); @@ -708,7 +708,7 @@ describe("Test: validation initialization", () => { collectionSpec, indexName, collectionName, - verboseErrors + verboseErrors, ); should(response.isValid).be.false(); @@ -750,7 +750,7 @@ describe("Test: validation initialization", () => { }; should(validation.curateFieldSpecification(fieldSpec)).be.deepEqual( - expectedReturn + expectedReturn, ); }); @@ -777,7 +777,7 @@ describe("Test: validation initialization", () => { }; should(validation.curateFieldSpecification(fieldSpec)).be.deepEqual( - expectedReturn + expectedReturn, ); }); @@ -814,12 +814,12 @@ describe("Test: validation initialization", () => { "anIndex", "aCollection", "aField", - true + true, ); should(response.isValid).be.false(); should(response.errors.length).be.eql(1); should(response.errors[0]).startWith( - 'The object "anIndex.aCollection.aField" contains unexpected properties' + 'The object "anIndex.aCollection.aField" contains unexpected properties', ); }); @@ -853,7 +853,7 @@ describe("Test: validation initialization", () => { }; should(validation.curateFieldSpecification(fieldSpec)).be.deepEqual( - expectedReturn + expectedReturn, ); }); @@ -920,7 +920,7 @@ describe("Test: validation initialization", () => { "anIndex", "aCollection", "aField", - true + true, ); should(response).be.deepEqual(anError); @@ -956,7 +956,7 @@ describe("Test: validation initialization", () => { indexName, collectionName, fieldName, - verboseErrors + verboseErrors, ); should(response.isValid).be.false(); should(response.errors.length).be.eql(2); @@ -974,7 +974,7 @@ describe("Test: validation initialization", () => { should(() => { validation.curateFieldSpecificationFormat(fieldSpec); }).throw( - 'Missing property "type" in field "undefined.undefined.undefined".' + 'Missing property "type" in field "undefined.undefined.undefined".', ); }); @@ -988,7 +988,7 @@ describe("Test: validation initialization", () => { should(() => { validation.curateFieldSpecificationFormat(fieldSpec); }).throw( - 'In "undefined.undefined.undefined": unknown type "not_recognized".' + 'In "undefined.undefined.undefined": unknown type "not_recognized".', ); }); @@ -1007,7 +1007,7 @@ describe("Test: validation initialization", () => { should(() => { validation.curateFieldSpecificationFormat(fieldSpec); }).throw( - 'The object "undefined.undefined.undefined.multivalued" contains unexpected properties (allowed: value, minCount, maxCount).' + 'The object "undefined.undefined.undefined.multivalued" contains unexpected properties (allowed: value, minCount, maxCount).', ); }); @@ -1024,7 +1024,7 @@ describe("Test: validation initialization", () => { should(() => { validation.curateFieldSpecificationFormat(fieldSpec); }).throw( - 'Missing property "value" in field "undefined.undefined.undefined.multivalued".' + 'Missing property "value" in field "undefined.undefined.undefined.multivalued".', ); }); @@ -1044,7 +1044,7 @@ describe("Test: validation initialization", () => { should(() => { validation.curateFieldSpecificationFormat(fieldSpec); }).throw( - 'Field "undefined.undefined.undefined": cannot set a property "minCount" if the field is not multivalued.' + 'Field "undefined.undefined.undefined": cannot set a property "minCount" if the field is not multivalued.', ); }); @@ -1064,7 +1064,7 @@ describe("Test: validation initialization", () => { should(() => { validation.curateFieldSpecificationFormat(fieldSpec); }).throw( - 'Field "undefined.undefined.undefined": cannot set a property "maxCount" if the field is not multivalued.' + 'Field "undefined.undefined.undefined": cannot set a property "maxCount" if the field is not multivalued.', ); }); @@ -1085,7 +1085,7 @@ describe("Test: validation initialization", () => { should(() => { validation.curateFieldSpecificationFormat(fieldSpec); }).throw( - 'Property "undefined.undefined.undefined": invalid range (minCount > maxCount).' + 'Property "undefined.undefined.undefined": invalid range (minCount > maxCount).', ); }); @@ -1103,7 +1103,7 @@ describe("Test: validation initialization", () => { }; should(() => validation.curateFieldSpecificationFormat(fieldSpec)).throw( - 'Wrong type for parameter "undefined.undefined.undefined.multivalued.value" (expected: boolean).' + 'Wrong type for parameter "undefined.undefined.undefined.multivalued.value" (expected: boolean).', ); }); @@ -1117,7 +1117,7 @@ describe("Test: validation initialization", () => { }; should( - validation.curateFieldSpecificationFormat(fieldSpec).isValid + validation.curateFieldSpecificationFormat(fieldSpec).isValid, ).be.true(); }); @@ -1136,7 +1136,7 @@ describe("Test: validation initialization", () => { }; should( - validation.curateFieldSpecificationFormat(fieldSpec).isValid + validation.curateFieldSpecificationFormat(fieldSpec).isValid, ).be.true(); }); }); diff --git a/test/core/validation/types/anything.test.js b/test/core/validation/types/anything.test.js index 03568fdbcb..81951ad100 100644 --- a/test/core/validation/types/anything.test.js +++ b/test/core/validation/types/anything.test.js @@ -28,7 +28,7 @@ describe("Test: validation/types/anything", () => { describe("#validateFieldSpecification", () => { it("should always return the provided options", () => { should(anythingType.validateFieldSpecification("foobar")).be.equal( - "foobar" + "foobar", ); }); }); diff --git a/test/core/validation/types/date.test.js b/test/core/validation/types/date.test.js index 13fbef181e..a4a95d0934 100644 --- a/test/core/validation/types/date.test.js +++ b/test/core/validation/types/date.test.js @@ -40,24 +40,24 @@ describe("Test: validation/types/date", () => { }; should(dateType.validateFieldSpecification(typeOptions)).be.deepEqual( - typeOptions + typeOptions, ); }); it('should throw if an invalid "formats" options is provided', () => { should(() => dateType.validateFieldSpecification({ formats: [] })).throw( PreconditionError, - { id: "validation.assert.invalid_type" } + { id: "validation.assert.invalid_type" }, ); should(() => - dateType.validateFieldSpecification({ formats: null }) + dateType.validateFieldSpecification({ formats: null }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); }); it('should throw if the "formats" option contains an unknown format', () => { should(() => - dateType.validateFieldSpecification({ formats: ["foobar"] }) + dateType.validateFieldSpecification({ formats: ["foobar"] }), ).throw(PreconditionError, { id: "validation.types.invalid_date_format", message: "The following date types are invalid: foobar.", @@ -66,7 +66,7 @@ describe("Test: validation/types/date", () => { should(() => dateType.validateFieldSpecification({ formats: ["foo", "epoch_millis", "bar"], - }) + }), ).throw(PreconditionError, { id: "validation.types.invalid_date_format", message: "The following date types are invalid: foo, bar.", @@ -80,7 +80,7 @@ describe("Test: validation/types/date", () => { id: "validation.assert.unexpected_properties", message: 'The object "range" contains unexpected properties (allowed: min, max).', - } + }, ); should(() => dateType.validateFieldSpecification({ range: [] })).throw( @@ -89,11 +89,11 @@ describe("Test: validation/types/date", () => { id: "validation.assert.unexpected_properties", message: 'The object "range" contains unexpected properties (allowed: min, max).', - } + }, ); should(() => - dateType.validateFieldSpecification({ range: { unknown: null } }) + dateType.validateFieldSpecification({ range: { unknown: null } }), ).throw(PreconditionError, { id: "validation.assert.unexpected_properties", message: @@ -105,7 +105,7 @@ describe("Test: validation/types/date", () => { const typeOptions = { range: { min: "NOW" } }; should(dateType.validateFieldSpecification(typeOptions)).be.deepEqual( - typeOptions + typeOptions, ); }); @@ -113,27 +113,27 @@ describe("Test: validation/types/date", () => { const typeOptions = { range: { max: "NOW" } }; should(dateType.validateFieldSpecification(typeOptions)).be.deepEqual( - typeOptions + typeOptions, ); }); it('should throw if "min" is not a valid date', () => { should(() => - dateType.validateFieldSpecification({ range: { min: "foobar" } }) + dateType.validateFieldSpecification({ range: { min: "foobar" } }), ).throw(PreconditionError, { id: "validation.types.invalid_date" }); should(() => - dateType.validateFieldSpecification({ range: { min: null } }) + dateType.validateFieldSpecification({ range: { min: null } }), ).throw(PreconditionError, { id: "validation.types.invalid_date" }); }); it('should throw if "max" is not a valid date', () => { should(() => - dateType.validateFieldSpecification({ range: { max: "foobar" } }) + dateType.validateFieldSpecification({ range: { max: "foobar" } }), ).throw(PreconditionError, { id: "validation.types.invalid_date" }); should(() => - dateType.validateFieldSpecification({ range: { max: null } }) + dateType.validateFieldSpecification({ range: { max: null } }), ).throw(PreconditionError, { id: "validation.types.invalid_date" }); }); @@ -145,7 +145,7 @@ describe("Test: validation/types/date", () => { should(() => dateType.validateFieldSpecification(typeOptions)).throw( PreconditionError, - { id: "validation.assert.invalid_range" } + { id: "validation.assert.invalid_range" }, ); }); @@ -181,7 +181,7 @@ describe("Test: validation/types/date", () => { }); should( - dateType.validate(typeOptions, "foobar", errorMessages) + dateType.validate(typeOptions, "foobar", errorMessages), ).be.false(); should(errorMessages).be.deepEqual(["The date format is invalid."]); }); @@ -203,7 +203,7 @@ describe("Test: validation/types/date", () => { }); should( - dateType.validate(typeOptions, Date.now() - 10000, errorMessages) + dateType.validate(typeOptions, Date.now() - 10000, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ "The provided date is before the defined minimum.", @@ -223,7 +223,7 @@ describe("Test: validation/types/date", () => { try { should(dateType.validate(typeOptions, Date.now() + 10, [])).be.true(); should( - dateType.validate(typeOptions, Date.now() - 10, []) + dateType.validate(typeOptions, Date.now() - 10, []), ).be.false(); done(); } catch (e) { @@ -253,7 +253,7 @@ describe("Test: validation/types/date", () => { }); should( - dateType.validate(typeOptions, Date.now() + 1000, errorMessages) + dateType.validate(typeOptions, Date.now() + 1000, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ "The provided date is after the defined maximum.", @@ -272,7 +272,7 @@ describe("Test: validation/types/date", () => { setTimeout(() => { try { should( - dateType.validate(typeOptions, Date.now() + 10, []) + dateType.validate(typeOptions, Date.now() + 10, []), ).be.false(); should(dateType.validate(typeOptions, Date.now() - 10, [])).be.true(); done(); @@ -413,7 +413,7 @@ describe("Test: validation/types/date", () => { before(() => { mockrequire("moment", momentMock); DateWithMockedMoment = mockrequire.reRequire( - "../../../../lib/core/validation/types/date" + "../../../../lib/core/validation/types/date", ); }); @@ -445,7 +445,7 @@ describe("Test: validation/types/date", () => { should(errors).be.an.Array().and.be.empty(); should(momentMock.unix.callCount).be.eql( - format === "epoch_second" ? 1 : 0 + format === "epoch_second" ? 1 : 0, ); should(momentMock.utc).calledWith(now); diff --git a/test/core/validation/types/email.test.js b/test/core/validation/types/email.test.js index c1be77913e..193064ed13 100644 --- a/test/core/validation/types/email.test.js +++ b/test/core/validation/types/email.test.js @@ -24,7 +24,7 @@ describe("Test: validation/types/email", () => { describe("#validate", () => { it("should return true if the provided email is valid", () => { should( - emailType.validate({ notEmpty: true }, "user@domain.com", []) + emailType.validate({ notEmpty: true }, "user@domain.com", []), ).be.true(); }); @@ -38,19 +38,19 @@ describe("Test: validation/types/email", () => { const errorMessage = []; should( - emailType.validate({ notEmpty: true }, "", errorMessage) + emailType.validate({ notEmpty: true }, "", errorMessage), ).be.false(); should(errorMessage).be.deepEqual(["The string must not be empty."]); errorMessage.shift(); should( - emailType.validate({ notEmpty: true }, undefined, errorMessage) + emailType.validate({ notEmpty: true }, undefined, errorMessage), ).be.false(); should(errorMessage).be.deepEqual(["Field cannot be undefined or null"]); errorMessage.shift(); should( - emailType.validate({ notEmpty: true }, null, errorMessage) + emailType.validate({ notEmpty: true }, null, errorMessage), ).be.false(); should(errorMessage).be.deepEqual(["Field cannot be undefined or null"]); }); @@ -59,7 +59,7 @@ describe("Test: validation/types/email", () => { const errorMessage = []; should( - emailType.validate({ notEmpty: true }, "not an email", errorMessage) + emailType.validate({ notEmpty: true }, "not an email", errorMessage), ).be.false(); should(errorMessage).be.deepEqual([ "The string must be a valid email address.", @@ -73,8 +73,8 @@ describe("Test: validation/types/email", () => { emailType.validate( { notEmpty: true }, { not: "a string" }, - errorMessage - ) + errorMessage, + ), ).be.false(); should(errorMessage).be.deepEqual(["The field must be a string."]); }); @@ -91,7 +91,7 @@ describe("Test: validation/types/email", () => { should( emailType.validateFieldSpecification({ notEmpty: true, - }) + }), ).be.deepEqual({ notEmpty: true, }); @@ -99,7 +99,7 @@ describe("Test: validation/types/email", () => { it('should throw if the provided "notEmpty" option is invalid', () => { should(() => - emailType.validateFieldSpecification({ notEmpty: "foobar" }) + emailType.validateFieldSpecification({ notEmpty: "foobar" }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); }); }); diff --git a/test/core/validation/types/enum.test.js b/test/core/validation/types/enum.test.js index 2dbe383337..3d7dd6120b 100644 --- a/test/core/validation/types/enum.test.js +++ b/test/core/validation/types/enum.test.js @@ -37,12 +37,12 @@ describe("Test: validation/types/enum", () => { enumType.validate( typeOptions, "not the string you are looking for", - errorMessage - ) + errorMessage, + ), ).be.false(); should(errorMessage).be.deepEqual([ `The field only accepts following values: "${typeOptions.values.join( - ", " + ", ", )}".`, ]); }); @@ -51,7 +51,7 @@ describe("Test: validation/types/enum", () => { const errorMessage = []; should( - enumType.validate(typeOptions, { not: "a string" }, errorMessage) + enumType.validate(typeOptions, { not: "a string" }, errorMessage), ).be.false(); should(errorMessage).be.deepEqual(["The field must be a string."]); }); @@ -61,26 +61,26 @@ describe("Test: validation/types/enum", () => { it("should throw if no values are provided", () => { should(() => enumType.validateFieldSpecification({})).throw( PreconditionError, - { id: "validation.types.missing_enum_values" } + { id: "validation.types.missing_enum_values" }, ); should(() => enumType.validateFieldSpecification({ values: [] })).throw( PreconditionError, - { id: "validation.assert.invalid_type" } + { id: "validation.assert.invalid_type" }, ); should(() => - enumType.validateFieldSpecification({ values: "foobar" }) + enumType.validateFieldSpecification({ values: "foobar" }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); }); it("should throw if a listed value is not a string", () => { should(() => - enumType.validateFieldSpecification({ values: [true, 42, "a string"] }) + enumType.validateFieldSpecification({ values: [true, 42, "a string"] }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); should(() => - enumType.validateFieldSpecification({ values: ["a string", null] }) + enumType.validateFieldSpecification({ values: ["a string", null] }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); }); @@ -88,7 +88,7 @@ describe("Test: validation/types/enum", () => { should( enumType.validateFieldSpecification({ values: ["a string", "another string", "one more string"], - }) + }), ).be.deepEqual({ values: ["a string", "another string", "one more string"], }); diff --git a/test/core/validation/types/geoPoint.test.js b/test/core/validation/types/geoPoint.test.js index e877bf79a0..5d88934d43 100644 --- a/test/core/validation/types/geoPoint.test.js +++ b/test/core/validation/types/geoPoint.test.js @@ -28,7 +28,7 @@ describe("Test: validation/types/geoPoint", () => { const errorMessages = []; should( - geoPointType.validate({}, { not: "a geopoint" }, errorMessages) + geoPointType.validate({}, { not: "a geopoint" }, errorMessages), ).be.false(); should(errorMessages).be.deepEqual(["Invalid GeoPoint format"]); }); diff --git a/test/core/validation/types/geoShape.test.js b/test/core/validation/types/geoShape.test.js index ce9e6ade4e..3a7a1072a9 100644 --- a/test/core/validation/types/geoShape.test.js +++ b/test/core/validation/types/geoShape.test.js @@ -110,8 +110,8 @@ describe("Test: validation/types/geoShape", () => { geoShapeType.recursiveShapeValidation( allowedShapes, shape, - errorMessages - ) + errorMessages, + ), ).be.false(); should(errorMessages).be.deepEqual([]); }); @@ -128,7 +128,7 @@ describe("Test: validation/types/geoShape", () => { GeoShapeType.__set__("isPoint", isPointStub); should( - geoShapeType.recursiveShapeValidation(allowedShapes, shape, []) + geoShapeType.recursiveShapeValidation(allowedShapes, shape, []), ).be.true(); should(isPointStub.callCount).be.eql(1); }); @@ -145,7 +145,7 @@ describe("Test: validation/types/geoShape", () => { GeoShapeType.__set__("isLine", isLineStub); should( - geoShapeType.recursiveShapeValidation(allowedShapes, shape, []) + geoShapeType.recursiveShapeValidation(allowedShapes, shape, []), ).be.true(); should(isLineStub.callCount).be.eql(1); }); @@ -162,7 +162,7 @@ describe("Test: validation/types/geoShape", () => { GeoShapeType.__set__("isPolygon", isPolygonStub); should( - geoShapeType.recursiveShapeValidation(allowedShapes, shape, []) + geoShapeType.recursiveShapeValidation(allowedShapes, shape, []), ).be.true(); should(isPolygonStub.callCount).be.eql(1); }); @@ -184,7 +184,7 @@ describe("Test: validation/types/geoShape", () => { GeoShapeType.__set__("isPoint", isPointStub); should( - geoShapeType.recursiveShapeValidation(allowedShapes, shape, []) + geoShapeType.recursiveShapeValidation(allowedShapes, shape, []), ).be.true(); should(isPointStub.callCount).be.eql(1); }); @@ -201,7 +201,7 @@ describe("Test: validation/types/geoShape", () => { GeoShapeType.__set__("isEnvelope", isEnvelopeStub); should( - geoShapeType.recursiveShapeValidation(allowedShapes, shape, []) + geoShapeType.recursiveShapeValidation(allowedShapes, shape, []), ).be.true(); should(isEnvelopeStub.callCount).be.eql(1); }); @@ -220,7 +220,7 @@ describe("Test: validation/types/geoShape", () => { GeoShapeType.__set__("isPoint", isPointStub); should( - geoShapeType.recursiveShapeValidation(allowedShapes, shape, []) + geoShapeType.recursiveShapeValidation(allowedShapes, shape, []), ).be.true(); should(isPointStub).calledOnce(); }); @@ -238,7 +238,7 @@ describe("Test: validation/types/geoShape", () => { GeoShapeType.__set__("isPoint", isPointStub); should( - geoShapeType.recursiveShapeValidation(allowedShapes, shape, []) + geoShapeType.recursiveShapeValidation(allowedShapes, shape, []), ).be.true(); should(isPointStub.callCount).be.eql(1); }); @@ -255,7 +255,7 @@ describe("Test: validation/types/geoShape", () => { GeoShapeType.__set__("isPoint", isPointStub); should( - geoShapeType.recursiveShapeValidation(allowedShapes, shape, []) + geoShapeType.recursiveShapeValidation(allowedShapes, shape, []), ).be.true(); should(isPointStub.callCount).be.eql(2); }); @@ -272,7 +272,7 @@ describe("Test: validation/types/geoShape", () => { GeoShapeType.__set__("isPoint", isPointStub); should( - geoShapeType.recursiveShapeValidation(allowedShapes, shape, []) + geoShapeType.recursiveShapeValidation(allowedShapes, shape, []), ).be.false(); should(isPointStub.callCount).be.eql(1); }); @@ -294,8 +294,8 @@ describe("Test: validation/types/geoShape", () => { geoShapeType.recursiveShapeValidation( allowedShapes, shape, - errorMessages - ) + errorMessages, + ), ).be.false(); should(isPolygonStub.callCount).be.eql(1); should(errorMessages).be.deepEqual([ @@ -324,8 +324,8 @@ describe("Test: validation/types/geoShape", () => { geoShapeType.recursiveShapeValidation( allowedShapes, shape, - errorMessages - ) + errorMessages, + ), ).be.false(); should(isPointStub.callCount).be.eql(1); should(errorMessages).be.deepEqual([ @@ -350,8 +350,8 @@ describe("Test: validation/types/geoShape", () => { geoShapeType.recursiveShapeValidation( allowedShapes, shape, - errorMessages - ) + errorMessages, + ), ).be.false(); should(isPointStub.callCount).be.eql(1); should(errorMessages).be.deepEqual([ @@ -377,8 +377,8 @@ describe("Test: validation/types/geoShape", () => { geoShapeType.recursiveShapeValidation( allowedShapes, shape, - errorMessages - ) + errorMessages, + ), ).be.false(); should(isPointStub.callCount).be.eql(1); should(errorMessages).be.deepEqual([ @@ -404,8 +404,8 @@ describe("Test: validation/types/geoShape", () => { geoShapeType.recursiveShapeValidation( allowedShapes, shape, - errorMessages - ) + errorMessages, + ), ).be.false(); should(isPointStub.callCount).be.eql(1); should(errorMessages).be.deepEqual([ @@ -433,7 +433,7 @@ describe("Test: validation/types/geoShape", () => { }; should( - geoShapeType.checkStructure(allowedShapes, shape, errorMessages) + geoShapeType.checkStructure(allowedShapes, shape, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ "The shape object has no type defined.", @@ -450,7 +450,7 @@ describe("Test: validation/types/geoShape", () => { }; should( - geoShapeType.checkStructure(allowedShapes, shape, errorMessages) + geoShapeType.checkStructure(allowedShapes, shape, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ "The shape object has a not allowed property.", @@ -466,7 +466,7 @@ describe("Test: validation/types/geoShape", () => { }; should( - geoShapeType.checkStructure(allowedShapes, shape, errorMessages) + geoShapeType.checkStructure(allowedShapes, shape, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ "The provided shape type is not allowed.", @@ -483,7 +483,7 @@ describe("Test: validation/types/geoShape", () => { }; should( - geoShapeType.checkStructure(allowedShapes, shape, errorMessages) + geoShapeType.checkStructure(allowedShapes, shape, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ 'The coordinates property must not be provided for the "geometrycollection" shape type.', @@ -499,7 +499,7 @@ describe("Test: validation/types/geoShape", () => { }; should( - geoShapeType.checkStructure(allowedShapes, shape, errorMessages) + geoShapeType.checkStructure(allowedShapes, shape, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ 'The coordinates property must be provided for the "allowed" shape type.', @@ -515,7 +515,7 @@ describe("Test: validation/types/geoShape", () => { }; should( - geoShapeType.checkStructure(allowedShapes, shape, errorMessages) + geoShapeType.checkStructure(allowedShapes, shape, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ 'The radius property is mandatory for the "circle" shape type.', @@ -532,7 +532,7 @@ describe("Test: validation/types/geoShape", () => { }; should( - geoShapeType.checkStructure(allowedShapes, shape, errorMessages) + geoShapeType.checkStructure(allowedShapes, shape, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ `The radius property must not be provided for the "${shape.type}" shape type.`, @@ -549,7 +549,7 @@ describe("Test: validation/types/geoShape", () => { }; should( - geoShapeType.checkStructure(allowedShapes, shape, errorMessages) + geoShapeType.checkStructure(allowedShapes, shape, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ `The orientation property must not be provided for the "${shape.type}" shape type.`, @@ -566,7 +566,7 @@ describe("Test: validation/types/geoShape", () => { }; should( - geoShapeType.checkStructure(allowedShapes, shape, errorMessages) + geoShapeType.checkStructure(allowedShapes, shape, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ `The geometries property must not be provided for the "${shape.type}" shape type.`, @@ -582,7 +582,7 @@ describe("Test: validation/types/geoShape", () => { }; should( - geoShapeType.checkStructure(allowedShapes, shape, errorMessages) + geoShapeType.checkStructure(allowedShapes, shape, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ 'The geometries property must be provided for the "geometrycollection" shape type.', @@ -607,14 +607,14 @@ describe("Test: validation/types/geoShape", () => { }; should(geoShapeType.validateFieldSpecification({})).be.deepEqual( - expectedTypeOptions + expectedTypeOptions, ); }); it("should return the typeOptions if shapeTypes is provided and valid", () => { const typeOptions = { shapeTypes: ["point", "linestring"] }; should(geoShapeType.validateFieldSpecification(typeOptions)).be.deepEqual( - typeOptions + typeOptions, ); }); @@ -622,20 +622,20 @@ describe("Test: validation/types/geoShape", () => { should(() => geoShapeType.validateFieldSpecification({ shapeTypes: ["circle", "multipolygon", "invalid"], - }) + }), ).throw(PreconditionError, { id: "validation.types.invalid_geoshape" }); should(() => geoShapeType.validateFieldSpecification({ shapeTypes: ["invalid", "circle", "foo", "multipolygon", "bar"], - }) + }), ).throw(PreconditionError, { id: "validation.types.invalid_geoshape" }); }); it("should throw if the provided shapeTypes list is empty or not an array", () => { [[], null, undefined, "foo", 123].forEach((t) => { should(() => - geoShapeType.validateFieldSpecification({ shapeTypes: t }) + geoShapeType.validateFieldSpecification({ shapeTypes: t }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); }); }); diff --git a/test/core/validation/types/integer.test.js b/test/core/validation/types/integer.test.js index 5f876197da..e71e8053ff 100644 --- a/test/core/validation/types/integer.test.js +++ b/test/core/validation/types/integer.test.js @@ -40,7 +40,7 @@ describe("Test: validation/types/integer", () => { const errorMessages = []; should( - integerType.validate(emptyTypeOptions, "a string", errorMessages) + integerType.validate(emptyTypeOptions, "a string", errorMessages), ).be.false(); should(errorMessages).be.deepEqual(["The field must be a number."]); }); @@ -49,7 +49,7 @@ describe("Test: validation/types/integer", () => { const errorMessages = []; should( - integerType.validate(emptyTypeOptions, 42.42, errorMessages) + integerType.validate(emptyTypeOptions, 42.42, errorMessages), ).be.false(); should(errorMessages).be.deepEqual(["The field must be an integer."]); }); @@ -58,7 +58,7 @@ describe("Test: validation/types/integer", () => { const errorMessages = []; should( - integerType.validate(rangeTypeOptions, 40, errorMessages) + integerType.validate(rangeTypeOptions, 40, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ "Value 40 is lesser than the allowed minimum (41)", @@ -69,7 +69,7 @@ describe("Test: validation/types/integer", () => { const errorMessages = []; should( - integerType.validate(rangeTypeOptions, 43, errorMessages) + integerType.validate(rangeTypeOptions, 43, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ "Value 43 is greater than the allowed maximum (42)", diff --git a/test/core/validation/types/ipAddress.test.js b/test/core/validation/types/ipAddress.test.js index 7d9086dadc..9b9667dd7a 100644 --- a/test/core/validation/types/ipAddress.test.js +++ b/test/core/validation/types/ipAddress.test.js @@ -24,14 +24,14 @@ describe("Test: validation/types/ipAddress", () => { describe("#validate", () => { it("should return true if the value is a valid IPv4 address", () => { should( - ipAddressType.validate({ notEmpty: true }, "127.0.0.1", []) + ipAddressType.validate({ notEmpty: true }, "127.0.0.1", []), ).be.true(); }); it("should return true if the value is a valid IPv6 address", () => { should(ipAddressType.validate({ notEmpty: true }, "::1", [])).be.true(); should( - ipAddressType.validate({ notEmpty: true }, "2001:db8::1", []) + ipAddressType.validate({ notEmpty: true }, "2001:db8::1", []), ).be.true(); }); @@ -43,7 +43,7 @@ describe("Test: validation/types/ipAddress", () => { const errorMessage = []; should( - ipAddressType.validate({ notEmpty: true }, "", errorMessage) + ipAddressType.validate({ notEmpty: true }, "", errorMessage), ).be.false(); should(errorMessage).be.deepEqual(["The string must not be empty."]); }); @@ -53,7 +53,7 @@ describe("Test: validation/types/ipAddress", () => { const errorMessage = []; should( - ipAddressType.validate({ notEmpty: true }, ip, errorMessage) + ipAddressType.validate({ notEmpty: true }, ip, errorMessage), ).be.false(); should(errorMessage).be.deepEqual([ "The string must be a valid IP address.", @@ -66,7 +66,7 @@ describe("Test: validation/types/ipAddress", () => { const errorMessage = []; should( - ipAddressType.validate({ notEmpty: true }, v, errorMessage) + ipAddressType.validate({ notEmpty: true }, v, errorMessage), ).be.false(); should(errorMessage).be.deepEqual(["The field must be a string."]); }); @@ -84,7 +84,7 @@ describe("Test: validation/types/ipAddress", () => { should( ipAddressType.validateFieldSpecification({ notEmpty: true, - }) + }), ).be.deepEqual({ notEmpty: true, }); @@ -92,7 +92,7 @@ describe("Test: validation/types/ipAddress", () => { it('should throw if "notEmpty" is not set properly', () => { should(() => - ipAddressType.validateFieldSpecification({ notEmpty: null }) + ipAddressType.validateFieldSpecification({ notEmpty: null }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); }); }); diff --git a/test/core/validation/types/numeric.test.js b/test/core/validation/types/numeric.test.js index 8b5afac7bb..2e1954c9f3 100644 --- a/test/core/validation/types/numeric.test.js +++ b/test/core/validation/types/numeric.test.js @@ -42,7 +42,7 @@ describe("Test: validation/types/numeric", () => { const errorMessages = []; should( - numericType.validate(emptyTypeOptions, "a string", errorMessages) + numericType.validate(emptyTypeOptions, "a string", errorMessages), ).be.false(); should(errorMessages).be.deepEqual(["The field must be a number."]); }); @@ -51,7 +51,7 @@ describe("Test: validation/types/numeric", () => { const errorMessages = []; should( - numericType.validate(rangeTypeOptions, 40.99, errorMessages) + numericType.validate(rangeTypeOptions, 40.99, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ "Value 40.99 is lesser than the allowed minimum (41)", @@ -62,7 +62,7 @@ describe("Test: validation/types/numeric", () => { const errorMessages = []; should( - numericType.validate(rangeTypeOptions, 42.1, errorMessages) + numericType.validate(rangeTypeOptions, 42.1, errorMessages), ).be.false(); should(errorMessages).be.deepEqual([ "Value 42.1 is greater than the allowed maximum (42)", @@ -86,14 +86,14 @@ describe("Test: validation/types/numeric", () => { [[], undefined, null, "foobar", 123].forEach((range) => { should(() => numericType.validateFieldSpecification({ range })).throw( PreconditionError, - { id: "validation.assert.unexpected_properties" } + { id: "validation.assert.unexpected_properties" }, ); }); }); it("should throw if an unrecognized property is passed to the range options", () => { should(() => - numericType.validateFieldSpecification({ range: { foo: 123 } }) + numericType.validateFieldSpecification({ range: { foo: 123 } }), ).throw(PreconditionError, { id: "validation.assert.unexpected_properties", }); @@ -102,11 +102,11 @@ describe("Test: validation/types/numeric", () => { it("should throw if a non-numeric value is passed to the min or max properties", () => { [[], {}, undefined, null, "foo"].forEach((v) => { should(() => - numericType.validateFieldSpecification({ range: { min: v } }) + numericType.validateFieldSpecification({ range: { min: v } }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); should(() => - numericType.validateFieldSpecification({ range: { max: v } }) + numericType.validateFieldSpecification({ range: { max: v } }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); }); }); @@ -118,7 +118,7 @@ describe("Test: validation/types/numeric", () => { min: 42, max: 41, }, - }) + }), ).throw(PreconditionError, { id: "validation.assert.invalid_range" }); }); }); diff --git a/test/core/validation/types/object.test.js b/test/core/validation/types/object.test.js index 0586d18bc4..452cd37f86 100644 --- a/test/core/validation/types/object.test.js +++ b/test/core/validation/types/object.test.js @@ -39,7 +39,7 @@ describe("Test: validation/types/object", () => { describe("#validateFieldSpecification", () => { it("should throw if the strict option is not a boolean", () => { should(() => - objectType.validateFieldSpecification({ strict: "not a boolean" }) + objectType.validateFieldSpecification({ strict: "not a boolean" }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); }); diff --git a/test/core/validation/types/string.test.js b/test/core/validation/types/string.test.js index ba99ee59d1..dec99b7d6d 100644 --- a/test/core/validation/types/string.test.js +++ b/test/core/validation/types/string.test.js @@ -28,7 +28,7 @@ describe("Test: validation/types/string", () => { it("should return true if the string length is comprised in the provided length range", () => { should( - stringType.validate({ length: { min: 7, max: 9 } }, "a string", []) + stringType.validate({ length: { min: 7, max: 9 } }, "a string", []), ).be.true(); }); @@ -45,7 +45,7 @@ describe("Test: validation/types/string", () => { const errorMessage = []; should( - stringType.validate({ length: { min: 10 } }, "a string", errorMessage) + stringType.validate({ length: { min: 10 } }, "a string", errorMessage), ).be.false(); should(errorMessage).be.deepEqual([ 'Invalid string length. Expected min: 10. Received: 8 ("a string")', @@ -56,7 +56,7 @@ describe("Test: validation/types/string", () => { const errorMessage = []; should( - stringType.validate({ length: { max: 5 } }, "a string", errorMessage) + stringType.validate({ length: { max: 5 } }, "a string", errorMessage), ).be.false(); should(errorMessage).be.deepEqual([ 'Invalid string length. Expected max: 5. Received: 8 ("a string")', @@ -80,14 +80,14 @@ describe("Test: validation/types/string", () => { [[], undefined, null, "foobar", 123].forEach((length) => { should(() => stringType.validateFieldSpecification({ length })).throw( PreconditionError, - { id: "validation.assert.unexpected_properties" } + { id: "validation.assert.unexpected_properties" }, ); }); }); it("should throw if an unrecognized property is passed to the length options", () => { should(() => - stringType.validateFieldSpecification({ length: { foo: 123 } }) + stringType.validateFieldSpecification({ length: { foo: 123 } }), ).throw(PreconditionError, { id: "validation.assert.unexpected_properties", }); @@ -96,11 +96,11 @@ describe("Test: validation/types/string", () => { it("should throw if a non-numeric value is passed to the min or max properties", () => { [[], {}, undefined, null, "foo"].forEach((v) => { should(() => - stringType.validateFieldSpecification({ length: { min: v } }) + stringType.validateFieldSpecification({ length: { min: v } }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); should(() => - stringType.validateFieldSpecification({ length: { max: v } }) + stringType.validateFieldSpecification({ length: { max: v } }), ).throw(PreconditionError, { id: "validation.assert.invalid_type" }); }); }); @@ -112,7 +112,7 @@ describe("Test: validation/types/string", () => { min: 42, max: 41, }, - }) + }), ).throw(PreconditionError, { id: "validation.assert.invalid_range" }); }); }); diff --git a/test/core/validation/types/url.test.js b/test/core/validation/types/url.test.js index 458d18072e..3c31de47b5 100644 --- a/test/core/validation/types/url.test.js +++ b/test/core/validation/types/url.test.js @@ -24,7 +24,7 @@ describe("Test: validation/types/url", () => { describe("#validate", () => { it("should return true if the value is valid", () => { should( - urlType.validate({ notEmpty: true }, "http://www.domain.com/", []) + urlType.validate({ notEmpty: true }, "http://www.domain.com/", []), ).be.true(); }); @@ -43,7 +43,11 @@ describe("Test: validation/types/url", () => { var errorMessage = []; should( - urlType.validate({ notEmpty: true }, "not an url address", errorMessage) + urlType.validate( + { notEmpty: true }, + "not an url address", + errorMessage, + ), ).be.false(); should(errorMessage).be.deepEqual(["The string must be a valid URL."]); }); @@ -53,7 +57,7 @@ describe("Test: validation/types/url", () => { const errorMessage = []; should( - urlType.validate({ notEmpty: true }, v, errorMessage) + urlType.validate({ notEmpty: true }, v, errorMessage), ).be.false(); should(errorMessage).be.deepEqual(["The field must be a string."]); }); @@ -71,7 +75,7 @@ describe("Test: validation/types/url", () => { should( urlType.validateFieldSpecification({ notEmpty: true, - }) + }), ).be.deepEqual({ notEmpty: true, }); @@ -81,7 +85,7 @@ describe("Test: validation/types/url", () => { [[], {}, "foo", 123, undefined, null].forEach((v) => { should(() => urlType.validateFieldSpecification({ notEmpty: v })).throw( PreconditionError, - { id: "validation.assert.invalid_type" } + { id: "validation.assert.invalid_type" }, ); }); }); diff --git a/test/core/validation/util.test.js b/test/core/validation/util.test.js index d02a87e90d..8c514d3a8a 100644 --- a/test/core/validation/util.test.js +++ b/test/core/validation/util.test.js @@ -23,7 +23,7 @@ describe("Test: validation utilities", () => { it("should be false if one of the property is not allowed", () => { should( - checkAllowedProperties({ foo: "bar", baz: "bar" }, ["foo"]) + checkAllowedProperties({ foo: "bar", baz: "bar" }, ["foo"]), ).be.false(); }); }); @@ -86,7 +86,7 @@ describe("Test: validation utilities", () => { }; should( - curateStructuredFields(typeAllowChildren, fields, maxDepth) + curateStructuredFields(typeAllowChildren, fields, maxDepth), ).be.deepEqual(expectedStructuredFields); }); @@ -144,7 +144,7 @@ describe("Test: validation utilities", () => { fieldPath = ["foo"]; should(getParent(structuredField, fieldPath)).be.deepEqual( - structuredField + structuredField, ); }); @@ -165,7 +165,7 @@ describe("Test: validation utilities", () => { fieldPath = ["foo", "bar", "baz"]; should(getParent(structuredField, fieldPath)).be.deepEqual( - structuredField.children.foo.children.bar + structuredField.children.foo.children.bar, ); }); @@ -351,7 +351,7 @@ describe("Test: validation utilities", () => { describe("#getValidationConfiguration", () => { let kuzzle; const getValidationConfiguration = Validation.__get__( - "getValidationConfiguration" + "getValidationConfiguration", ); beforeEach(() => { @@ -371,7 +371,7 @@ describe("Test: validation utilities", () => { should(kuzzle.ask).calledWithMatch( "core:storage:private:document:search", kuzzle.internalIndex.index, - "validations" + "validations", ); }); diff --git a/test/core/validation/validate.test.js b/test/core/validation/validate.test.js index f97148e2ad..06e9d05d30 100644 --- a/test/core/validation/validate.test.js +++ b/test/core/validation/validate.test.js @@ -142,10 +142,10 @@ describe("Test: validation.validate", () => { should(result).be.deepEqual(request); should(validation.recurseFieldValidation.callCount).be.eql(1); should(validation.recurseFieldValidation.args[0][0]).be.deepEqual( - documentBody + documentBody, ); should(validation.recurseFieldValidation.args[0][1]).be.deepEqual( - specification[index][collection].fields.children + specification[index][collection].fields.children, ); should(validation.recurseFieldValidation.args[0][2]).be.true(); should(validation.recurseFieldValidation.args[0][3]).be.eql([]); @@ -154,7 +154,7 @@ describe("Test: validation.validate", () => { .calledOnce() .calledWithMatch( { ...documentBody, _id: id }, - `${index}/${collection}` + `${index}/${collection}`, ); }); }); @@ -183,7 +183,7 @@ describe("Test: validation.validate", () => { should(result).be.deepEqual(request); should(validation.recurseFieldValidation.callCount).be.eql(1); should(validation.recurseFieldValidation.args[0][0]).be.deepEqual( - documentBody + documentBody, ); should(validation.recurseFieldValidation.args[0][1]).be.deepEqual({}); should(validation.recurseFieldValidation.args[0][2]).be.true(); @@ -213,11 +213,11 @@ describe("Test: validation.validate", () => { "manageErrorMessage", sinon.spy(function () { throw new Error(arguments[2]); - }) + }), ); return should(validation.validate(request, verbose)).be.rejectedWith( - error + error, ); }); @@ -241,11 +241,11 @@ describe("Test: validation.validate", () => { "manageErrorMessage", sinon.spy(function () { throw new Error(arguments[2]); - }) + }), ); return should(validation.validate(request, verbose)).be.rejectedWith( - "The document does not match validation filters." + "The document does not match validation filters.", ); }); @@ -271,11 +271,11 @@ describe("Test: validation.validate", () => { "manageErrorMessage", sinon.spy(function () { throw new Error(arguments[2]); - }) + }), ); return should(validation.validate(request, verbose)).be.rejectedWith( - 'The document validation is strict. Cannot add unspecified sub-field "field"' + 'The document validation is strict. Cannot add unspecified sub-field "field"', ); }); @@ -314,7 +314,7 @@ describe("Test: validation.validate", () => { should(recurseFieldValidationStub.args[0][4]).be.eql(verbose); should(manageErrorMessageStub.callCount).be.eql(1); should(manageErrorMessageStub.args[0][2]).be.eql( - 'The document validation is strict. Cannot add unspecified sub-field "field"' + 'The document validation is strict. Cannot add unspecified sub-field "field"', ); }); }); @@ -339,11 +339,11 @@ describe("Test: validation.validate", () => { "manageErrorMessage", sinon.spy(function () { throw new Error(arguments[2]); - }) + }), ); return should(validation.validate(request, verbose)).be.rejectedWith( - error + error, ); }); @@ -370,7 +370,7 @@ describe("Test: validation.validate", () => { "core:storage:public:document:get", index, collection, - "foo" + "foo", ); }); }); @@ -412,8 +412,8 @@ describe("Test: validation.validate", () => { validation.recurseApplyDefault( isUpdate, documentSubset, - collectionSpecSubset - ) + collectionSpecSubset, + ), ).deepEqual(expectedResult); }); @@ -446,8 +446,8 @@ describe("Test: validation.validate", () => { validation.recurseApplyDefault( isUpdate, documentSubset, - collectionSpecSubset - ) + collectionSpecSubset, + ), ).deepEqual(expectedResult); }); @@ -487,8 +487,8 @@ describe("Test: validation.validate", () => { validation.recurseApplyDefault( isUpdate, documentSubset, - collectionSpecSubset - ) + collectionSpecSubset, + ), ).deepEqual(expectedResult); }); }); @@ -501,8 +501,8 @@ describe("Test: validation.validate", () => { { aField: { some: "specification" } }, true, [], - false - ) + false, + ), ).throw("strictness"); }); @@ -521,8 +521,8 @@ describe("Test: validation.validate", () => { }, false, [], - false - ) + false, + ), ).throw("an error"); should(validation.isValidField.callCount).be.eql(1); @@ -543,8 +543,8 @@ describe("Test: validation.validate", () => { }, false, [], - true - ) + true, + ), ).be.true(); should(validation.isValidField.callCount).be.eql(2); @@ -564,8 +564,8 @@ describe("Test: validation.validate", () => { }, true, [], - false - ) + false, + ), ).be.true(); should(validation.isValidField.callCount).be.eql(2); @@ -583,8 +583,8 @@ describe("Test: validation.validate", () => { }, false, [], - true - ) + true, + ), ).be.false(); should(validation.isValidField.callCount).be.eql(2); @@ -605,8 +605,8 @@ describe("Test: validation.validate", () => { }, true, [], - false - ) + false, + ), ).be.false(); should(validation.isValidField.callCount).be.eql(1); @@ -636,8 +636,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, [], - false - ) + false, + ), ).be.true(); }); @@ -663,8 +663,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, [], - false - ) + false, + ), ).be.true(); }); @@ -692,8 +692,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - false - ) + false, + ), ).throw(BadRequestError, { id: "validation.check.failed_field" }); }); @@ -721,8 +721,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - true - ) + true, + ), ).be.false(); should(errorMessages).be.deepEqual({ fieldScope: { @@ -756,8 +756,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, [], - false - ) + false, + ), ).be.true(); }); @@ -785,8 +785,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - true - ) + true, + ), ).be.false(); should(errorMessages).be.deepEqual({ fieldScope: { @@ -826,8 +826,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - true - ) + true, + ), ).be.false(); should(errorMessages).be.deepEqual({ fieldScope: { @@ -865,8 +865,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - true - ) + true, + ), ).be.false(); should(errorMessages).be.deepEqual({ fieldScope: { @@ -903,8 +903,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - true - ) + true, + ), ).be.false(); should(errorMessages).be.deepEqual({ fieldScope: { @@ -941,8 +941,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - true - ) + true, + ), ).be.false(); should(errorMessages).be.deepEqual({ fieldScope: { @@ -992,8 +992,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - true - ) + true, + ), ).be.false(); should(errorMessages).be.deepEqual({ fieldScope: { @@ -1051,7 +1051,7 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - false + false, ); }).throw(BadRequestError, { id: "validation.check.failed_field" }); }); @@ -1097,8 +1097,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - true - ) + true, + ), ).be.false(); should(errorMessages).be.deepEqual({ fieldScope: { children: { aField: { messages: ["an error"] } } }, @@ -1146,8 +1146,8 @@ describe("Test: validation.validate", () => { collectionSubset, true, errorMessages, - true - ) + true, + ), ).be.false(); should(errorMessages).be.deepEqual({ fieldScope: { diff --git a/test/kerror/codes.test.js b/test/kerror/codes.test.js index ddd66f28e7..395d918c41 100644 --- a/test/kerror/codes.test.js +++ b/test/kerror/codes.test.js @@ -99,7 +99,7 @@ describe("kerror: error codes loader", () => { it("should throw if a domain is missing a code", () => { delete domains.foo.code; should(() => checkDomains(domains)).throw( - /missing required 'code' field/i + /missing required 'code' field/i, ); }); @@ -109,7 +109,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'code' must be an integer/i + /field 'code' must be an integer/i, ); } }); @@ -125,7 +125,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'code' must be between 0 and 255/i + /field 'code' must be between 0 and 255/i, ); } @@ -142,7 +142,7 @@ describe("kerror: error codes loader", () => { it("should throw if no subDomains are defined", () => { delete domains.foo.subDomains; should(() => checkDomains(domains)).throw( - /missing required 'subDomains' field/i + /missing required 'subDomains' field/i, ); }); @@ -160,7 +160,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'subDomains' must be an object/i + /field 'subDomains' must be an object/i, ); } }); @@ -168,7 +168,7 @@ describe("kerror: error codes loader", () => { it("should throw if a non-plugin subdomain is missing a code", () => { delete domains.bar.subDomains.sub1.code; should(() => checkDomains(domains)).throw( - /missing required 'code' field/i + /missing required 'code' field/i, ); }); @@ -184,7 +184,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'code' must be an integer/i + /field 'code' must be an integer/i, ); } }); @@ -205,7 +205,7 @@ describe("kerror: error codes loader", () => { domains.foo.subDomains.sub1.code = 42; domains.foo.subDomains.sub2.code = 42; should(() => checkDomains(domains, { plugin: true })).throw( - /code .* is not unique/i + /code .* is not unique/i, ); }); @@ -214,7 +214,7 @@ describe("kerror: error codes loader", () => { domains.foo.subDomains.sub2.code = code; /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'code' must be between 0 and 255/i + /field 'code' must be between 0 and 255/i, ); } @@ -232,7 +232,7 @@ describe("kerror: error codes loader", () => { it("should throw if a subdomain is missing an errors object", () => { delete domains.foo.subDomains.sub2.errors; should(() => checkDomains(domains)).throw( - /missing required 'errors' field/i + /missing required 'errors' field/i, ); }); @@ -242,7 +242,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'errors' must be an object/i + /field 'errors' must be an object/i, ); } }); @@ -250,7 +250,7 @@ describe("kerror: error codes loader", () => { it("should throw if an error is missing a code", () => { delete domains.foo.subDomains.sub1.errors.err1.code; should(() => checkDomains(domains)).throw( - /missing required 'code' field/i + /missing required 'code' field/i, ); }); @@ -260,7 +260,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'code' must be an integer/i + /field 'code' must be an integer/i, ); } }); @@ -271,7 +271,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'code' must be between 1 and 65535/i + /field 'code' must be between 1 and 65535/i, ); } @@ -287,7 +287,7 @@ describe("kerror: error codes loader", () => { delete domains.foo.subDomains.sub1.errors.err1.message; should(() => checkDomains(domains)).throw( - /missing required 'message' field/i + /missing required 'message' field/i, ); }); @@ -297,7 +297,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'message' must be a non-empty string/i + /field 'message' must be a non-empty string/i, ); } }); @@ -306,7 +306,7 @@ describe("kerror: error codes loader", () => { delete domains.foo.subDomains.sub1.errors.err1.class; should(() => checkDomains(domains)).throw( - /missing required 'class' field/i + /missing required 'class' field/i, ); }); @@ -316,7 +316,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'class' must be a string/i + /field 'class' must be a string/i, ); } }); @@ -325,7 +325,7 @@ describe("kerror: error codes loader", () => { domains.foo.subDomains.sub2.errors.err1.class = "foo"; should(() => checkDomains(domains)).throw( - /field 'class' must target a known KuzzleError object/i + /field 'class' must target a known KuzzleError object/i, ); for (const name of Object.keys(kuzzleObjectErrors)) { @@ -340,7 +340,7 @@ describe("kerror: error codes loader", () => { delete domains.foo.subDomains.sub2.errors.err1.description; should(() => checkDomains(domains)).throw( - /field 'description' must be a non-empty string/i + /field 'description' must be a non-empty string/i, ); for (const description of [ @@ -357,7 +357,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'description' must be a non-empty string/i + /field 'description' must be a non-empty string/i, ); } }); @@ -374,7 +374,7 @@ describe("kerror: error codes loader", () => { /* eslint-disable-next-line no-loop-func -- false positive */ should(() => checkDomains(domains)).throw( - /field 'deprecated' must be a non-empty string/i + /field 'deprecated' must be a non-empty string/i, ); } }); diff --git a/test/kerror/errors/errors.test.js b/test/kerror/errors/errors.test.js index 532ba9d3f7..8964af4aeb 100644 --- a/test/kerror/errors/errors.test.js +++ b/test/kerror/errors/errors.test.js @@ -65,7 +65,7 @@ describe("Errors", () => { const error = new PluginImplementationError("message", "id.error", 4242); should(error.message).be.eql( - "message\nThis is probably not a Kuzzle error, but a problem with a plugin implementation." + "message\nThis is probably not a Kuzzle error, but a problem with a plugin implementation.", ); should(error.id).be.eql("id.error"); should(error.code).be.eql(4242); diff --git a/test/kerror/errors/partialError.test.js b/test/kerror/errors/partialError.test.js index 940b08321e..81471f8bcd 100644 --- a/test/kerror/errors/partialError.test.js +++ b/test/kerror/errors/partialError.test.js @@ -27,7 +27,7 @@ describe("#PartialError", () => { it("should serialize correctly", () => { let err = JSON.parse( - JSON.stringify(new PartialError("foobar", ["foo", "bar"])) + JSON.stringify(new PartialError("foobar", ["foo", "bar"])), ); should(err.message).be.eql("foobar"); diff --git a/test/kerror/kerror.test.js b/test/kerror/kerror.test.js index f3d40d8911..1984053817 100644 --- a/test/kerror/kerror.test.js +++ b/test/kerror/kerror.test.js @@ -39,7 +39,7 @@ describe("#kerror", () => { "custom", "httpStatus", "conflict", - "placeHolder-1" + "placeHolder-1", ); should(err).be.instanceOf(KuzzleError); @@ -52,7 +52,7 @@ describe("#kerror", () => { "core", "fatal", "service_unavailable", - '{"status":"red"}' + '{"status":"red"}', ); should(err).be.instanceOf(ExternalServiceError); should(err).match({ @@ -68,7 +68,7 @@ describe("#kerror", () => { "fatal", "service_unavailable", "Lambda Core", - { message: "Anomalous Materials" } + { message: "Anomalous Materials" }, ); should(err).be.instanceOf(ExternalServiceError); @@ -96,7 +96,7 @@ describe("#kerror", () => { "not_found", "fake_id", "index", - "collection" + "collection", ); should(err).be.instanceOf(NotFoundError); should(err).match({ diff --git a/test/kuzzle/dumpGenerator.test.js b/test/kuzzle/dumpGenerator.test.js index 8325f200a9..e00fedcaa9 100644 --- a/test/kuzzle/dumpGenerator.test.js +++ b/test/kuzzle/dumpGenerator.test.js @@ -70,7 +70,7 @@ describe("Test: kuzzle/dumpGenerator", () => { should(fsStub.mkdirSync.getCall(0).args[0]).be.exactly(baseDumpPath); should(fsStub.writeFileSync.getCall(0).args[0]).be.exactly( - baseDumpPath.concat("/kuzzle.json") + baseDumpPath.concat("/kuzzle.json"), ); should(fsStub.writeFileSync.getCall(0).args[1]).be.exactly( JSON.stringify( @@ -79,19 +79,19 @@ describe("Test: kuzzle/dumpGenerator", () => { version: require("../../package.json").version, }, null, - " " - ).concat("\n") + " ", + ).concat("\n"), ); should(fsStub.writeFileSync.getCall(1).args[0]).be.exactly( - baseDumpPath.concat("/plugins.json") + baseDumpPath.concat("/plugins.json"), ); should(fsStub.writeFileSync.getCall(1).args[1]).be.exactly( - JSON.stringify(kuzzle.pluginsManager.plugins, null, " ").concat("\n") + JSON.stringify(kuzzle.pluginsManager.plugins, null, " ").concat("\n"), ); should(fsStub.writeFileSync.getCall(2).args[0]).be.exactly( - baseDumpPath.concat("/nodejs.json") + baseDumpPath.concat("/nodejs.json"), ); const processDump = JSON.parse(fsStub.writeFileSync.getCall(2).args[1]); should(processDump).have.keys( @@ -100,11 +100,11 @@ describe("Test: kuzzle/dumpGenerator", () => { "argv", "versions", "release", - "moduleLoadList" + "moduleLoadList", ); should(fsStub.writeFileSync.getCall(3).args[0]).be.exactly( - baseDumpPath.concat("/os.json") + baseDumpPath.concat("/os.json"), ); const osDump = JSON.parse(fsStub.writeFileSync.getCall(3).args[1]); should(osDump).have.keys( @@ -113,30 +113,30 @@ describe("Test: kuzzle/dumpGenerator", () => { "uptime", "cpus", "mem", - "networkInterfaces" + "networkInterfaces", ); should(osDump.mem).have.keys("total", "free"); should(fsStub.writeFileSync.getCall(4).args[0]).be.exactly( - baseDumpPath.concat("/statistics.json") + baseDumpPath.concat("/statistics.json"), ); should(fsStub.writeFileSync.getCall(4).args[1]).be.exactly( - JSON.stringify([{ stats: 42 }], null, " ").concat("\n") + JSON.stringify([{ stats: 42 }], null, " ").concat("\n"), ); should( - coreStub.firstCall.calledWith("gcore", baseDumpPath.concat("/core")) + coreStub.firstCall.calledWith("gcore", baseDumpPath.concat("/core")), ).be.true(); should(fsStub.createReadStream.getCall(0).args[0]).be.exactly( - `/tmp/${new Date().getFullYear()}-dump-me-master/core` + `/tmp/${new Date().getFullYear()}-dump-me-master/core`, ); should(fsStub.createWriteStream).be.calledOnce(); should(fsStub.createReadStream().pipe).be.called(2); should(fsStub.copyFileSync.getCall(0).args[0]).be.exactly(process.argv[0]); should(fsStub.copyFileSync.getCall(0).args[1]).be.exactly( - baseDumpPath.concat("/node") + baseDumpPath.concat("/node"), ); }); @@ -216,7 +216,7 @@ describe("Test: kuzzle/dumpGenerator", () => { for (let i = 1; i < 8; i++) { should(dumpGenerator._listFilesMatching).be.calledWith( `/tmp/${i}`, - "core" + "core", ); should(fsStub.unlinkSync).be.calledWith(`/tmp/${i}/core.gz`); } @@ -224,7 +224,7 @@ describe("Test: kuzzle/dumpGenerator", () => { for (let i = 9; i < 11; i++) { should(dumpGenerator._listFilesMatching).not.be.calledWith( `/tmp/${i}/`, - "core" + "core", ); } }); diff --git a/test/kuzzle/event/kuzzleEventEmitter.test.js b/test/kuzzle/event/kuzzleEventEmitter.test.js index 647f6b0305..cc926362c3 100644 --- a/test/kuzzle/event/kuzzleEventEmitter.test.js +++ b/test/kuzzle/event/kuzzleEventEmitter.test.js @@ -109,7 +109,7 @@ describe("#KuzzleEventEmitter", () => { "hook:onError", "plugin-foobar", "foo:bar", - new Error("error") + new Error("error"), ); setImmediate(() => { @@ -321,7 +321,7 @@ describe("#KuzzleEventEmitter", () => { it("should throw if a non-function answerer is submitted", () => { [{}, [], null, undefined, 123, false, true, "foo"].forEach((fn) => { should(() => emitter.onAsk("foo:bar", fn)).throw( - `Cannot listen to ask event "foo:bar": "${fn}" is not a function` + `Cannot listen to ask event "foo:bar": "${fn}" is not a function`, ); }); }); @@ -330,7 +330,7 @@ describe("#KuzzleEventEmitter", () => { emitter.onAsk("foo:bar", sinon.stub()); should(() => emitter.onAsk("foo:bar", sinon.stub())).throw( - 'Cannot add a listener to the ask event "foo:bar": event has already an answerer' + 'Cannot add a listener to the ask event "foo:bar": event has already an answerer', ); }); @@ -378,7 +378,7 @@ describe("#KuzzleEventEmitter", () => { it("should throw if a non-function answerer is submitted", () => { [{}, [], null, undefined, 123, false, true, "foo"].forEach((fn) => { should(() => emitter.onCall("foo:bar", fn)).throw( - `Cannot register callback for event "foo:bar": "${fn}" is not a function` + `Cannot register callback for event "foo:bar": "${fn}" is not a function`, ); }); }); @@ -387,7 +387,7 @@ describe("#KuzzleEventEmitter", () => { emitter.onCall("foo:bar", sinon.stub()); should(() => emitter.onCall("foo:bar", sinon.stub())).throw( - 'Cannot register callback for event "foo:bar": a callback has already been registered' + 'Cannot register callback for event "foo:bar": a callback has already been registered', ); }); diff --git a/test/kuzzle/event/pipeRunner.test.js b/test/kuzzle/event/pipeRunner.test.js index e01e380f58..c285897a2c 100644 --- a/test/kuzzle/event/pipeRunner.test.js +++ b/test/kuzzle/event/pipeRunner.test.js @@ -61,7 +61,7 @@ describe("#pipeRunner", () => { it("should throw if an invalid number of max concurrent request is provided", () => { for (const invalid of [-1, [], {}, 0, null, undefined, "URGH"]) { should(() => new PipeRunner(invalid, 123)).throw( - "Cannot instantiate pipes executor: invalid maxConcurrentPipes parameter value" + "Cannot instantiate pipes executor: invalid maxConcurrentPipes parameter value", ); } }); @@ -69,7 +69,7 @@ describe("#pipeRunner", () => { it("should throw if an invalid buffer size is provided", () => { for (const invalid of [-1, [], {}, 0, null, undefined, "URGH"]) { should(() => new PipeRunner(123, invalid)).throw( - "Cannot instantiate pipes executor: invalid pipesBufferSize parameter value" + "Cannot instantiate pipes executor: invalid pipesBufferSize parameter value", ); } }); diff --git a/test/kuzzle/event/waterfall.test.js b/test/kuzzle/event/waterfall.test.js index 4a4dfb55a7..3cd6a3f732 100644 --- a/test/kuzzle/event/waterfall.test.js +++ b/test/kuzzle/event/waterfall.test.js @@ -17,7 +17,7 @@ describe("waterfall", () => { this.done(); }, - context + context, ); }); @@ -43,7 +43,7 @@ describe("waterfall", () => { this.done(); }, - context + context, ); }); @@ -63,7 +63,7 @@ describe("waterfall", () => { this.done(); }, - context + context, ); }); }); diff --git a/test/kuzzle/internalIndexHandler.test.js b/test/kuzzle/internalIndexHandler.test.js index ed1723f3c1..1b68a85e52 100644 --- a/test/kuzzle/internalIndexHandler.test.js +++ b/test/kuzzle/internalIndexHandler.test.js @@ -30,7 +30,7 @@ describe("#kuzzle/InternalIndexHandler", () => { mockrequire.reRequire("../../lib/core/shared/store"); InternalIndexHandler = mockrequire.reRequire( - "../../lib/kuzzle/internalIndexHandler" + "../../lib/kuzzle/internalIndexHandler", ); }); @@ -58,21 +58,21 @@ describe("#kuzzle/InternalIndexHandler", () => { "core:storage:private:collection:create", "fooindex", "foo", - { mappings: collections.foo } + { mappings: collections.foo }, ); should(kuzzle.ask).calledWith( "core:storage:private:collection:create", "fooindex", "bar", - { mappings: collections.bar } + { mappings: collections.bar }, ); should(kuzzle.ask).calledWith( "core:storage:private:collection:create", "fooindex", "baz", - { mappings: collections.baz } + { mappings: collections.baz }, ); }); @@ -89,7 +89,7 @@ describe("#kuzzle/InternalIndexHandler", () => { "core:storage:private:document:exist", internalIndexName, "config", - internalIndexHandler._BOOTSTRAP_DONE_ID + internalIndexHandler._BOOTSTRAP_DONE_ID, ); const mutex = MutexMock.__getLastMutex(); @@ -105,7 +105,7 @@ describe("#kuzzle/InternalIndexHandler", () => { internalIndexName, "config", sinon.match.object, - { id: internalIndexHandler._BOOTSTRAP_DONE_ID } + { id: internalIndexHandler._BOOTSTRAP_DONE_ID }, ); }); @@ -123,7 +123,7 @@ describe("#kuzzle/InternalIndexHandler", () => { internalIndexName, "config", sinon.match.object, - { id: internalIndexHandler._BOOTSTRAP_DONE_ID } + { id: internalIndexHandler._BOOTSTRAP_DONE_ID }, ); }); @@ -142,7 +142,7 @@ describe("#kuzzle/InternalIndexHandler", () => { internalIndexName, "config", sinon.match.object, - { id: internalIndexHandler._BOOTSTRAP_DONE_ID } + { id: internalIndexHandler._BOOTSTRAP_DONE_ID }, ); }); @@ -157,7 +157,7 @@ describe("#kuzzle/InternalIndexHandler", () => { await should(internalIndexHandler.init()).rejectedWith( KuzzleInternalError, - { id: "services.storage.bootstrap_timeout" } + { id: "services.storage.bootstrap_timeout" }, ); should(kuzzle.ask).not.calledWith( @@ -165,7 +165,7 @@ describe("#kuzzle/InternalIndexHandler", () => { internalIndexName, "config", sinon.match({ timestamp: sinon.match.number }), - { id: internalIndexHandler._BOOTSTRAP_DONE_ID } + { id: internalIndexHandler._BOOTSTRAP_DONE_ID }, ); }); }); @@ -187,7 +187,7 @@ describe("#kuzzle/InternalIndexHandler", () => { internalIndexName, "config", sinon.match({ version: sinon.match.string }), - { id: internalIndexHandler._DATAMODEL_VERSION_ID } + { id: internalIndexHandler._DATAMODEL_VERSION_ID }, ); }); }); @@ -210,7 +210,7 @@ describe("#kuzzle/InternalIndexHandler", () => { }, }, }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(kuzzle.ask).calledWith( @@ -227,7 +227,7 @@ describe("#kuzzle/InternalIndexHandler", () => { }, }, }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(kuzzle.ask).calledWith( @@ -244,7 +244,7 @@ describe("#kuzzle/InternalIndexHandler", () => { }, }, }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); }); @@ -260,7 +260,7 @@ describe("#kuzzle/InternalIndexHandler", () => { policies: [{ roleId: "admin" }], rateLimit: 0, }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(kuzzle.ask).calledWith( @@ -271,7 +271,7 @@ describe("#kuzzle/InternalIndexHandler", () => { { policies: [{ roleId: "default" }], }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(kuzzle.ask).calledWith( @@ -282,7 +282,7 @@ describe("#kuzzle/InternalIndexHandler", () => { { policies: [{ roleId: "anonymous" }], }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); }); }); @@ -304,7 +304,7 @@ describe("#kuzzle/InternalIndexHandler", () => { internalIndexName, "validations", "index#collection", - kuzzle.config.validation.index.collection + kuzzle.config.validation.index.collection, ); }); }); @@ -318,7 +318,7 @@ describe("#kuzzle/InternalIndexHandler", () => { }); InternalIndexHandler = mockrequire.reRequire( - "../../lib/kuzzle/internalIndexHandler" + "../../lib/kuzzle/internalIndexHandler", ); }); @@ -340,7 +340,7 @@ describe("#kuzzle/InternalIndexHandler", () => { internalIndexName, "config", sinon.match({ seed: "foobar" }), - { id: internalIndexHandler._JWT_SECRET_ID } + { id: internalIndexHandler._JWT_SECRET_ID }, ); should(randomBytesMock).not.called(); @@ -354,7 +354,7 @@ describe("#kuzzle/InternalIndexHandler", () => { internalIndexName, "config", sinon.match({ seed: randomBytesMock().toString("hex") }), - { id: internalIndexHandler._JWT_SECRET_ID } + { id: internalIndexHandler._JWT_SECRET_ID }, ); should(randomBytesMock).calledWith(512); @@ -383,7 +383,7 @@ describe("#kuzzle/InternalIndexHandler", () => { "core:storage:private:document:get", internalIndexName, "config", - internalIndexHandler._JWT_SECRET_ID + internalIndexHandler._JWT_SECRET_ID, ); }); }); diff --git a/test/kuzzle/kuzzle.test.js b/test/kuzzle/kuzzle.test.js index da2647544c..22eadd9fba 100644 --- a/test/kuzzle/kuzzle.test.js +++ b/test/kuzzle/kuzzle.test.js @@ -80,7 +80,7 @@ describe("/lib/kuzzle/kuzzle.js", () => { kuzzle = _mockKuzzle(Kuzzle); application = new Plugin( { init: sinon.stub() }, - { name: "application", application: true, openApi: "openApi" } + { name: "application", application: true, openApi: "openApi" }, ); }); @@ -138,7 +138,7 @@ describe("/lib/kuzzle/kuzzle.js", () => { kuzzle.pipe.withArgs("kuzzle:state:live"), kuzzle.entryPoint.startListening, kuzzle.pipe.withArgs("kuzzle:state:ready"), - kuzzle.emit.withArgs("core:kuzzleStart") + kuzzle.emit.withArgs("core:kuzzleStart"), ); should(kuzzle.state).be.eql(kuzzleStateEnum.RUNNING); @@ -166,7 +166,7 @@ describe("/lib/kuzzle/kuzzle.js", () => { kuzzleWithPCRE.ask.withArgs("core:cache:internal:get").resolves(1); kuzzleWithPCRE.config = JSON.parse( - JSON.stringify(kuzzleWithPCRE.config) + JSON.stringify(kuzzleWithPCRE.config), ); kuzzleWithPCRE.config.realtime.pcreSupport = true; @@ -199,39 +199,39 @@ describe("/lib/kuzzle/kuzzle.js", () => { return kuzzle.start(application); }).then(() => { should(processRemoveAllListenersSpy.getCall(0).args[0]).be.exactly( - "unhandledRejection" + "unhandledRejection", ); should(processOnSpy.getCall(0).args[0]).be.exactly( - "unhandledRejection" + "unhandledRejection", ); should(processRemoveAllListenersSpy.getCall(1).args[0]).be.exactly( - "uncaughtException" + "uncaughtException", ); should(processOnSpy.getCall(1).args[0]).be.exactly("uncaughtException"); should(processRemoveAllListenersSpy.getCall(2).args[0]).be.exactly( - "SIGQUIT" + "SIGQUIT", ); should(processOnSpy.getCall(2).args[0]).be.exactly("SIGQUIT"); should(processRemoveAllListenersSpy.getCall(3).args[0]).be.exactly( - "SIGABRT" + "SIGABRT", ); should(processOnSpy.getCall(3).args[0]).be.exactly("SIGABRT"); should(processRemoveAllListenersSpy.getCall(4).args[0]).be.exactly( - "SIGTRAP" + "SIGTRAP", ); should(processOnSpy.getCall(4).args[0]).be.exactly("SIGTRAP"); should(processRemoveAllListenersSpy.getCall(5).args[0]).be.exactly( - "SIGINT" + "SIGINT", ); should(processOnSpy.getCall(5).args[0]).be.exactly("SIGINT"); should(processRemoveAllListenersSpy.getCall(6).args[0]).be.exactly( - "SIGTERM" + "SIGTERM", ); should(processOnSpy.getCall(6).args[0]).be.exactly("SIGTERM"); }); @@ -321,7 +321,7 @@ describe("/lib/kuzzle/kuzzle.js", () => { "core:storage:private:document:exist", "kuzzle", "installations", - "id" + "id", ); should(kuzzle.ask).be.calledWith( "core:storage:private:document:create", @@ -332,7 +332,7 @@ describe("/lib/kuzzle/kuzzle.js", () => { handler: handler.toString(), installedAt: Date.now(), }, - { id: "id" } + { id: "id" }, ); should(handler).be.calledOnce(); should(kuzzle.log.info).be.calledOnce(); @@ -350,14 +350,14 @@ describe("/lib/kuzzle/kuzzle.js", () => { "core:storage:private:document:exist", "kuzzle", "installations", - "id" + "id", ); should(kuzzle.ask).be.neverCalledWith( "core:storage:private:document:create", "kuzzle", "installations", { handler: handler.toString(), installedAt: Date.now() }, - { id: "id" } + { id: "id" }, ); should(handler).not.be.called(); should(kuzzle.log.info).not.be.called(); @@ -428,7 +428,7 @@ describe("/lib/kuzzle/kuzzle.js", () => { should(kuzzle.ask).be.calledWith( "core:cache:internal:get", - "backend:init:import:mappings" + "backend:init:import:mappings", ); should(kuzzle.ask).be.calledWith( @@ -438,13 +438,13 @@ describe("/lib/kuzzle/kuzzle.js", () => { stringify({ toImport: mappingsPayload.toImport, toSupport: {}, - }) - ) + }), + ), ); should(kuzzle.ask).be.calledWith( "core:cache:internal:get", - "backend:init:import:permissions" + "backend:init:import:permissions", ); should(kuzzle.ask).be.calledWith( @@ -454,13 +454,13 @@ describe("/lib/kuzzle/kuzzle.js", () => { stringify({ toImport: permissionsPayload.toImport, toSupport: {}, - }) - ) + }), + ), ); should(kuzzle.internalIndex.updateMapping).be.calledWith( "users", - toImport.userMappings + toImport.userMappings, ); should(kuzzle.internalIndex.refreshCollection).be.calledWith("users"); should(kuzzle.ask).calledWith( @@ -470,7 +470,7 @@ describe("/lib/kuzzle/kuzzle.js", () => { indexCacheOnly: false, propagate: false, refresh: true, - } + }, ); should(kuzzle.ask).calledWith( "core:security:load", @@ -483,7 +483,7 @@ describe("/lib/kuzzle/kuzzle.js", () => { onExistingUsers: toImport.onExistingUsers, onExistingUsersWarning: true, refresh: "wait_for", - } + }, ); }); @@ -493,7 +493,7 @@ describe("/lib/kuzzle/kuzzle.js", () => { should(kuzzle.ask).be.calledWith( "core:cache:internal:get", - "backend:init:import:mappings" + "backend:init:import:mappings", ); should(kuzzle.ask).be.calledWith( @@ -503,13 +503,13 @@ describe("/lib/kuzzle/kuzzle.js", () => { stringify({ toSupport: mappingsPayload.toSupport, toImport: {}, - }) - ) + }), + ), ); should(kuzzle.ask).be.calledWith( "core:cache:internal:get", - "backend:init:import:permissions" + "backend:init:import:permissions", ); should(kuzzle.ask).be.calledWith( @@ -519,13 +519,13 @@ describe("/lib/kuzzle/kuzzle.js", () => { stringify({ toSupport: permissionsPayload.toSupport, toImport: {}, - }) - ) + }), + ), ); should(kuzzle.ask).be.calledWith( "core:cache:internal:get", - "backend:init:import:fixtures" + "backend:init:import:fixtures", ); should(kuzzle.ask).be.calledWith( @@ -534,8 +534,8 @@ describe("/lib/kuzzle/kuzzle.js", () => { sha256( stringify({ toSupport: fixturesPayload.toSupport, - }) - ) + }), + ), ); should(kuzzle.ask).calledWith( @@ -546,11 +546,11 @@ describe("/lib/kuzzle/kuzzle.js", () => { propagate: false, rawMappings: true, refresh: true, - } + }, ); should(kuzzle.ask).calledWith( "core:storage:public:document:import", - toSupport.fixtures + toSupport.fixtures, ); should(kuzzle.ask).calledWith( "core:security:load", @@ -558,13 +558,13 @@ describe("/lib/kuzzle/kuzzle.js", () => { { force: true, refresh: "wait_for", - } + }, ); }); it("should prevent mappings to be loaded from import and support simultaneously", () => { return should( - kuzzle.loadInitialState(toImport, { mappings: { something: "here" } }) + kuzzle.loadInitialState(toImport, { mappings: { something: "here" } }), ).be.rejectedWith({ id: "plugin.runtime.incompatible" }); }); @@ -572,8 +572,8 @@ describe("/lib/kuzzle/kuzzle.js", () => { return should( kuzzle.loadInitialState( { profiles: { something: "here" } }, - { securities: { roles: { something: "here" } } } - ) + { securities: { roles: { something: "here" } } }, + ), ).be.rejectedWith({ id: "plugin.runtime.incompatible" }); }); }); diff --git a/test/kuzzle/kuzzlerc.test.js b/test/kuzzle/kuzzlerc.test.js index 7785199b33..2c551135b7 100644 --- a/test/kuzzle/kuzzlerc.test.js +++ b/test/kuzzle/kuzzlerc.test.js @@ -6,7 +6,7 @@ const fs = require("fs"); describe(".kuzzlerc.sample.jsonc", () => { it("should be able to load the kuzzlerc sample file without errors", () => { const content = fs.readFileSync( - `${__dirname}/../../.kuzzlerc.sample.jsonc` + `${__dirname}/../../.kuzzlerc.sample.jsonc`, ); const stripped = stripJson(content.toString()); diff --git a/test/kuzzle/log.test.js b/test/kuzzle/log.test.js index 496aae8c37..f081d39f53 100644 --- a/test/kuzzle/log.test.js +++ b/test/kuzzle/log.test.js @@ -25,7 +25,7 @@ describe("/lib/kuzzle/log", () => { should(kuzzle.emit).be.calledWith( "log:info", - "[knode-nasty-author-4242] Kiev" + "[knode-nasty-author-4242] Kiev", ); }); @@ -36,7 +36,7 @@ describe("/lib/kuzzle/log", () => { should(kuzzle.emit).be.calledWith( "log:info", - "[knode-nasty-author-4242] [request-unique-id] Kiev" + "[knode-nasty-author-4242] [request-unique-id] Kiev", ); }); }); diff --git a/test/kuzzle/vault.test.js b/test/kuzzle/vault.test.js index 40f4c74c4c..08f1c6f5d4 100644 --- a/test/kuzzle/vault.test.js +++ b/test/kuzzle/vault.test.js @@ -17,7 +17,7 @@ describe("/lib/kuzzle/vault", () => { })(async () => { const vault = new Vault( "the spoon does not exist", - "config/secrets.json" + "config/secrets.json", ); should(vaultArgs).eql(["the spoon does not exist"]); diff --git a/test/mocks/clientAdapter.mock.js b/test/mocks/clientAdapter.mock.js index fcc5810af4..1e5657c781 100644 --- a/test/mocks/clientAdapter.mock.js +++ b/test/mocks/clientAdapter.mock.js @@ -16,7 +16,7 @@ class ClientAdapterMock extends ClientAdapter { global.kuzzle.onAsk( `core:storage:${this.scope}:info:get`, - sinon.stub().resolves() + sinon.stub().resolves(), ); }); diff --git a/test/mocks/kuzzle.mock.js b/test/mocks/kuzzle.mock.js index 1f6ce1358a..0990044567 100644 --- a/test/mocks/kuzzle.mock.js +++ b/test/mocks/kuzzle.mock.js @@ -15,7 +15,7 @@ class KuzzleMock extends KuzzleEventEmitter { super( config.plugins.common.maxConcurrentPipes, - config.plugins.common.pipesBufferSize + config.plugins.common.pipesBufferSize, ); Reflect.defineProperty(global, "kuzzle", { diff --git a/test/mocks/mutex.mock.js b/test/mocks/mutex.mock.js index 970dfe6b25..2bf5757c91 100644 --- a/test/mocks/mutex.mock.js +++ b/test/mocks/mutex.mock.js @@ -27,7 +27,7 @@ class MutexMock extends Mutex { static __canLock(value) { assert( typeof value === "boolean", - "Mutex.lock can only return a boolean value" + "Mutex.lock can only return a boolean value", ); lockResult = value; } diff --git a/test/mocks/name-generator.mock.js b/test/mocks/name-generator.mock.js index c4ddab24ee..d985c9671b 100644 --- a/test/mocks/name-generator.mock.js +++ b/test/mocks/name-generator.mock.js @@ -27,7 +27,7 @@ class NameGeneratorMock { return `${prefix}${adjective}${separator}${name}${separator}${randomNumberMock( min, - max + max, )}`; } } diff --git a/test/mocks/service/redisClient.mock.js b/test/mocks/service/redisClient.mock.js index e9385f620c..945f41dcc4 100644 --- a/test/mocks/service/redisClient.mock.js +++ b/test/mocks/service/redisClient.mock.js @@ -23,11 +23,11 @@ class RedisClientMock extends EventEmitter { }); this.select = sinon.spy((key, callback) => - key > 16 ? callback(new Error("Unknown database")) : callback(null) + key > 16 ? callback(new Error("Unknown database")) : callback(null), ); process.nextTick(() => - err ? this.emit("error", err) : this.emit("ready") + err ? this.emit("error", err) : this.emit("ready"), ); } diff --git a/test/mocks/uWS.mock.js b/test/mocks/uWS.mock.js index fc5247b041..5895a22d0a 100644 --- a/test/mocks/uWS.mock.js +++ b/test/mocks/uWS.mock.js @@ -164,7 +164,7 @@ class App { return this._httpMessageHandler( this._httpResponse, - new MockHttpRequest(method, url, qs, headers) + new MockHttpRequest(method, url, qs, headers), ); } } diff --git a/test/model/security/profile.test.js b/test/model/security/profile.test.js index 48fedd96c4..541ce6cc13 100644 --- a/test/model/security/profile.test.js +++ b/test/model/security/profile.test.js @@ -20,7 +20,7 @@ describe("Test: model/security/profile", () => { controller: "controller", action: "action", }, - context + context, ); let kuzzle; @@ -78,7 +78,7 @@ describe("Test: model/security/profile", () => { Object.entries({ index2: ["collection1"], index3: ["collection1", "collection2"], - }) + }), ), }, ]; @@ -104,7 +104,7 @@ describe("Test: model/security/profile", () => { restrictedTo: new Map( Object.entries({ index1: ["collection1", "collection2"], - }) + }), ), }); @@ -120,7 +120,7 @@ describe("Test: model/security/profile", () => { restrictedTo: new Map( Object.entries({ index2: [], - }) + }), ), }); @@ -145,12 +145,12 @@ describe("Test: model/security/profile", () => { should(rights).be.an.Object(); rights = Object.keys(rights).reduce( (array, item) => array.concat(rights[item]), - [] + [], ); should(rights).be.an.Array(); filteredItem = rights.filter( - (item) => item.controller === "document" && item.action === "get" + (item) => item.controller === "document" && item.action === "get", ); should(filteredItem).length(1); @@ -159,25 +159,25 @@ describe("Test: model/security/profile", () => { should(filteredItem[0].value).be.equal("allowed"); filteredItem = rights.filter( - (item) => item.controller === "document" && item.action === "*" + (item) => item.controller === "document" && item.action === "*", ); should(filteredItem).length(2); should(filteredItem.every((item) => item.index === "index1")).be.equal( - true + true, ); should( - filteredItem.some((item) => item.collection === "collection1") + filteredItem.some((item) => item.collection === "collection1"), ).be.equal(true); should( - filteredItem.some((item) => item.collection === "collection2") + filteredItem.some((item) => item.collection === "collection2"), ).be.equal(true); should(filteredItem.every((item) => item.value === "allowed")).be.equal( - true + true, ); filteredItem = rights.filter( - (item) => item.controller === "document" && item.action === "delete" + (item) => item.controller === "document" && item.action === "delete", ); should(filteredItem).length(1); @@ -186,7 +186,7 @@ describe("Test: model/security/profile", () => { should(filteredItem[0].value).be.equal("allowed"); filteredItem = rights.filter( - (item) => item.controller === "document" && item.action === "update" + (item) => item.controller === "document" && item.action === "update", ); should( @@ -194,8 +194,8 @@ describe("Test: model/security/profile", () => { (item) => item.index === "index2" && item.collection === "*" && - item.value === "allowed" - ) + item.value === "allowed", + ), ).be.equal(true); }); @@ -216,7 +216,7 @@ describe("Test: model/security/profile", () => { return should(profile.validateDefinition()).be.rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -225,14 +225,14 @@ describe("Test: model/security/profile", () => { return should(profile.validateDefinition()).be.rejectedWith( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); it("should reject if an empty policies array is provided", () => { return should(profile.validateDefinition()).be.rejectedWith( BadRequestError, - { id: "api.assert.empty_argument" } + { id: "api.assert.empty_argument" }, ); }); @@ -244,7 +244,7 @@ describe("Test: model/security/profile", () => { { id: "api.assert.missing_argument", message: 'Missing argument "test.policies[0].roleId".', - } + }, ); }); @@ -255,7 +255,7 @@ describe("Test: model/security/profile", () => { BadRequestError, { id: "api.assert.unexpected_argument", - } + }, ); }); @@ -266,7 +266,7 @@ describe("Test: model/security/profile", () => { BadRequestError, { id: "api.assert.invalid_type", - } + }, ); }); @@ -277,7 +277,7 @@ describe("Test: model/security/profile", () => { BadRequestError, { id: "api.assert.invalid_type", - } + }, ); }); @@ -288,7 +288,7 @@ describe("Test: model/security/profile", () => { BadRequestError, { id: "api.assert.missing_argument", - } + }, ); }); @@ -304,7 +304,7 @@ describe("Test: model/security/profile", () => { BadRequestError, { id: "api.assert.unexpected_argument", - } + }, ); }); @@ -324,7 +324,7 @@ describe("Test: model/security/profile", () => { PreconditionError, { id: "services.storage.unknown_index", - } + }, ); should(kuzzle.ask).calledWith("core:storage:public:index:exist", "index"); @@ -342,7 +342,7 @@ describe("Test: model/security/profile", () => { BadRequestError, { id: "api.assert.invalid_type", - } + }, ); }); @@ -364,13 +364,13 @@ describe("Test: model/security/profile", () => { PreconditionError, { id: "services.storage.unknown_collection", - } + }, ); should(kuzzle.ask).calledWith( "core:storage:public:collection:exist", "index", - "foo" + "foo", ); }); diff --git a/test/model/security/role.test.js b/test/model/security/role.test.js index ca655c124d..00005c0137 100644 --- a/test/model/security/role.test.js +++ b/test/model/security/role.test.js @@ -18,7 +18,7 @@ describe("Test: model/security/role", () => { controller: "controller", action: "action", }, - context + context, ); before(() => { @@ -117,7 +117,7 @@ describe("Test: model/security/role", () => { controller: "controller", action: "action", }, - context + context, ); role.controllers = { @@ -177,14 +177,14 @@ describe("Test: model/security/role", () => { controller: "controller", action: "action", }, - context + context, ), restrictions = new Map( Object.entries({ index1: [], index2: ["collection1"], index3: ["collection1", "collection2"], - }) + }), ); role.controllers = { @@ -198,31 +198,31 @@ describe("Test: model/security/role", () => { should(role.checkRestrictions(req, restrictions)).be.true(); should( - role.checkRestrictions("index", undefined, restrictions) + role.checkRestrictions("index", undefined, restrictions), ).be.false(); should( - role.checkRestrictions("index1", undefined, restrictions) + role.checkRestrictions("index1", undefined, restrictions), ).be.true(); should( - role.checkRestrictions("index2", undefined, restrictions) + role.checkRestrictions("index2", undefined, restrictions), ).be.true(); should( - role.checkRestrictions("index2", "collection", restrictions) + role.checkRestrictions("index2", "collection", restrictions), ).be.false(); should( - role.checkRestrictions("index2", "collection1", restrictions) + role.checkRestrictions("index2", "collection1", restrictions), ).be.true(); should( - role.checkRestrictions("index2", "collection2", restrictions) + role.checkRestrictions("index2", "collection2", restrictions), ).be.false(); should( - role.checkRestrictions("index3", "collection2", restrictions) + role.checkRestrictions("index3", "collection2", restrictions), ).be.true(); }); }); @@ -234,7 +234,7 @@ describe("Test: model/security/role", () => { return should(role.validateDefinition(context)).be.rejectedWith( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -244,7 +244,7 @@ describe("Test: model/security/role", () => { return should(role.validateDefinition(context)).be.rejectedWith( BadRequestError, - { id: "api.assert.empty_argument" } + { id: "api.assert.empty_argument" }, ); }); @@ -256,7 +256,7 @@ describe("Test: model/security/role", () => { return should(role.validateDefinition(context)).be.rejectedWith( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -268,7 +268,7 @@ describe("Test: model/security/role", () => { return should(role.validateDefinition(context)).be.rejectedWith( BadRequestError, - { id: "api.assert.empty_argument" } + { id: "api.assert.empty_argument" }, ); }); @@ -282,7 +282,7 @@ describe("Test: model/security/role", () => { return should(role.validateDefinition(context)).be.rejectedWith( BadRequestError, - { id: "api.assert.missing_argument" } + { id: "api.assert.missing_argument" }, ); }); @@ -296,7 +296,7 @@ describe("Test: model/security/role", () => { return should(role.validateDefinition(context)).be.rejectedWith( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); @@ -310,7 +310,7 @@ describe("Test: model/security/role", () => { return should(role.validateDefinition(context)).be.rejectedWith( BadRequestError, - { id: "api.assert.empty_argument" } + { id: "api.assert.empty_argument" }, ); }); @@ -326,7 +326,7 @@ describe("Test: model/security/role", () => { return should(role.validateDefinition(context)).be.rejectedWith( BadRequestError, - { id: "api.assert.invalid_type" } + { id: "api.assert.invalid_type" }, ); }); diff --git a/test/model/security/user.test.js b/test/model/security/user.test.js index 716d62f3b8..b1ba04a925 100644 --- a/test/model/security/user.test.js +++ b/test/model/security/user.test.js @@ -101,12 +101,12 @@ describe("Test: model/security/user", () => { should(rights).be.an.Object(); rights = Object.keys(rights).reduce( (array, item) => array.concat(rights[item]), - [] + [], ); should(rights).be.an.Array(); filteredItem = rights.filter( - (item) => item.controller === "document" && item.action === "get" + (item) => item.controller === "document" && item.action === "get", ); should(filteredItem).length(1); @@ -115,7 +115,7 @@ describe("Test: model/security/user", () => { should(filteredItem[0].value).be.equal("allowed"); filteredItem = rights.filter( - (item) => item.controller === "document" && item.action === "delete" + (item) => item.controller === "document" && item.action === "delete", ); should(filteredItem).length(1); @@ -124,7 +124,7 @@ describe("Test: model/security/user", () => { should(filteredItem[0].value).be.equal("denied"); filteredItem = rights.filter( - (item) => item.controller === "document" && item.action === "create" + (item) => item.controller === "document" && item.action === "create", ); should(filteredItem).length(1); @@ -164,7 +164,7 @@ describe("Test: model/security/user", () => { return should(user.isActionAllowed(new Request({}))).be.rejectedWith( InternalError, - { id: "security.user.uninitialized" } + { id: "security.user.uninitialized" }, ); }); @@ -239,7 +239,7 @@ describe("Test: model/security/user", () => { let allowed = await user.areTargetsAllowed( request, [profile, profile2], - [{ index: "*", collections: ["foo"] }] + [{ index: "*", collections: ["foo"] }], ); await should(allowed).be.false(); @@ -247,7 +247,7 @@ describe("Test: model/security/user", () => { allowed = await user.areTargetsAllowed( request, [profile, profile2], - [{ index: "foo", collections: ["*"] }] + [{ index: "foo", collections: ["*"] }], ); await should(allowed).be.false(); @@ -258,7 +258,7 @@ describe("Test: model/security/user", () => { let allowed = await user.areTargetsAllowed( request, [profile, profile2], - [] + [], ); await should(allowed).be.true(); @@ -269,7 +269,7 @@ describe("Test: model/security/user", () => { let allowed = await user.areTargetsAllowed( request, [profile, profile2], - [{ collections: ["foo"] }] + [{ collections: ["foo"] }], ); await should(allowed).be.true(); @@ -277,7 +277,7 @@ describe("Test: model/security/user", () => { allowed = await user.areTargetsAllowed( request, [profile, profile2], - [{ index: "foo" }] + [{ index: "foo" }], ); await should(allowed).be.true(); @@ -291,7 +291,7 @@ describe("Test: model/security/user", () => { [ { index: "foo", collections: ["bar", "baz"] }, { index: "alpha", collections: ["beta"] }, - ] + ], ); await should(allowed).be.true(); @@ -300,76 +300,76 @@ describe("Test: model/security/user", () => { profilePolicies[0].role.checkRestrictions.firstCall, "foo", "bar", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies[0].role.checkRestrictions.secondCall, "foo", "baz", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies[0].role.checkRestrictions.thirdCall, "alpha", "beta", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies[1].role.checkRestrictions.firstCall, "foo", "bar", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies[1].role.checkRestrictions.secondCall, "foo", "baz", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies[1].role.checkRestrictions.thirdCall, "alpha", "beta", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies2[0].role.checkRestrictions.firstCall, "foo", "bar", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies2[0].role.checkRestrictions.secondCall, "foo", "baz", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies2[0].role.checkRestrictions.thirdCall, "alpha", "beta", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies2[1].role.checkRestrictions.firstCall, "foo", "bar", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies2[1].role.checkRestrictions.secondCall, "foo", "baz", - new Map() + new Map(), ); await sinon.assert.calledWithMatch( profilePolicies2[1].role.checkRestrictions.thirdCall, "alpha", "beta", - new Map() + new Map(), ); }); }); diff --git a/test/model/storage/apiKey.test.js b/test/model/storage/apiKey.test.js index c16c328be2..9a6fc2d0bc 100644 --- a/test/model/storage/apiKey.test.js +++ b/test/model/storage/apiKey.test.js @@ -21,7 +21,7 @@ describe("ApiKey", () => { mockrequire("../../../lib/core/storage/clientAdapter", ClientAdapterMock); StorageEngine = mockrequire.reRequire( - "../../../lib/core/storage/storageEngine" + "../../../lib/core/storage/storageEngine", ); storageEngine = new StorageEngine(); @@ -108,7 +108,7 @@ describe("ApiKey", () => { user, "expiresIn", "Sigfox API key", - {} + {}, ); should(apiKey._id).be.eql(apiKey._source.fingerprint); }); @@ -139,7 +139,7 @@ describe("ApiKey", () => { should(deleteByQueryStub).be.calledWith( { term: { userId: "mylehuong" } }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); }); }); @@ -163,11 +163,11 @@ describe("ApiKey", () => { it("should return the apiKey without the token if specified", () => { const apiKey = new ApiKey( { token: "encrypted-token", userId: "mylehuong" }, - "api-key-id" + "api-key-id", ); const apiKey2 = new ApiKey( { token: "encrypted-token", userId: "mylehuong" }, - "api-key-id2" + "api-key-id2", ); const serialized = apiKey.serialize(); diff --git a/test/model/storage/baseModel.test.js b/test/model/storage/baseModel.test.js index 18f11adf3f..c012a4d0c5 100644 --- a/test/model/storage/baseModel.test.js +++ b/test/model/storage/baseModel.test.js @@ -38,7 +38,7 @@ describe("BaseModel", () => { mockrequire("../../../lib/core/storage/clientAdapter", ClientAdapterMock); StorageEngine = mockrequire.reRequire( - "../../../lib/core/storage/storageEngine" + "../../../lib/core/storage/storageEngine", ); storageEngine = new StorageEngine(); @@ -123,7 +123,7 @@ describe("BaseModel", () => { "core:storage:private:document:get", kuzzle.internalIndex.index, "models", - "mylehuong" + "mylehuong", ); }); }); @@ -149,7 +149,7 @@ describe("BaseModel", () => { "core:storage:private:document:deleteByQuery", kuzzle.internalIndex.index, "models", - { match_all: {} } + { match_all: {} }, ); should(Model.prototype._afterDelete).be.calledTwice(); @@ -161,7 +161,7 @@ describe("BaseModel", () => { should(kuzzle.ask).be.calledWith( "core:storage:private:collection:refresh", kuzzle.internalIndex.index, - "models" + "models", ); }); }); @@ -177,7 +177,7 @@ describe("BaseModel", () => { const models = await Model.search( { query: { match_all: {} } }, - { scroll: "5s" } + { scroll: "5s" }, ); should(kuzzle.ask).be.calledWith( @@ -185,7 +185,7 @@ describe("BaseModel", () => { kuzzle.internalIndex.index, "models", { query: { match_all: {} } }, - { scroll: "5s" } + { scroll: "5s" }, ); should(models).be.length(2); should(models[0]._id).be.eql("mylehuong"); @@ -203,7 +203,7 @@ describe("BaseModel", () => { should(BaseModel.deleteByQuery).be.calledWith( { match_all: {} }, - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(ret).be.eql("ret"); } finally { @@ -233,7 +233,7 @@ describe("BaseModel", () => { kuzzle.internalIndex.index, "models", { location: "Saigon" }, - { id: "mylehuong", userId: "aschen", refresh: "wait_for" } + { id: "mylehuong", userId: "aschen", refresh: "wait_for" }, ); should(model.__persisted).be.true(); }); @@ -248,7 +248,7 @@ describe("BaseModel", () => { kuzzle.internalIndex.index, "models", { location: "Saigon" }, - { id: null, userId: null, refresh: undefined } + { id: null, userId: null, refresh: undefined }, ); should(model._id).be.eql("mylehuong"); }); @@ -265,7 +265,7 @@ describe("BaseModel", () => { "models", "mylehuong", { location: "Saigon" }, - { userId: "aschen", refresh: "wait_for" } + { userId: "aschen", refresh: "wait_for" }, ); }); }); @@ -285,7 +285,7 @@ describe("BaseModel", () => { kuzzle.internalIndex.index, "models", "mylehuong", - { refresh: "wait_for" } + { refresh: "wait_for" }, ); should(model._afterDelete).be.calledOnce(); should(model.__persisted).be.false(); @@ -297,7 +297,7 @@ describe("BaseModel", () => { await model.delete(); should(kuzzle.ask).not.be.calledWith( - "core:storage:private:document:delete" + "core:storage:private:document:delete", ); }); }); diff --git a/test/service/cache/redis.test.js b/test/service/cache/redis.test.js index 29bd67f430..25703c0384 100644 --- a/test/service/cache/redis.test.js +++ b/test/service/cache/redis.test.js @@ -49,7 +49,7 @@ describe("Redis", () => { it("should raise an error if unable to connect", () => { Redis.prototype._buildClient.returns( - new RedisClientMock(undefined, new Error("connection error")) + new RedisClientMock(undefined, new Error("connection error")), ); const testredis = new Redis(config); diff --git a/test/service/service.test.js b/test/service/service.test.js index 8e7fd2c2f9..a7fae3d80b 100644 --- a/test/service/service.test.js +++ b/test/service/service.test.js @@ -25,7 +25,7 @@ describe("Service", () => { const service2 = new Service(name, { initTimeout: 1000 }); should(service._initTimeout).be.eql( - kuzzle.config.services.common.defaultInitTimeout + kuzzle.config.services.common.defaultInitTimeout, ); should(service2._initTimeout).be.eql(1000); }); diff --git a/test/service/storage/elasticsearch.test.js b/test/service/storage/elasticsearch.test.js index 414986ef07..fda4736fe0 100644 --- a/test/service/storage/elasticsearch.test.js +++ b/test/service/storage/elasticsearch.test.js @@ -76,7 +76,7 @@ describe("Test: ElasticSearch service", () => { const esPublic = new ES(kuzzle.config.services.storageEngine); const esInternal = new ES( kuzzle.config.services.storageEngine, - scopeEnum.PRIVATE + scopeEnum.PRIVATE, ); should(esPublic.config).be.exactly(kuzzle.config.services.storageEngine); @@ -183,7 +183,7 @@ describe("Test: ElasticSearch service", () => { collections: ["bar"], }, ], - }) + }), ); elasticsearch._client.scroll.resolves({ @@ -235,7 +235,7 @@ describe("Test: ElasticSearch service", () => { }, ], }), - { ttl: 10000 } + { ttl: 10000 }, ); should(elasticsearch._client.clearScroll).not.called(); @@ -281,7 +281,7 @@ describe("Test: ElasticSearch service", () => { collections: ["bar"], }, ], - }) + }), ); elasticsearch._client.scroll.resolves({ @@ -371,7 +371,7 @@ describe("Test: ElasticSearch service", () => { elasticsearch._config.maxScrollDuration = "21m"; await should( - elasticsearch.scroll("i-am-scroll-id", { scrollTTL: "42m" }) + elasticsearch.scroll("i-am-scroll-id", { scrollTTL: "42m" }), ).be.rejectedWith({ id: "services.storage.scroll_duration_too_great" }); should(elasticsearch._client.scroll).not.be.called(); @@ -385,7 +385,7 @@ describe("Test: ElasticSearch service", () => { fetched: 1, index, collection, - }) + }), ); elasticsearch._client.scroll.resolves({ @@ -406,7 +406,7 @@ describe("Test: ElasticSearch service", () => { index, collection, }), - sinon.match.object + sinon.match.object, ); should(elasticsearch._client.scroll.firstCall.args[0]).be.deepEqual({ @@ -516,7 +516,7 @@ describe("Test: ElasticSearch service", () => { fetched: 1, index, }), - { ttl: ms(elasticsearch.config.defaults.scrollTTL) } + { ttl: ms(elasticsearch.config.defaults.scrollTTL) }, ); should(result).match({ @@ -556,7 +556,7 @@ describe("Test: ElasticSearch service", () => { await elasticsearch.search( { index, collection, searchBody }, - { from: 0, scroll: "30s", size: 1 } + { from: 0, scroll: "30s", size: 1 }, ); should(elasticsearch._client.search.firstCall.args[0]).match({ @@ -576,7 +576,7 @@ describe("Test: ElasticSearch service", () => { fetched: 0, index, }), - { ttl: 30000 } + { ttl: 30000 }, ); }); @@ -604,11 +604,11 @@ describe("Test: ElasticSearch service", () => { elasticsearch._client.search.rejects(esClientError); await should( - elasticsearch.search({ index, collection, searchBody }) + elasticsearch.search({ index, collection, searchBody }), ).be.rejected(); should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); @@ -619,7 +619,7 @@ describe("Test: ElasticSearch service", () => { }; return should( - elasticsearch.search({ index, collection, searchBody }) + elasticsearch.search({ index, collection, searchBody }), ).be.rejectedWith({ id: "services.storage.invalid_search_query" }); }); @@ -640,7 +640,7 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch.search( { index, collection, searchBody }, - { scroll: "42m" } + { scroll: "42m" }, ); await should(promise).be.rejectedWith({ @@ -694,7 +694,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -744,7 +744,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -787,7 +787,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -827,7 +827,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -847,7 +847,7 @@ describe("Test: ElasticSearch service", () => { index, collection, { city: "Kathmandu" }, - { id: "liia", refresh: "wait_for", userId: "aschen" } + { id: "liia", refresh: "wait_for", userId: "aschen" }, ); return promise.then((result) => { @@ -925,7 +925,7 @@ describe("Test: ElasticSearch service", () => { collection, "liia", { city: "Kathmandu" }, - { refresh: "wait_for", userId: "aschen" } + { refresh: "wait_for", userId: "aschen" }, ); return promise.then((result) => { @@ -959,7 +959,7 @@ describe("Test: ElasticSearch service", () => { collection, "liia", { city: "Kathmandu" }, - { injectKuzzleMeta: false } + { injectKuzzleMeta: false }, ); return promise.then((result) => { @@ -992,7 +992,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -1050,7 +1050,7 @@ describe("Test: ElasticSearch service", () => { collection, "liia", { city: "Panipokari" }, - { refresh: "wait_for", userId: "aschen", retryOnConflict: 42 } + { refresh: "wait_for", userId: "aschen", retryOnConflict: 42 }, ); return promise.then((result) => { @@ -1092,7 +1092,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -1103,7 +1103,7 @@ describe("Test: ElasticSearch service", () => { collection, "liia", { city: "Panipokari" }, - { refresh: "wait_for", userId: "oh noes", retryOnConflict: null } + { refresh: "wait_for", userId: "oh noes", retryOnConflict: null }, ); should(elasticsearch._client.update).be.calledWithMatch({ @@ -1186,7 +1186,7 @@ describe("Test: ElasticSearch service", () => { { city: "Panipokari" }, { defaultValues: { oh: "noes" }, - } + }, ); should(elasticsearch._client.update).be.calledWithMatch({ @@ -1242,7 +1242,7 @@ describe("Test: ElasticSearch service", () => { { city: "Panipokari" }, { defaultValues: { oh: "noes" }, - } + }, ); should(elasticsearch._client.update).be.calledWithMatch({ @@ -1285,7 +1285,7 @@ describe("Test: ElasticSearch service", () => { collection, "liia", { city: "Panipokari" }, - { refresh: "wait_for", userId: "aschen", retryOnConflict: 42 } + { refresh: "wait_for", userId: "aschen", retryOnConflict: 42 }, ); should(elasticsearch._client.update).be.calledWithMatch({ @@ -1327,7 +1327,7 @@ describe("Test: ElasticSearch service", () => { await should( elasticsearch.upsert(index, collection, "liia", { city: "Kathmandu", - }) + }), ).rejected(); should(elasticsearch._esWrapper.formatESError).calledWith(esClientError); @@ -1339,7 +1339,7 @@ describe("Test: ElasticSearch service", () => { collection, "liia", { city: "Panipokari" }, - { refresh: "wait_for", userId: "oh noes", retryOnConflict: null } + { refresh: "wait_for", userId: "oh noes", retryOnConflict: null }, ); should(elasticsearch._client.update).be.calledWithMatch({ @@ -1415,7 +1415,7 @@ describe("Test: ElasticSearch service", () => { collection, "liia", { city: "Kathmandu" }, - { refresh: "wait_for", userId: "aschen" } + { refresh: "wait_for", userId: "aschen" }, ); return promise.then((result) => { @@ -1470,7 +1470,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -1524,7 +1524,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -1580,7 +1580,7 @@ describe("Test: ElasticSearch service", () => { index, collection, { filter: { term: { name: "Ok" } } }, - { name: "bar" } + { name: "bar" }, ); return promise.then((result) => { @@ -1588,7 +1588,7 @@ describe("Test: ElasticSearch service", () => { index, collection, documents, - { refresh: undefined } + { refresh: undefined }, ); should(result).match({ @@ -1615,7 +1615,7 @@ describe("Test: ElasticSearch service", () => { collection, { filter: "term" }, { name: "bar" }, - { refresh: "wait_for", size: 3, userId: "aschen" } + { refresh: "wait_for", size: 3, userId: "aschen" }, ); should(elasticsearch._getAllDocumentsFromQuery).be.calledWithMatch({ @@ -1632,7 +1632,7 @@ describe("Test: ElasticSearch service", () => { { refresh: "wait_for", userId: "aschen", - } + }, ); should(result).match({ @@ -1662,7 +1662,7 @@ describe("Test: ElasticSearch service", () => { kuzzle.config.limits.documentsFetchCount = 2; return should( - elasticsearch.updateByQuery(index, collection, {}, {}) + elasticsearch.updateByQuery(index, collection, {}, {}), ).rejectedWith(SizeLimitError, { id: "services.storage.write_limit_exceeded", }); @@ -1708,7 +1708,7 @@ describe("Test: ElasticSearch service", () => { index, collection, query, - changes + changes, ); should(elasticsearch._client.updateByQuery).be.calledWithMatch(request); @@ -1735,14 +1735,14 @@ describe("Test: ElasticSearch service", () => { index, collection, query, - changes + changes, ); return should(promise) .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -1760,7 +1760,7 @@ describe("Test: ElasticSearch service", () => { index, collection, query, - changes + changes, ); return should(promise).be.rejectedWith(MultipleErrorsError, { @@ -1826,7 +1826,7 @@ describe("Test: ElasticSearch service", () => { index, collection, { filter: "term" }, - { refresh: "wait_for", from: 1, size: 3 } + { refresh: "wait_for", from: 1, size: 3 }, ); should(elasticsearch._client.deleteByQuery).be.calledWithMatch({ @@ -1848,7 +1848,7 @@ describe("Test: ElasticSearch service", () => { index, collection, { filter: "term" }, - { fetch: false } + { fetch: false }, ); should(elasticsearch._client.deleteByQuery).be.calledWithMatch({ @@ -1881,7 +1881,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -1890,7 +1890,7 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch.deleteByQuery( index, collection, - "not an object" + "not an object", ); return should(promise).be.rejectedWith({ @@ -1916,7 +1916,7 @@ describe("Test: ElasticSearch service", () => { kuzzle.config.limits.documentsFetchCount = 2; return should( - elasticsearch.deleteByQuery(index, collection, {}) + elasticsearch.deleteByQuery(index, collection, {}), ).rejectedWith(SizeLimitError, { id: "services.storage.write_limit_exceeded", }); @@ -1980,7 +1980,7 @@ describe("Test: ElasticSearch service", () => { collection, "liia", ["useless"], - { refresh: "wait_for", userId: "aschen" } + { refresh: "wait_for", userId: "aschen" }, ); return promise.then((result) => { @@ -2021,7 +2021,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); should(elasticsearch._client.index).not.be.called(); }); @@ -2038,7 +2038,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -2079,7 +2079,7 @@ describe("Test: ElasticSearch service", () => { index, collection, { match: 21 }, - callbackStub + callbackStub, ); should(result).match([1, 2]); @@ -2102,7 +2102,7 @@ describe("Test: ElasticSearch service", () => { index, collection, "not an object", - () => {} + () => {}, ); return should(promise).be.rejectedWith({ @@ -2127,14 +2127,14 @@ describe("Test: ElasticSearch service", () => { await elasticsearch.createIndex("lfiduras"); should(elasticsearch._createHiddenCollection).be.calledWithMatch( - "lfiduras" + "lfiduras", ); }); it("should reject if the index already exists", () => { return should(elasticsearch.createIndex("nepali")).be.rejectedWith( PreconditionError, - { id: "services.storage.index_already_exists" } + { id: "services.storage.index_already_exists" }, ); }); @@ -2149,7 +2149,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -2159,7 +2159,7 @@ describe("Test: ElasticSearch service", () => { return should(elasticsearch.createIndex("foobar")).rejectedWith( BadRequestError, - { id: "services.storage.invalid_index_name" } + { id: "services.storage.invalid_index_name" }, ); }); }); @@ -2225,7 +2225,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._hasHiddenCollection).be.calledWith(index); should(elasticsearch.deleteCollection).be.calledWith( index, - "_kuzzle_keep" + "_kuzzle_keep", ); }); @@ -2262,7 +2262,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -2303,7 +2303,7 @@ describe("Test: ElasticSearch service", () => { global.NODE_ENV = "development"; await should( - elasticsearch.createCollection(index, collection, { mappings }) + elasticsearch.createCollection(index, collection, { mappings }), ).be.rejectedWith({ message: 'Invalid mapping property "mappings.dinamic". Did you mean "dynamic"?', @@ -2312,7 +2312,7 @@ describe("Test: ElasticSearch service", () => { global.NODE_ENV = "production"; await should( - elasticsearch.createCollection(index, collection, { mappings }) + elasticsearch.createCollection(index, collection, { mappings }), ).be.rejectedWith({ message: 'Invalid mapping property "mappings.dinamic".', id: "services.storage.invalid_mapping", @@ -2349,7 +2349,7 @@ describe("Test: ElasticSearch service", () => { await should( elasticsearch.createCollection(index, collection, { mappings: mappings1, - }) + }), ).be.rejectedWith({ message: /Dynamic property value should be a string./, id: "services.storage.invalid_mapping", @@ -2358,7 +2358,7 @@ describe("Test: ElasticSearch service", () => { await should( elasticsearch.createCollection(index, collection, { mappings: mappings2, - }) + }), ).be.rejectedWith({ message: /Incorrect dynamic property value/, id: "services.storage.invalid_mapping", @@ -2383,7 +2383,7 @@ describe("Test: ElasticSearch service", () => { { settings: { index: { blocks: { write: true } } }, mappings: { properties: { city: { type: "keyword" } } }, - } + }, ); }); @@ -2442,7 +2442,7 @@ describe("Test: ElasticSearch service", () => { return should(elasticsearch.createCollection("foo", "bar")).rejectedWith( BadRequestError, - { id: "services.storage.invalid_index_name" } + { id: "services.storage.invalid_index_name" }, ); }); @@ -2451,7 +2451,7 @@ describe("Test: ElasticSearch service", () => { return should(elasticsearch.createCollection("foo", "bar")).rejectedWith( BadRequestError, - { id: "services.storage.invalid_collection_name" } + { id: "services.storage.invalid_collection_name" }, ); }); @@ -2598,7 +2598,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -2650,12 +2650,12 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch.updateSettings).be.calledWith( index, collection, - settings + settings, ); should(elasticsearch.updateMapping).be.calledWith( index, collection, - mappings + mappings, ); }); @@ -2672,12 +2672,12 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch.updateSettings).be.calledWith( index, collection, - settings + settings, ); should(elasticsearch.updateMapping).be.calledWith( index, collection, - mappings + mappings, ); should(elasticsearch.updateSearchIndex).not.be.called(); }); @@ -2768,7 +2768,7 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch.updateMapping( index, collection, - newMapping + newMapping, ); return promise.then((result) => { @@ -2810,7 +2810,7 @@ describe("Test: ElasticSearch service", () => { global.NODE_ENV = "development"; await should( - elasticsearch.updateMapping(index, collection, newMapping) + elasticsearch.updateMapping(index, collection, newMapping), ).be.rejectedWith({ message: 'Invalid mapping property "mappings.dinamic". Did you mean "dynamic"?', @@ -2819,7 +2819,7 @@ describe("Test: ElasticSearch service", () => { global.NODE_ENV = "production"; await should( - elasticsearch.updateMapping(index, collection, newMapping) + elasticsearch.updateMapping(index, collection, newMapping), ).be.rejectedWith({ message: 'Invalid mapping property "mappings.dinamic".', id: "services.storage.invalid_mapping", @@ -2839,7 +2839,7 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch.updateMapping( index, collection, - newMapping + newMapping, ); return promise.then((result) => { @@ -2864,14 +2864,14 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch.updateMapping( index, collection, - newMapping + newMapping, ); return should(promise) .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -2894,7 +2894,7 @@ describe("Test: ElasticSearch service", () => { const result = await elasticsearch.updateSettings( index, collection, - newSettings + newSettings, ); should(elasticsearch._client.indices.putSettings).be.calledWithMatch({ @@ -2932,14 +2932,14 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch.updateSettings( index, collection, - newSettings + newSettings, ); return should(promise) .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -3040,7 +3040,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -3179,7 +3179,7 @@ describe("Test: ElasticSearch service", () => { return promise.then((result) => { should(elasticsearch._client.bulk).be.calledWithMatch( - getExpectedEsRequest() + getExpectedEsRequest(), ); should(result).match({ @@ -3207,7 +3207,7 @@ describe("Test: ElasticSearch service", () => { refresh: "wait_for", timeout: "10m", userId: "aschen", - }) + }), ); }); }); @@ -3252,7 +3252,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -3300,7 +3300,7 @@ describe("Test: ElasticSearch service", () => { await should(elasticsearch.listCollections(index)).be.rejected(); should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -3351,7 +3351,7 @@ describe("Test: ElasticSearch service", () => { await should(elasticsearch.listIndexes()).be.rejected(); should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -3424,7 +3424,7 @@ describe("Test: ElasticSearch service", () => { await should(elasticsearch.listAliases()).be.rejected(); should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -3479,7 +3479,7 @@ describe("Test: ElasticSearch service", () => { await should(elasticsearch.listIndexes()).be.rejected(); should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -3560,7 +3560,7 @@ describe("Test: ElasticSearch service", () => { elasticsearch._client.indices.refresh.rejects(esClientError); await should( - elasticsearch.refreshCollection(index, collection) + elasticsearch.refreshCollection(index, collection), ).rejected(); should(elasticsearch._esWrapper.formatESError).calledWith(esClientError); @@ -3594,7 +3594,7 @@ describe("Test: ElasticSearch service", () => { .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -3694,7 +3694,7 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch.mCreate( index, collection, - documentsWithIds + documentsWithIds, ); return promise.then((result) => { @@ -3721,7 +3721,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match(mExecuteResult); @@ -3738,7 +3738,7 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch.mCreate( index, collection, - documentsWithIds + documentsWithIds, ); return promise.then((result) => { @@ -3771,7 +3771,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - rejected + rejected, ); should(result).match(mExecuteResult); @@ -3782,7 +3782,7 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch.mCreate( index, collection, - documentsWithoutIds + documentsWithoutIds, ); return promise.then((result) => { @@ -3806,7 +3806,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match(mExecuteResult); @@ -3819,7 +3819,7 @@ describe("Test: ElasticSearch service", () => { index, collection, documentsWithoutIds, - { refresh: "wait_for", timeout: "10m", userId: "aschen" } + { refresh: "wait_for", timeout: "10m", userId: "aschen" }, ); return promise.then((result) => { @@ -3843,7 +3843,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match(mExecuteResult); @@ -3879,7 +3879,7 @@ describe("Test: ElasticSearch service", () => { index, collection, documents, - { source: false } + { source: false }, ); const result = await promise; @@ -3903,7 +3903,7 @@ describe("Test: ElasticSearch service", () => { esRequest, toImport, [], - { source: false } + { source: false }, ); should(result).match(mExecuteResult); @@ -3913,7 +3913,7 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch.mCreateOrReplace( index, collection, - documents + documents, ); return promise.then((result) => { @@ -3935,7 +3935,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match(mExecuteResult); @@ -3949,7 +3949,7 @@ describe("Test: ElasticSearch service", () => { index, collection, documents, - { refresh: "wait_for", timeout: "10m", userId: "aschen" } + { refresh: "wait_for", timeout: "10m", userId: "aschen" }, ); return promise.then((result) => { @@ -3971,7 +3971,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match(mExecuteResult); @@ -3983,7 +3983,7 @@ describe("Test: ElasticSearch service", () => { index, collection, documents, - { injectKuzzleMeta: false } + { injectKuzzleMeta: false }, ); return promise.then((result) => { @@ -4005,7 +4005,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match(mExecuteResult); @@ -4093,7 +4093,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match({ @@ -4141,7 +4141,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); }); }); @@ -4188,7 +4188,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - rejected + rejected, ); }); }); @@ -4300,7 +4300,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match({ @@ -4330,7 +4330,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match({ @@ -4368,7 +4368,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); }); @@ -4389,7 +4389,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - rejected + rejected, ); }); @@ -4402,7 +4402,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match({ @@ -4486,7 +4486,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match(mExecuteResult); @@ -4540,7 +4540,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - rejected + rejected, ); should(result).match(mExecuteResult); @@ -4589,7 +4589,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - rejected + rejected, ); should(result).match(mExecuteResult); @@ -4623,7 +4623,7 @@ describe("Test: ElasticSearch service", () => { should(elasticsearch._mExecute).be.calledWithMatch( esRequest, toImport, - [] + [], ); should(result).match(mExecuteResult); @@ -4666,7 +4666,7 @@ describe("Test: ElasticSearch service", () => { const result = await elasticsearch.mDelete( index, collection, - documentIds + documentIds, ); should(elasticsearch._client.indices.refresh).be.calledWith({ @@ -4819,7 +4819,7 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch._mExecute( esRequest, documents, - partialErrors + partialErrors, ); return promise.then((result) => { @@ -4879,7 +4879,7 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch._mExecute( esRequest, documents, - partialErrors + partialErrors, ); return should(promise).be.rejectedWith({ @@ -4894,7 +4894,7 @@ describe("Test: ElasticSearch service", () => { esRequest, documents, partialErrors, - { limits: false } + { limits: false }, ); return should(promise).be.fulfilled(); @@ -4906,14 +4906,14 @@ describe("Test: ElasticSearch service", () => { const promise = elasticsearch._mExecute( esRequest, documents, - partialErrors + partialErrors, ); return should(promise) .be.rejected() .then(() => { should(elasticsearch._esWrapper.formatESError).be.calledWith( - esClientError + esClientError, ); }); }); @@ -4936,7 +4936,7 @@ describe("Test: ElasticSearch service", () => { const { rejected, extractedDocuments } = elasticsearch._extractMDocuments( documents, - kuzzleMeta + kuzzleMeta, ); should(rejected).match([ @@ -4998,7 +4998,7 @@ describe("Test: ElasticSearch service", () => { it("should not allow collection names that are too long", () => { return should( - elasticsearch.isCollectionNameValid("Ӣ".repeat(64)) + elasticsearch.isCollectionNameValid("Ӣ".repeat(64)), ).be.false(); }); @@ -5219,7 +5219,7 @@ describe("Test: ElasticSearch service", () => { publicES = new ES(kuzzle.config.services.storageEngine); internalES = new ES( kuzzle.config.services.storageEngine, - scopeEnum.PRIVATE + scopeEnum.PRIVATE, ); await publicES.init(); @@ -5299,11 +5299,11 @@ describe("Test: ElasticSearch service", () => { const publicIndice = await publicES._getAvailableIndice( "nepali", - "liia" + "liia", ); const internalIndice = await internalES._getAvailableIndice( "nepali", - "_kuzzle_keep" + "_kuzzle_keep", ); should(publicIndice).be.eql("&nepali.liia"); @@ -5322,11 +5322,11 @@ describe("Test: ElasticSearch service", () => { const publicIndice = await publicES._getAvailableIndice( "nepali", - "liia" + "liia", ); const internalIndice = await internalES._getAvailableIndice( "nepali", - "mehry" + "mehry", ); // Random suffix = 100000 because randomNumber has been mocked @@ -5350,26 +5350,26 @@ describe("Test: ElasticSearch service", () => { const publicIndice = await publicES._getAvailableIndice( longIndex, - longCollection + longCollection, ); const internalIndice = await internalES._getAvailableIndice( longIndex, - longCollection + longCollection, ); // Random suffix = 100000 because randomNumber has been mocked should(publicIndice).match( - `&${longIndex}.${longCollection.substr(0, 120)}.100000` + `&${longIndex}.${longCollection.substr(0, 120)}.100000`, ); should(internalIndice).match( - `%${longIndex}.${longCollection.substr(0, 120)}.100000` + `%${longIndex}.${longCollection.substr(0, 120)}.100000`, ); // The indice should be truncated just enough, not more not less should(publicIndice).match( - (value) => Buffer.from(value).length === 255 + (value) => Buffer.from(value).length === 255, ); should(internalIndice).match( - (value) => Buffer.from(value).length === 255 + (value) => Buffer.from(value).length === 255, ); }); }); @@ -5397,9 +5397,8 @@ describe("Test: ElasticSearch service", () => { internalES._client.indices.getAlias.resolves({ body: privateBody }); const publicIndice = await publicES._getAliasFromIndice("&nepali.lia"); - const internalIndice = await internalES._getAliasFromIndice( - "%nepalu.mehry" - ); + const internalIndice = + await internalES._getAliasFromIndice("%nepalu.mehry"); should(publicIndice).be.eql(["@&nepali.liia"]); should(internalIndice).be.eql(["@%nepali.mehry"]); @@ -5420,11 +5419,11 @@ describe("Test: ElasticSearch service", () => { internalES._client.indices.getAlias.resolves({ body: privateBody }); await should( - publicES._getAliasFromIndice("&nepali.lia") + publicES._getAliasFromIndice("&nepali.lia"), ).be.rejectedWith({ id: "services.storage.unknown_index_collection" }); await should( - internalES._getAliasFromIndice("%nepalu.mehry") + internalES._getAliasFromIndice("%nepalu.mehry"), ).be.rejectedWith({ id: "services.storage.unknown_index_collection" }); }); @@ -5449,11 +5448,11 @@ describe("Test: ElasticSearch service", () => { internalES._client.indices.getAlias.resolves({ body: privateBody }); await should( - publicES._getAliasFromIndice("&nepali.lia") + publicES._getAliasFromIndice("&nepali.lia"), ).not.be.rejectedWith({ id: "services.storage.multiple_indice_alias" }); await should( - internalES._getAliasFromIndice("%nepalu.mehry") + internalES._getAliasFromIndice("%nepalu.mehry"), ).not.be.rejectedWith({ id: "services.storage.multiple_indice_alias" }); }); @@ -5478,11 +5477,11 @@ describe("Test: ElasticSearch service", () => { internalES._client.indices.getAlias.resolves({ body: privateBody }); await should( - publicES._getAliasFromIndice("&nepali.lia") + publicES._getAliasFromIndice("&nepali.lia"), ).not.be.rejectedWith({ id: "services.storage.multiple_indice_alias" }); await should( - internalES._getAliasFromIndice("%nepalu.mehry") + internalES._getAliasFromIndice("%nepalu.mehry"), ).not.be.rejectedWith({ id: "services.storage.multiple_indice_alias" }); }); }); @@ -5622,7 +5621,7 @@ describe("Test: ElasticSearch service", () => { publicES._extractCollection("@&vietnam.lfiduras"); const publicCollection3 = publicES._extractCollection("@&vietnam.l"); const publicCollection4 = publicES._extractCollection( - "@&vietnam.iamaverylongcollectionnamebecauseiworthit" + "@&vietnam.iamaverylongcollectionnamebecauseiworthit", ); const internalCollection = internalES._extractCollection("@%nepali.liia"); @@ -5631,7 +5630,7 @@ describe("Test: ElasticSearch service", () => { should(publicCollection2).be.eql("lfiduras"); should(publicCollection3).be.eql("l"); should(publicCollection4).be.eql( - "iamaverylongcollectionnamebecauseiworthit" + "iamaverylongcollectionnamebecauseiworthit", ); should(internalCollection).be.eql("liia"); }); @@ -5699,7 +5698,7 @@ describe("Test: ElasticSearch service", () => { } const result = publicES._sanitizeSearchBody( - Object.assign({}, searchBody) + Object.assign({}, searchBody), ); should(result).be.deepEqual(searchBody); @@ -5712,7 +5711,7 @@ describe("Test: ElasticSearch service", () => { should(() => publicES._sanitizeSearchBody(searchBody)).throw( BadRequestError, - { id: "services.storage.invalid_search_query" } + { id: "services.storage.invalid_search_query" }, ); }); @@ -5739,7 +5738,7 @@ describe("Test: ElasticSearch service", () => { should(() => publicES._sanitizeSearchBody(searchBody)).throw( BadRequestError, - { id: "services.storage.invalid_query_keyword" } + { id: "services.storage.invalid_query_keyword" }, ); }); @@ -5794,7 +5793,7 @@ describe("Test: ElasticSearch service", () => { should(() => publicES._sanitizeSearchBody(searchParams)).throw( BadRequestError, - { id: "services.storage.invalid_query_keyword" } + { id: "services.storage.invalid_query_keyword" }, ); searchParams = { @@ -5812,7 +5811,7 @@ describe("Test: ElasticSearch service", () => { should(() => publicES._sanitizeSearchBody(searchParams)).throw( BadRequestError, - { id: "services.storage.invalid_query_keyword" } + { id: "services.storage.invalid_query_keyword" }, ); }); @@ -5839,7 +5838,7 @@ describe("Test: ElasticSearch service", () => { should(() => publicES._sanitizeSearchBody(searchParams)).throw( BadRequestError, - { id: "services.storage.invalid_query_keyword" } + { id: "services.storage.invalid_query_keyword" }, ); }); }); diff --git a/test/service/storage/esWrapper.test.js b/test/service/storage/esWrapper.test.js index c4d7ff8c9f..11662bbbd4 100644 --- a/test/service/storage/esWrapper.test.js +++ b/test/service/storage/esWrapper.test.js @@ -32,7 +32,7 @@ describe("Test: ElasticSearch Wrapper", () => { it("should handle version conflict errors", () => { const error = new Error( - '[version_conflict_engine_exception] [data][AVrbg0eg90VMe4Z_dG8j]: version conflict, current version [153] is different than the one provided [152], with { index_uuid="iDrU6CfZSO6CghM1t6dl0A" & shard="2" & index="userglobaldata" }' + '[version_conflict_engine_exception] [data][AVrbg0eg90VMe4Z_dG8j]: version conflict, current version [153] is different than the one provided [152], with { index_uuid="iDrU6CfZSO6CghM1t6dl0A" & shard="2" & index="userglobaldata" }', ); error.meta = { statusCode: 409, diff --git a/test/service/storage/queryTranslator.test.js b/test/service/storage/queryTranslator.test.js index dc51bd237a..aa1b414c82 100644 --- a/test/service/storage/queryTranslator.test.js +++ b/test/service/storage/queryTranslator.test.js @@ -14,7 +14,7 @@ describe("QueryTranslator", () => { }; const esClause = translator._translateClause( - ...Object.entries(clause)[0] + ...Object.entries(clause)[0], ); should(esClause).be.eql({ @@ -28,7 +28,7 @@ describe("QueryTranslator", () => { }; const esClause = translator._translateClause( - ...Object.entries(clause)[0] + ...Object.entries(clause)[0], ); should(esClause).be.eql({ @@ -42,7 +42,7 @@ describe("QueryTranslator", () => { }; const esClause = translator._translateClause( - ...Object.entries(clause)[0] + ...Object.entries(clause)[0], ); should(esClause).be.eql({ @@ -58,7 +58,7 @@ describe("QueryTranslator", () => { }; const esClause = translator._translateClause( - ...Object.entries(clause)[0] + ...Object.entries(clause)[0], ); should(esClause).be.eql({ @@ -74,7 +74,7 @@ describe("QueryTranslator", () => { }; const esClause = translator._translateClause( - ...Object.entries(clause)[0] + ...Object.entries(clause)[0], ); should(esClause).be.eql({ @@ -92,7 +92,7 @@ describe("QueryTranslator", () => { }; const esClause = translator._translateClause( - ...Object.entries(clause)[0] + ...Object.entries(clause)[0], ); should(esClause).be.eql({ @@ -110,7 +110,7 @@ describe("QueryTranslator", () => { }; const esClause = translator._translateClause( - ...Object.entries(clause)[0] + ...Object.entries(clause)[0], ); should(esClause).be.eql({ @@ -128,7 +128,7 @@ describe("QueryTranslator", () => { }; const esClause = translator._translateClause( - ...Object.entries(clause)[0] + ...Object.entries(clause)[0], ); should(esClause).be.eql({ @@ -146,7 +146,7 @@ describe("QueryTranslator", () => { }; const esClause = translator._translateClause( - ...Object.entries(clause)[0] + ...Object.entries(clause)[0], ); should(esClause).be.eql({ @@ -163,7 +163,7 @@ describe("QueryTranslator", () => { }; const esClause = translator._translateClause( - ...Object.entries(clause)[0] + ...Object.entries(clause)[0], ); should(esClause).be.eql({ @@ -181,7 +181,7 @@ describe("QueryTranslator", () => { }; const esOperator = translator._translateOperator( - ...Object.entries(operator)[0] + ...Object.entries(operator)[0], ); should(esOperator).be.eql({ @@ -197,7 +197,7 @@ describe("QueryTranslator", () => { }; const esOperator = translator._translateOperator( - ...Object.entries(operator)[0] + ...Object.entries(operator)[0], ); should(esOperator).be.eql({ @@ -213,7 +213,7 @@ describe("QueryTranslator", () => { }; const esOperator = translator._translateOperator( - ...Object.entries(operator)[0] + ...Object.entries(operator)[0], ); should(esOperator).be.eql({ diff --git a/test/util/deprecate.test.js b/test/util/deprecate.test.js index 98c31bbcff..71426a47a8 100644 --- a/test/util/deprecate.test.js +++ b/test/util/deprecate.test.js @@ -54,10 +54,10 @@ describe("Test: Deprecate util", () => { should(kuzzle.log.warn.callCount).be.eql(4); should(kuzzle.log.warn.getCall(0).args[0]).be.eql("DEPRECATION WARNING"); should(kuzzle.log.warn.getCall(1).args[0]).be.eql( - "Use of 'foo' property is deprecated. Please, use 'FOO' instead." + "Use of 'foo' property is deprecated. Please, use 'FOO' instead.", ); should(kuzzle.log.warn.getCall(3).args[0]).be.eql( - "Use of 'leet' property is deprecated." + "Use of 'leet' property is deprecated.", ); }); diff --git a/test/util/errorMatcher.js b/test/util/errorMatcher.js index 386b83817e..e754f887a8 100644 --- a/test/util/errorMatcher.js +++ b/test/util/errorMatcher.js @@ -81,4 +81,4 @@ function fromMessage(domain, subdomain, id, message) { return fromError(error); } -module.exports = { fromMessage, fromError }; +module.exports = { fromError, fromMessage }; diff --git a/test/util/extractFields.test.js b/test/util/extractFields.test.js index 464c1576e7..87a8fe1684 100644 --- a/test/util/extractFields.test.js +++ b/test/util/extractFields.test.js @@ -8,18 +8,18 @@ describe("util/extractFields", () => { beforeEach(() => { document = { - foo: "valueFoo", bar: { a: "valueBarA", b: "valueBarB", }, + foo: "valueFoo", }; }); it("Should extract fields recursively", () => { const result = extractFields(document); - should(result).match(["foo", "bar.a", "bar.b"]); + should(result).match(["bar.a", "bar.b", "foo"]); }); it("Should ignore requested fields", () => { @@ -32,9 +32,9 @@ describe("util/extractFields", () => { const result = extractFields(document, { alsoExtractValues: true }); should(result).match([ - { key: "foo", value: "valueFoo" }, { key: "bar.a", value: "valueBarA" }, { key: "bar.b", value: "valueBarB" }, + { key: "foo", value: "valueFoo" }, ]); }); }); diff --git a/test/util/mutex.test.js b/test/util/mutex.test.js index ec7ab0cedf..da91ac1a91 100644 --- a/test/util/mutex.test.js +++ b/test/util/mutex.test.js @@ -33,7 +33,7 @@ describe("#mutex", () => { "core:cache:internal:store", "foo", sinon.match.string, - { onlyIfNew: true, ttl: 123 } + { onlyIfNew: true, ttl: 123 }, ); }); @@ -67,7 +67,7 @@ describe("#mutex", () => { "core:cache:internal:store", "foo", sinon.match.string, - { onlyIfNew: true, ttl: 123 } + { onlyIfNew: true, ttl: 123 }, ); }); @@ -81,7 +81,7 @@ describe("#mutex", () => { for (let seconds = 0; seconds < 10; seconds++) { await should( - Promise.race([mutexPromise, resolvedPromise]) + Promise.race([mutexPromise, resolvedPromise]), ).fulfilledWith("pending"); clock.tick(1000); } @@ -99,7 +99,7 @@ describe("#mutex", () => { for (let seconds = 0; seconds < 5; seconds++) { await should( - Promise.race([mutexPromise, resolvedPromise]) + Promise.race([mutexPromise, resolvedPromise]), ).fulfilledWith("pending"); clock.tick(1000); } @@ -119,7 +119,7 @@ describe("#mutex", () => { for (let seconds = 0; seconds < 1000; seconds++) { await should( - Promise.race([mutexPromise, resolvedPromise]) + Promise.race([mutexPromise, resolvedPromise]), ).fulfilledWith("pending"); clock.tick(1000); @@ -184,7 +184,7 @@ describe("#mutex", () => { "core:cache:internal:script:execute", "delIfValueEqual", "foo", - mutex.mutexId + mutex.mutexId, ); }); @@ -209,7 +209,7 @@ describe("#mutex", () => { "core:cache:internal:script:define", "delIfValueEqual", 1, - sinon.match.string + sinon.match.string, ); kuzzle.ask.resetHistory(); diff --git a/test/util/name-generator.test.js b/test/util/name-generator.test.js index 861a2f940a..279729bf80 100644 --- a/test/util/name-generator.test.js +++ b/test/util/name-generator.test.js @@ -44,7 +44,7 @@ describe("NameGenerator", () => { }); it("should return a random formatted name with a specified random number range", () => { - const postfixRandRange = { min: 100, max: 1001 }; + const postfixRandRange = { max: 1001, min: 100 }; const name = NameGenerator.generateRandomName({ postfixRandRange }); const [minDigits, maxDigits] = [ postfixRandRange.min.toString().length, @@ -55,7 +55,7 @@ describe("NameGenerator", () => { should(name).not.be.empty(); should(name).match( - new RegExp(`^[a-zA-Z]+-[a-zA-Z]+-[0-9]{${minDigits},${maxDigits}}$`) + new RegExp(`^[a-zA-Z]+-[a-zA-Z]+-[0-9]{${minDigits},${maxDigits}}$`), ); }); @@ -67,7 +67,7 @@ describe("NameGenerator", () => { should(name).not.be.empty(); should(name).match( - new RegExp(`^[a-zA-Z]+${separator}[a-zA-Z]+${separator}[0-9]+$`) + new RegExp(`^[a-zA-Z]+${separator}[a-zA-Z]+${separator}[0-9]+$`), ); }); });