forest-cli 2.5.0 → 2.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,31 @@
1
+ ## [2.5.4](https://github.com/ForestAdmin/toolbelt/compare/v2.5.3...v2.5.4) (2021-12-31)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **logger:** allow logger to display object ([#321](https://github.com/ForestAdmin/toolbelt/issues/321)) ([d81d5f1](https://github.com/ForestAdmin/toolbelt/commit/d81d5f17cab5980ee4009c6b8fe56a1ad06a743f))
7
+
8
+ ## [2.5.3](https://github.com/ForestAdmin/toolbelt/compare/v2.5.2...v2.5.3) (2021-12-31)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **mongodb:** force to display progress bar by default ([#322](https://github.com/ForestAdmin/toolbelt/issues/322)) ([c318970](https://github.com/ForestAdmin/toolbelt/commit/c3189707f294615aeecb2a3617519af289486806))
14
+
15
+ ## [2.5.2](https://github.com/ForestAdmin/toolbelt/compare/v2.5.1...v2.5.2) (2021-12-30)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * **mongodb:** fix the onboarding cli when mongodb does't support js ([#311](https://github.com/ForestAdmin/toolbelt/issues/311)) ([ee97db2](https://github.com/ForestAdmin/toolbelt/commit/ee97db2146a0e62f883f0aec9026d21567d809f0))
21
+
22
+ ## [2.5.1](https://github.com/ForestAdmin/toolbelt/compare/v2.5.0...v2.5.1) (2021-12-10)
23
+
24
+
25
+ ### Bug Fixes
26
+
27
+ * error message when the user wants to create a branch on a remote branch ([#285](https://github.com/ForestAdmin/toolbelt/issues/285)) ([2cbde60](https://github.com/ForestAdmin/toolbelt/commit/2cbde60e62f0172ea306e729d374a737db428cb6))
28
+
1
29
  # [2.5.0](https://github.com/ForestAdmin/toolbelt/compare/v2.4.1...v2.5.0) (2021-11-15)
2
30
 
3
31
 
package/README.md CHANGED
@@ -51,6 +51,7 @@ With the Development Workflow activated.
51
51
  - `switch` switch to another branch in your local development environment.
52
52
  - `push` push layout changes of your current branch to a remote environment.
53
53
  - `deploy` deploy layout changes of an environment to the reference one.
54
+ - `environments:reset` reset a remote environment by removing all layout changes.
54
55
 
55
56
  ### Schema
56
57
 
@@ -1 +1 @@
1
- {"version":"2.5.0","commands":{"branch":{"id":"branch","description":"Create a new branch or list your existing branches.","pluginName":"forest-cli","pluginType":"core","aliases":["branches"],"flags":{"projectId":{"name":"projectId","type":"option","description":"The id of the project to create a branch in."},"delete":{"name":"delete","type":"boolean","char":"d","description":"Delete the branch.","allowNo":false},"force":{"name":"force","type":"boolean","description":"When deleting a branch, skip confirmation.","allowNo":false},"help":{"name":"help","type":"boolean","description":"Display usage information.","allowNo":false}},"args":[{"name":"BRANCH_NAME","description":"The name of the branch to create.","required":false}]},"deploy":{"id":"deploy","description":"Deploy layout changes of an environment to the reference one.","pluginName":"forest-cli","pluginType":"core","aliases":["environments:deploy"],"flags":{"help":{"name":"help","type":"boolean","description":"Display usage information.","allowNo":false},"force":{"name":"force","type":"boolean","char":"f","description":"Skip deploy confirmation.","allowNo":false},"projectId":{"name":"projectId","type":"option","char":"p","description":"The id of the project you want to deploy.","default":null}},"args":[{"name":"ENVIRONMENT_NAME","description":"The name of the environment containing the layout changes to deploy to the reference one.","required":false}]},"environments":{"id":"environments","description":"Manage environments.","pluginName":"forest-cli","pluginType":"core","aliases":["environments:list"],"flags":{"projectId":{"name":"projectId","type":"option","char":"p","description":"Forest project ID.","default":null},"format":{"name":"format","type":"option","char":"format","description":"Ouput format.","options":["table","json"],"default":"table"}},"args":[]},"init":{"id":"init","description":"Set up your development environment in your current folder.","pluginName":"forest-cli","pluginType":"core","aliases":["environments:init"],"flags":{"projectId":{"name":"projectId","type":"option","char":"p","description":"The id of the project you want to init."}},"args":[]},"login":{"id":"login","description":"Sign in with an existing account.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"email":{"name":"email","type":"option","char":"e","description":"Your Forest Admin account email."},"password":{"name":"password","type":"option","char":"P","description":"Your Forest Admin account password (ignored if token is set)."},"token":{"name":"token","type":"option","char":"t","description":"Your Forest Admin account token (replaces password)."}},"args":[]},"logout":{"id":"logout","description":"Sign out of your account.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"build":{"name":"build"},"option":{"name":"option"},"enum":{"name":"enum"},"string":{"name":"string"},"boolean":{"name":"boolean"},"integer":{"name":"integer"},"version":{"name":"version"},"help":{"name":"help"}},"args":[]},"projects":{"id":"projects","description":"Manage projects.","pluginName":"forest-cli","pluginType":"core","aliases":["projects:list"],"flags":{"format":{"name":"format","type":"option","char":"format","description":"Ouput format.","options":["table","json"],"default":"table"}},"args":[]},"push":{"id":"push","description":"Push layout changes of your current branch to a remote environment.","pluginName":"forest-cli","pluginType":"core","aliases":["branches:push"],"flags":{"environment":{"name":"environment","type":"option","char":"e","description":"The remote environment name to push onto."},"force":{"name":"force","type":"boolean","description":"Skip push changes confirmation.","allowNo":false},"help":{"name":"help","type":"boolean","description":"Display usage information.","allowNo":false},"projectId":{"name":"projectId","type":"option","char":"p","description":"The id of the project to work on.","default":null}},"args":[]},"switch":{"id":"switch","description":"Switch to another branch in your local development environment.","pluginName":"forest-cli","pluginType":"core","aliases":["branch:switch"],"flags":{"help":{"name":"help","type":"boolean","description":"Display usage information.","allowNo":false}},"args":[{"name":"BRANCH_NAME","description":"The name of the local branch to set as current.","required":false}]},"user":{"id":"user","description":"Display the current logged in user.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"build":{"name":"build"},"option":{"name":"option"},"enum":{"name":"enum"},"string":{"name":"string"},"boolean":{"name":"boolean"},"integer":{"name":"integer"},"version":{"name":"version"},"help":{"name":"help"}},"args":[]},"environments:copy-layout":{"id":"environments:copy-layout","description":"Copy the layout from one environment to another.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"projectId":{"name":"projectId","type":"option","char":"p","description":"Forest project ID.","default":null},"force":{"name":"force","type":"boolean","char":"force","description":"Force copy.","allowNo":false}},"args":[{"name":"fromEnvironment","description":"Source environment ID.","required":true},{"name":"toEnvironment","description":"Target environment ID.","required":true}]},"environments:create":{"id":"environments:create","description":"Create a new environment.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"projectId":{"name":"projectId","type":"option","char":"p","description":"Forest project ID.","default":null},"name":{"name":"name","type":"option","char":"n","description":"Environment name.","required":true},"url":{"name":"url","type":"option","char":"u","description":"Application URL.","required":true},"format":{"name":"format","type":"option","char":"format","description":"Ouput format.","options":["table","json"],"default":"table"}},"args":[]},"environments:delete":{"id":"environments:delete","description":"Delete an environment.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"force":{"name":"force","type":"boolean","char":"force","description":"Force delete.","allowNo":false}},"args":[{"name":"environmentId","description":"ID of an environment.","required":true}]},"environments:get":{"id":"environments:get","description":"Get the configuration of an environment.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"format":{"name":"format","type":"option","char":"format","description":"Output format.","options":["table","json"],"default":"table"}},"args":[{"name":"environmentId","description":"ID of an environment.","required":true}]},"environments:reset":{"id":"environments:reset","description":"Reset a remote environment by removing all layout changes","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"environment":{"name":"environment","type":"option","char":"e","description":"The remote environment name to reset."},"force":{"name":"force","type":"boolean","description":"Skip reset changes confirmation.","allowNo":false},"projectId":{"name":"projectId","type":"option","char":"p","description":"The id of the project to work on.","default":null}},"args":[]},"environments:update":{"id":"environments:update","description":"Update an environment.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"environmentId":{"name":"environmentId","type":"option","char":"e","description":"The forest environment ID to update.","required":true},"name":{"name":"name","type":"option","char":"n","description":"To update the environment name.","required":false},"url":{"name":"url","type":"option","char":"u","description":"To update the application URL.","required":false}},"args":[]},"projects:create":{"id":"projects:create","description":"Create a Forest API.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"applicationHost":{"name":"applicationHost","type":"option","char":"H","description":"Hostname of your admin backend application.","required":false},"applicationPort":{"name":"applicationPort","type":"option","char":"P","description":"Port of your admin backend application.","required":false},"databaseConnectionURL":{"name":"databaseConnectionURL","type":"option","char":"c","description":"Enter the database credentials with a connection URL.","required":false},"databaseDialect":{"name":"databaseDialect","type":"option","char":"d","description":"Enter your database dialect.","required":false,"options":["mongodb","mssql","mysql","postgres"]},"databaseName":{"name":"databaseName","type":"option","char":"n","description":"Enter your database name.","required":false},"databaseHost":{"name":"databaseHost","type":"option","char":"h","description":"Enter your database host.","required":false},"databasePort":{"name":"databasePort","type":"option","char":"p","description":"Enter your database port.","required":false},"databaseUser":{"name":"databaseUser","type":"option","char":"u","description":"Enter your database user.","required":false},"databasePassword":{"name":"databasePassword","type":"option","description":"Enter your database password.","required":false},"databaseSchema":{"name":"databaseSchema","type":"option","char":"s","description":"Enter your database schema.","required":false},"databaseSSL":{"name":"databaseSSL","type":"boolean","description":"Use SSL for database connection.","required":false,"allowNo":false},"mongoDBSRV":{"name":"mongoDBSRV","type":"boolean","description":"Use SRV DNS record for mongoDB connection.","required":false,"allowNo":false}},"args":[{"name":"applicationName","description":"Name of the project to create.","required":true}]},"projects:get":{"id":"projects:get","description":"Get the configuration of a project.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"format":{"name":"format","type":"option","char":"format","description":"Ouput format.","options":["table","json"],"default":"table"}},"args":[{"name":"projectId","description":"ID of a project.","required":true}]},"schema:apply":{"id":"schema:apply","description":"Apply the current schema of your repository to the specified environment (using your \".forestadmin-schema.json\" file).","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"secret":{"name":"secret","type":"option","char":"s","description":"Environment secret of the project (FOREST_ENV_SECRET).","required":false}},"args":[]},"schema:update":{"id":"schema:update","description":"Refresh your schema by generating files that do not currently exist.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"config":{"name":"config","type":"option","char":"c","description":"Database configuration file to use.","required":false,"default":"config/databases.js"},"outputDirectory":{"name":"outputDirectory","type":"option","char":"o","description":"Output directory where to generate new files.","required":false}},"args":[]}}}
1
+ {"version":"2.5.4","commands":{"branch":{"id":"branch","description":"Create a new branch or list your existing branches.","pluginName":"forest-cli","pluginType":"core","aliases":["branches"],"flags":{"projectId":{"name":"projectId","type":"option","description":"The id of the project to create a branch in."},"delete":{"name":"delete","type":"boolean","char":"d","description":"Delete the branch.","allowNo":false},"force":{"name":"force","type":"boolean","description":"When deleting a branch, skip confirmation.","allowNo":false},"help":{"name":"help","type":"boolean","description":"Display usage information.","allowNo":false}},"args":[{"name":"BRANCH_NAME","description":"The name of the branch to create.","required":false}]},"deploy":{"id":"deploy","description":"Deploy layout changes of an environment to the reference one.","pluginName":"forest-cli","pluginType":"core","aliases":["environments:deploy"],"flags":{"help":{"name":"help","type":"boolean","description":"Display usage information.","allowNo":false},"force":{"name":"force","type":"boolean","char":"f","description":"Skip deploy confirmation.","allowNo":false},"projectId":{"name":"projectId","type":"option","char":"p","description":"The id of the project you want to deploy.","default":null}},"args":[{"name":"ENVIRONMENT_NAME","description":"The name of the environment containing the layout changes to deploy to the reference one.","required":false}]},"environments":{"id":"environments","description":"Manage environments.","pluginName":"forest-cli","pluginType":"core","aliases":["environments:list"],"flags":{"projectId":{"name":"projectId","type":"option","char":"p","description":"Forest project ID.","default":null},"format":{"name":"format","type":"option","char":"format","description":"Ouput format.","options":["table","json"],"default":"table"}},"args":[]},"init":{"id":"init","description":"Set up your development environment in your current folder.","pluginName":"forest-cli","pluginType":"core","aliases":["environments:init"],"flags":{"projectId":{"name":"projectId","type":"option","char":"p","description":"The id of the project you want to init."}},"args":[]},"login":{"id":"login","description":"Sign in with an existing account.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"email":{"name":"email","type":"option","char":"e","description":"Your Forest Admin account email."},"password":{"name":"password","type":"option","char":"P","description":"Your Forest Admin account password (ignored if token is set)."},"token":{"name":"token","type":"option","char":"t","description":"Your Forest Admin account token (replaces password)."}},"args":[]},"logout":{"id":"logout","description":"Sign out of your account.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"build":{"name":"build"},"option":{"name":"option"},"enum":{"name":"enum"},"string":{"name":"string"},"boolean":{"name":"boolean"},"integer":{"name":"integer"},"version":{"name":"version"},"help":{"name":"help"}},"args":[]},"projects":{"id":"projects","description":"Manage projects.","pluginName":"forest-cli","pluginType":"core","aliases":["projects:list"],"flags":{"format":{"name":"format","type":"option","char":"format","description":"Ouput format.","options":["table","json"],"default":"table"}},"args":[]},"push":{"id":"push","description":"Push layout changes of your current branch to a remote environment.","pluginName":"forest-cli","pluginType":"core","aliases":["branches:push"],"flags":{"environment":{"name":"environment","type":"option","char":"e","description":"The remote environment name to push onto."},"force":{"name":"force","type":"boolean","description":"Skip push changes confirmation.","allowNo":false},"help":{"name":"help","type":"boolean","description":"Display usage information.","allowNo":false},"projectId":{"name":"projectId","type":"option","char":"p","description":"The id of the project to work on.","default":null}},"args":[]},"switch":{"id":"switch","description":"Switch to another branch in your local development environment.","pluginName":"forest-cli","pluginType":"core","aliases":["branch:switch"],"flags":{"help":{"name":"help","type":"boolean","description":"Display usage information.","allowNo":false}},"args":[{"name":"BRANCH_NAME","description":"The name of the local branch to set as current.","required":false}]},"user":{"id":"user","description":"Display the current logged in user.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"build":{"name":"build"},"option":{"name":"option"},"enum":{"name":"enum"},"string":{"name":"string"},"boolean":{"name":"boolean"},"integer":{"name":"integer"},"version":{"name":"version"},"help":{"name":"help"}},"args":[]},"environments:copy-layout":{"id":"environments:copy-layout","description":"Copy the layout from one environment to another.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"projectId":{"name":"projectId","type":"option","char":"p","description":"Forest project ID.","default":null},"force":{"name":"force","type":"boolean","char":"force","description":"Force copy.","allowNo":false}},"args":[{"name":"fromEnvironment","description":"Source environment ID.","required":true},{"name":"toEnvironment","description":"Target environment ID.","required":true}]},"environments:create":{"id":"environments:create","description":"Create a new environment.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"projectId":{"name":"projectId","type":"option","char":"p","description":"Forest project ID.","default":null},"name":{"name":"name","type":"option","char":"n","description":"Environment name.","required":true},"url":{"name":"url","type":"option","char":"u","description":"Application URL.","required":true},"format":{"name":"format","type":"option","char":"format","description":"Ouput format.","options":["table","json"],"default":"table"}},"args":[]},"environments:delete":{"id":"environments:delete","description":"Delete an environment.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"force":{"name":"force","type":"boolean","char":"force","description":"Force delete.","allowNo":false}},"args":[{"name":"environmentId","description":"ID of an environment.","required":true}]},"environments:get":{"id":"environments:get","description":"Get the configuration of an environment.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"format":{"name":"format","type":"option","char":"format","description":"Output format.","options":["table","json"],"default":"table"}},"args":[{"name":"environmentId","description":"ID of an environment.","required":true}]},"environments:reset":{"id":"environments:reset","description":"Reset a remote environment by removing all layout changes","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"environment":{"name":"environment","type":"option","char":"e","description":"The remote environment name to reset."},"force":{"name":"force","type":"boolean","description":"Skip reset changes confirmation.","allowNo":false},"projectId":{"name":"projectId","type":"option","char":"p","description":"The id of the project to work on.","default":null}},"args":[]},"environments:update":{"id":"environments:update","description":"Update an environment.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"environmentId":{"name":"environmentId","type":"option","char":"e","description":"The forest environment ID to update.","required":true},"name":{"name":"name","type":"option","char":"n","description":"To update the environment name.","required":false},"url":{"name":"url","type":"option","char":"u","description":"To update the application URL.","required":false}},"args":[]},"projects:create":{"id":"projects:create","description":"Create a Forest API.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"applicationHost":{"name":"applicationHost","type":"option","char":"H","description":"Hostname of your admin backend application.","required":false},"applicationPort":{"name":"applicationPort","type":"option","char":"P","description":"Port of your admin backend application.","required":false},"databaseConnectionURL":{"name":"databaseConnectionURL","type":"option","char":"c","description":"Enter the database credentials with a connection URL.","required":false},"databaseDialect":{"name":"databaseDialect","type":"option","char":"d","description":"Enter your database dialect.","required":false,"options":["mongodb","mssql","mysql","postgres"]},"databaseName":{"name":"databaseName","type":"option","char":"n","description":"Enter your database name.","required":false},"databaseHost":{"name":"databaseHost","type":"option","char":"h","description":"Enter your database host.","required":false},"databasePort":{"name":"databasePort","type":"option","char":"p","description":"Enter your database port.","required":false},"databaseUser":{"name":"databaseUser","type":"option","char":"u","description":"Enter your database user.","required":false},"databasePassword":{"name":"databasePassword","type":"option","description":"Enter your database password.","required":false},"databaseSchema":{"name":"databaseSchema","type":"option","char":"s","description":"Enter your database schema.","required":false},"databaseSSL":{"name":"databaseSSL","type":"boolean","description":"Use SSL for database connection.","required":false,"allowNo":false},"mongoDBSRV":{"name":"mongoDBSRV","type":"boolean","description":"Use SRV DNS record for mongoDB connection.","required":false,"allowNo":false}},"args":[{"name":"applicationName","description":"Name of the project to create.","required":true}]},"projects:get":{"id":"projects:get","description":"Get the configuration of a project.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"format":{"name":"format","type":"option","char":"format","description":"Ouput format.","options":["table","json"],"default":"table"}},"args":[{"name":"projectId","description":"ID of a project.","required":true}]},"schema:apply":{"id":"schema:apply","description":"Apply the current schema of your repository to the specified environment (using your \".forestadmin-schema.json\" file).","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"secret":{"name":"secret","type":"option","char":"s","description":"Environment secret of the project (FOREST_ENV_SECRET).","required":false}},"args":[]},"schema:update":{"id":"schema:update","description":"Refresh your schema by generating files that do not currently exist.","pluginName":"forest-cli","pluginType":"core","aliases":[],"flags":{"config":{"name":"config","type":"option","char":"c","description":"Database configuration file to use.","required":false,"default":"config/databases.js"},"outputDirectory":{"name":"outputDirectory","type":"option","char":"o","description":"Output directory where to generate new files.","required":false}},"args":[]}}}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "forest-cli",
3
3
  "description": "The Lumberjacks' toolbelt is the Forest CLI which makes easy to manage your back office application directly from the terminal.",
4
- "version": "2.5.0",
4
+ "version": "2.5.4",
5
5
  "author": "Sandro Munda",
6
6
  "contributors": [
7
7
  "Arnaud Valensi <arnaud.valensi@gmail.com>",
@@ -15,7 +15,7 @@
15
15
  },
16
16
  "bugs": "https://github.com/ForestAdmin/toolbelt/issues",
17
17
  "dependencies": {
18
- "@forestadmin/context": "1.16.0",
18
+ "@forestadmin/context": "1.31.0",
19
19
  "@oclif/command": "1.5.4",
20
20
  "@oclif/config": "1.8.8",
21
21
  "@oclif/errors": "1.2.2",
@@ -88,9 +88,7 @@ class CreateCommand extends AbstractAuthenticatedCommand {
88
88
  const connectionPromise = this.database.connect(dbConfig);
89
89
  const connection = await this.spinner.attachToPromise(connectionPromise);
90
90
 
91
- this.spinner.start({ text: 'Analyzing the database' });
92
- const schemaPromise = this.databaseAnalyzer.analyze(connection, dbConfig, true);
93
- schema = await this.spinner.attachToPromise(schemaPromise);
91
+ schema = await this.analyzeDatabase(dbConfig, connection);
94
92
 
95
93
  this.spinner.start({ text: 'Disconnecting from your database' });
96
94
  const disconnectPromise = this.database.disconnect(connection);
@@ -119,6 +117,20 @@ class CreateCommand extends AbstractAuthenticatedCommand {
119
117
  await this.eventSender.notifySuccess();
120
118
  }
121
119
 
120
+ async analyzeDatabase(dbConfig, connection) {
121
+ if (dbConfig.dbDialect === 'mongodb') {
122
+ // the mongodb analyzer display a progress bar during the analyze
123
+ this.logger.info('Analyzing the database...');
124
+ const analysis = await this.databaseAnalyzer.analyzeMongoDb(connection, dbConfig, true);
125
+ this.logger.success('Database is analyzed', { lineColor: 'green' });
126
+ return analysis;
127
+ }
128
+
129
+ this.spinner.start({ text: 'Analyzing the database' });
130
+ const schemaPromise = this.databaseAnalyzer.analyze(connection, dbConfig, true);
131
+ return this.spinner.attachToPromise(schemaPromise);
132
+ }
133
+
122
134
  // FIXME: Not properly called/tested by testCli helper.
123
135
  async catch(error) {
124
136
  this.logger.error([
@@ -5,7 +5,6 @@ module.exports = (plan) => plan
5
5
  .addModule('Handlebars', () => require('handlebars'))
6
6
  .addUsingClass('database', () => require('../services/schema/update/database'))
7
7
  .addUsingClass('dumper', () => require('../services/dumper/dumper'))
8
- .addUsingClass('eventSender', () => require('../utils/event-sender'))
9
8
  .addValue('GeneralPrompter', () => require('../services/prompter/general-prompter'))
10
9
  .addUsingClass('commandGenerateConfigGetter', () => require('../services/projects/create/command-generate-config-getter'))
11
10
  .addUsingClass('projectCreator', () => require('../services/projects/create/project-creator'))
@@ -1,6 +1,65 @@
1
+ const ProgressBar = require('progress');
2
+ const {
3
+ detectReferences,
4
+ applyReferences,
5
+ } = require('../services/schema/update/analyzer/mongo-references-analyzer');
6
+
7
+ const {
8
+ detectHasMany,
9
+ applyHasMany,
10
+ } = require('../services/schema/update/analyzer/mongo-hasmany-analyzer');
11
+
12
+ const { isUnderscored } = require('../utils/fields');
13
+
14
+ const {
15
+ getMongooseTypeFromValue,
16
+ isOfMongooseType,
17
+ } = require('../utils/mongo-primitive-type');
18
+
19
+ const {
20
+ isSystemCollection,
21
+ getCollectionName,
22
+ } = require('../utils/mongo-collections');
23
+
24
+ const {
25
+ getMongooseArraySchema,
26
+ getMongooseEmbeddedSchema,
27
+ getMongooseSchema,
28
+ haveSameEmbeddedType,
29
+ hasEmbeddedTypes,
30
+ mergeAnalyzedSchemas,
31
+ } = require('../services/schema/update/analyzer/mongo-embedded-analyzer');
32
+
33
+ const {
34
+ MongoCollectionsAnalyzer, mapCollection, reduceCollection,
35
+ } = require('../services/schema/update/analyzer/mongo-collections-analyzer');
36
+
37
+ function makeProgressBar(message, total) {
38
+ return new ProgressBar(`${message} [:bar] :percent`, { total, width: 50 });
39
+ }
40
+
1
41
  /* eslint-disable global-require */
2
42
  module.exports = (plan) => plan
3
43
  .addModule('path', () => require('path'))
4
- .addFunction('mongoAnalyzer', require('../services/schema/update/analyzer/mongo-collections-analyzer'))
44
+ .addFunction('mapCollection', mapCollection, { private: true })
45
+ .addFunction('reduceCollection', reduceCollection, { private: true })
46
+ .addFunction('detectReferences', detectReferences, { private: true })
47
+ .addFunction('applyReferences', applyReferences, { private: true })
48
+ .addFunction('detectHasMany', detectHasMany, { private: true })
49
+ .addFunction('applyHasMany', applyHasMany, { private: true })
50
+ .addFunction('isUnderscored', isUnderscored, { private: true })
51
+ .addFunction('getMongooseTypeFromValue', getMongooseTypeFromValue, { private: true })
52
+ .addFunction('isOfMongooseType', isOfMongooseType, { private: true })
53
+ .addFunction('getMongooseArraySchema', getMongooseArraySchema, { private: true })
54
+ .addFunction('getMongooseEmbeddedSchema', getMongooseEmbeddedSchema, { private: true })
55
+ .addFunction('getMongooseSchema', getMongooseSchema, { private: true })
56
+ .addFunction('haveSameEmbeddedType', haveSameEmbeddedType, { private: true })
57
+ .addFunction('hasEmbeddedTypes', hasEmbeddedTypes, { private: true })
58
+ .addFunction('mergeAnalyzedSchemas', mergeAnalyzedSchemas, { private: true })
59
+ .addFunction('isSystemCollection', isSystemCollection, { private: true })
60
+ .addFunction('getCollectionName', getCollectionName, { private: true })
61
+ .addFunction('makeProgressBar', makeProgressBar, { private: true })
5
62
  .addFunction('sequelizeAnalyzer', require('../services/schema/update/analyzer/sequelize-tables-analyzer'))
63
+ .addUsingClass('spinnerUi', () => require('../services/spinner'))
64
+ .addUsingClass('mongoAnalyzer', MongoCollectionsAnalyzer)
6
65
  .addUsingClass('databaseAnalyzer', () => require('../services/schema/update/analyzer/database-analyzer'));
@@ -1,6 +1,4 @@
1
- const ErrorHandler = require('../utils/error-handler');
2
- const SchemaService = require('../services/schema/schema-service');
3
-
1
+ /* eslint-disable global-require */
4
2
  module.exports = (plan) => plan
5
- .addClass(ErrorHandler)
6
- .addClass(SchemaService);
3
+ .addUsingClass('errorHandler', () => require('../utils/error-handler'))
4
+ .addUsingClass('schemaService', () => require('../services/schema/schema-service'));
@@ -1,17 +1,17 @@
1
1
  /* eslint-disable global-require */
2
2
  module.exports = (plan) => plan
3
- .addStep('open', (planOpen) => planOpen
4
- .addFunction('open', require('open')))
5
- .addStep('std', (planStd) => planStd
6
- .addFunction('stdout', process.stdout)
7
- .addFunction('stderr', process.stderr))
8
- .addStep('inquirer', (planInquirer) => planInquirer
9
- .addInstance('inquirer', require('inquirer')))
10
- .addStep('jwtDecode', (planJWTDecode) => planJWTDecode
11
- .addInstance('jwtDecode', require('jwt-decode')))
12
- .addStep('others', (planOthers) => planOthers
3
+ .addPackage('open', (planOpen) => planOpen
4
+ .addUsingFunction('open', () => require('open')))
5
+ .addPackage('std', (planStd) => planStd
6
+ .addUsingFunction('stdout', () => process.stdout)
7
+ .addUsingFunction('stderr', () => process.stderr))
8
+ .addPackage('inquirer', (planInquirer) => planInquirer
9
+ .addInstance('inquirer', () => require('inquirer')))
10
+ .addPackage('jwtDecode', (planJWTDecode) => planJWTDecode
11
+ .addInstance('jwtDecode', () => require('jwt-decode')))
12
+ .addPackage('others', (planOthers) => planOthers
13
13
  .addModule('mkdirp', () => require('mkdirp'))
14
- .addInstance('Table', require('cli-table'))
14
+ .addInstance('Table', () => require('cli-table'))
15
15
  .addModule('chalk', () => require('chalk'))
16
16
  .addModule('crypto', () => require('crypto'))
17
17
  .addModule('fs', () => require('fs'))
@@ -1,12 +1,12 @@
1
1
  /* eslint-disable global-require */
2
2
  module.exports = (plan) => plan
3
- .addStep('dotenv', (planDotenv) => planDotenv
3
+ .addPackage('dotenv', (planDotenv) => planDotenv
4
4
  .addModule('dotenv', () => require('dotenv'), { private: true })
5
5
  .with('dotenv', (dotenv) => dotenv.config()))
6
6
  .addValue('constants', {
7
7
  CURRENT_WORKING_DIRECTORY: process.cwd(),
8
8
  })
9
- .addStep('variables', (planVariables) => planVariables
9
+ .addPackage('variables', (planVariables) => planVariables
10
10
  .addUsingFunction('env', ({ assertPresent, os }) => {
11
11
  assertPresent({ os });
12
12
  const DEFAULT_FOREST_URL = 'https://api.forestadmin.com';
@@ -22,6 +22,6 @@ module.exports = (plan) => plan
22
22
  TOKEN_PATH: process.env.TOKEN_PATH || os.homedir(),
23
23
  };
24
24
  }))
25
- .addStep('others', (planOthers) => planOthers
25
+ .addPackage('others', (planOthers) => planOthers
26
26
  .addValue('process', process)
27
27
  .addModule('pkg', () => require('../../package.json')));
@@ -1,22 +1,12 @@
1
- const processPlan = require('./process-plan');
2
- const envPlan = require('./env-plan');
3
- const dependenciesPlan = require('./dependencies-plan');
4
- const utilsPlan = require('./utils-plan');
5
- const renderersPlan = require('./renderers-plan');
6
- const serializersPlan = require('./serializers-plan');
7
- const servicesPlan = require('./services-plan');
8
- const commandProjectCommonPlan = require('./command-projects-common-plan');
9
- const commandProjectCreatePlan = require('./command-project-create-plan');
10
- const commandSchemaUpdatePlan = require('./command-schema-update-command-plan');
11
-
1
+ /* eslint-disable global-require */
12
2
  module.exports = (plan) => plan
13
- .addStep('dependencies', dependenciesPlan)
14
- .addStep('env', envPlan)
15
- .addStep('process', processPlan)
16
- .addStep('utils', utilsPlan)
17
- .addStep('serializers', serializersPlan)
18
- .addStep('services', servicesPlan)
19
- .addStep('renderers', renderersPlan)
20
- .addStep('commandProjectCommon', commandProjectCommonPlan)
21
- .addStep('commandProjectCreate', commandProjectCreatePlan)
22
- .addStep('commandProjectUpdate', commandSchemaUpdatePlan);
3
+ .addPackage('dependencies', require('./dependencies-plan'))
4
+ .addPackage('env', require('./env-plan'))
5
+ .addPackage('process', require('./process-plan'))
6
+ .addPackage('utils', require('./utils-plan'))
7
+ .addPackage('serializers', require('./serializers-plan'))
8
+ .addPackage('services', require('./services-plan'))
9
+ .addPackage('renderers', require('./renderers-plan'))
10
+ .addPackage('commandProjectCommon', require('./command-projects-common-plan'))
11
+ .addPackage('commandProjectCreate', require('./command-project-create-plan'))
12
+ .addPackage('commandProjectUpdate', require('./command-schema-update-command-plan'));
@@ -1,3 +1,3 @@
1
1
  module.exports = (plan) => plan
2
- .addStep('exit', (context) => context
2
+ .addPackage('exit', (context) => context
3
3
  .addFunction('exitProcess', (exitCode) => process.exit(exitCode)));
@@ -1,10 +1,6 @@
1
- const EnvironmentRenderer = require('../renderers/environment');
2
- const EnvironmentsRenderer = require('../renderers/environments');
3
- const ProjectRenderer = require('../renderers/project');
4
- const ProjectsRenderer = require('../renderers/projects');
5
-
1
+ /* eslint-disable global-require */
6
2
  module.exports = (plan) => plan
7
- .addClass(EnvironmentRenderer)
8
- .addClass(EnvironmentsRenderer)
9
- .addClass(ProjectRenderer)
10
- .addClass(ProjectsRenderer);
3
+ .addUsingClass('environmentRenderer', () => require('../renderers/environment'))
4
+ .addUsingClass('environmentsRenderer', () => require('../renderers/environments'))
5
+ .addUsingClass('projectRenderer', () => require('../renderers/project'))
6
+ .addUsingClass('projectsRenderer', () => require('../renderers/projects'));
@@ -1,14 +1,8 @@
1
- const applicationTokenSerializer = require('../serializers/application-token');
2
- const applicationTokenDeserializer = require('../deserializers/application-token');
3
- const environmentDeserializer = require('../deserializers/environment');
4
- const environmentSerializer = require('../serializers/environment');
5
- const projectDeserializer = require('../deserializers/project');
6
- const projectSerializer = require('../serializers/project');
7
-
1
+ /* eslint-disable global-require */
8
2
  module.exports = (plan) => plan
9
- .addInstance('applicationTokenSerializer', applicationTokenSerializer)
10
- .addInstance('applicationTokenDeserializer', applicationTokenDeserializer)
11
- .addInstance('environmentDeserializer', environmentDeserializer)
12
- .addInstance('environmentSerializer', environmentSerializer)
13
- .addInstance('projectDeserializer', projectDeserializer)
14
- .addInstance('projectSerializer', projectSerializer);
3
+ .addInstance('applicationTokenSerializer', () => require('../serializers/application-token'))
4
+ .addInstance('applicationTokenDeserializer', () => require('../deserializers/application-token'))
5
+ .addInstance('environmentDeserializer', () => require('../deserializers/environment'))
6
+ .addInstance('environmentSerializer', () => require('../serializers/environment'))
7
+ .addInstance('projectDeserializer', () => require('../deserializers/project'))
8
+ .addInstance('projectSerializer', () => require('../serializers/project'));
@@ -1,9 +1,8 @@
1
1
  /* eslint-disable global-require */
2
2
  module.exports = (plan) => plan
3
- .addStep('dependencies', (planDependencies) => planDependencies
4
- .addUsingClass('logger', () => require('../services/logger'))
3
+ .addPackage('dependencies', (planDependencies) => planDependencies
5
4
  .addUsingClass('api', () => require('../services/api'))
6
5
  .addUsingClass('oidcAuthenticator', () => require('../services/oidc/authenticator'))
7
6
  .addUsingClass('applicationTokenService', () => require('../services/application-token')))
8
- .addStep('authenticator', (planAuthenticator) => planAuthenticator
7
+ .addPackage('authenticator', (planAuthenticator) => planAuthenticator
9
8
  .addUsingClass('authenticator', () => require('../services/authenticator')));
@@ -1,8 +1,7 @@
1
- const KeyGenerator = require('../utils/key-generator');
2
- const messages = require('../utils/messages');
3
- const terminator = require('../utils/terminator');
4
-
1
+ /* eslint-disable global-require */
5
2
  module.exports = (plan) => plan
6
- .addClass(KeyGenerator)
7
- .addInstance('terminator', terminator)
8
- .addValue('messages', messages);
3
+ .addUsingClass('keyGenerator', () => require('../utils/key-generator'))
4
+ .addUsingClass('logger', () => require('../services/logger'))
5
+ .addUsingClass('eventSender', () => require('../utils/event-sender'))
6
+ .addUsingFunction('terminator', require('../utils/terminator'))
7
+ .addValue('messages', require('../utils/messages'));
@@ -7,6 +7,7 @@ const { handleError } = require('../utils/error');
7
7
  const ERROR_MESSAGE_PROJECT_IN_V1 = 'This project does not support branches yet. Please migrate your environments from your Project settings first.';
8
8
  const ERROR_MESSAGE_ENV_SECRET_ISSUE = 'Your development environment is not properly set up. Please run `forest init` first and retry.';
9
9
  const ERROR_MESSAGE_BRANCH_ALREADY_EXISTS = 'This branch already exists.';
10
+ const ERROR_MESSAGE_ADDITIONAL_REMOTE_BRANCHES = 'The remote environments can\'t have additional branches.';
10
11
  const ERROR_MESSAGE_NO_PRODUCTION_OR_REMOTE_ENVIRONMENT = 'You cannot run branch commands until this project has either a remote or a production environment.';
11
12
  const ERROR_MESSAGE_NO_REMOTE_ENVIRONMENT = 'You cannot run this command until this project has a remote non-production environment.';
12
13
  const ERROR_MESSAGE_BRANCH_DOES_NOT_EXIST = 'This branch doesn\'t exist.';
@@ -111,8 +112,8 @@ function handleBranchError(rawError) {
111
112
  return ERROR_MESSAGE_ENV_SECRET_ISSUE;
112
113
  case 'Forbidden':
113
114
  return ERROR_MESSAGE_NOT_ADMIN_USER;
114
- case 'Not development environment.':
115
- return ERROR_MESSAGE_ENV_SECRET_ISSUE;
115
+ case 'Environment is not in development.':
116
+ return ERROR_MESSAGE_ADDITIONAL_REMOTE_BRANCHES;
116
117
  case 'Dev Workflow disabled.':
117
118
  return ERROR_MESSAGE_PROJECT_IN_V1;
118
119
  case 'Branch name already exists.':
@@ -1,5 +1,16 @@
1
1
  const chalk = require('chalk');
2
2
 
3
+ const ALLOWED_OPTION_KEYS = [
4
+ 'color',
5
+ 'prefix',
6
+ 'std',
7
+ 'lineColor',
8
+ ];
9
+ const DEFAULT_OPTION_VALUES = ALLOWED_OPTION_KEYS.reduce((options, key) => {
10
+ options[key] = undefined;
11
+ return options;
12
+ }, {});
13
+
3
14
  class Logger {
4
15
  constructor({
5
16
  assertPresent,
@@ -20,17 +31,21 @@ class Logger {
20
31
  if (this.silent) return;
21
32
 
22
33
  options = {
23
- color: null,
24
- prefix: null,
25
- std: null,
34
+ ...DEFAULT_OPTION_VALUES,
26
35
  ...options,
27
36
  };
28
37
 
29
38
  let actualPrefix = '';
30
39
  if ([undefined, null, ''].indexOf(options.prefix) === -1) actualPrefix = `${options.prefix} `;
31
- if (actualPrefix && options.color) actualPrefix = chalk.bold[options.color](actualPrefix);
40
+ if (actualPrefix && options.color) {
41
+ actualPrefix = Logger._setBoldColor(options.color, actualPrefix);
42
+ }
32
43
 
33
- const actualMessage = `${actualPrefix}${message} \n`;
44
+ let actualMessage = Logger._stringifyIfObject(message);
45
+ if (options.lineColor) {
46
+ actualMessage = `${Logger._setColor(options.lineColor, actualMessage)}`;
47
+ }
48
+ actualMessage = `${actualPrefix}${actualMessage}\n`;
34
49
 
35
50
  if (options.std === 'err') {
36
51
  this.stderr.write(actualMessage);
@@ -39,19 +54,72 @@ class Logger {
39
54
  }
40
55
  }
41
56
 
42
- _logLines(messages, options) {
43
- messages.forEach((message) => this._logLine(message, options));
57
+ _logLines(messagesWithPotentialGivenOptions, baseOptions) {
58
+ const { options, messages } = Logger._extractGivenOptionsFromMessages(
59
+ messagesWithPotentialGivenOptions,
60
+ );
61
+ messages.forEach((message) => this._logLine(message, { ...baseOptions, ...options }));
62
+ }
63
+
64
+ static _stringifyIfObject(message) {
65
+ if (typeof message === 'object') {
66
+ return JSON.stringify(message);
67
+ }
68
+
69
+ return message;
70
+ }
71
+
72
+ static _setColor(color, message) {
73
+ return chalk[color](message);
74
+ }
75
+
76
+ static _setBoldColor(color, message) {
77
+ return chalk.bold[color](message);
78
+ }
79
+
80
+ static _isObjectKeysMatchAlwaysTheGivenKeys(object) {
81
+ if (typeof object !== 'object') {
82
+ return false;
83
+ }
84
+
85
+ return Object.keys(object).every((key) => ALLOWED_OPTION_KEYS.includes(key));
86
+ }
87
+
88
+ // This is a hack to keep the current signature of Logger methods.
89
+ // Last `message` is considered an option object if its keys are in `ALLOWED_OPTION_KEYS`.
90
+ static _extractGivenOptionsFromMessages(messages) {
91
+ let options = {};
92
+
93
+ const potentialGivenOptions = messages[messages.length - 1];
94
+ const hasOptions = Logger._isObjectKeysMatchAlwaysTheGivenKeys(potentialGivenOptions);
95
+
96
+ if (hasOptions) {
97
+ messages = messages.slice(0, -1);
98
+ options = { ...options, ...potentialGivenOptions };
99
+ }
100
+
101
+ return { messages, options };
44
102
  }
45
103
 
46
- error(...messages) { this._logLines(messages, { color: 'red', prefix: '×', std: 'err' }); }
104
+ /**
105
+ * Allows to log one ore more messages, with option object as last optional parameter.
106
+ * @example logger.log('message')
107
+ * @example logger.log('message', { color: 'blue', colorLine: 'green' })
108
+ * @example logger.log('message 1', 'message 2')
109
+ * @example logger.log('message 1', 'message 2', { color: 'blue', colorLine: 'green' })
110
+ */
111
+ log(...messagesAndOptions) { this._logLines(messagesAndOptions); }
47
112
 
48
- info(...messages) { this._logLines(messages, { color: 'blue', prefix: '>' }); }
113
+ error(...messagesAndOptions) { this._logLines(messagesAndOptions, { color: 'red', prefix: '×', std: 'err' }); }
49
114
 
50
- log(...messages) { this._logLines(messages); }
115
+ info(...messagesAndOptions) { this._logLines(messagesAndOptions, { color: 'blue', prefix: '>' }); }
51
116
 
52
- success(...messages) { this._logLines(messages, { color: 'green', prefix: '√' }); }
117
+ success(...messagesAndOptions) { this._logLines(messagesAndOptions, { color: 'green', prefix: '√' }); }
53
118
 
54
- warn(...messages) { this._logLines(messages, { color: 'yellow', prefix: 'Δ' }); }
119
+ warn(...messagesAndOptions) { this._logLines(messagesAndOptions, { color: 'yellow', prefix: 'Δ' }); }
55
120
  }
56
121
 
122
+ if (process.env.NODE_ENV === 'test') {
123
+ Logger.DEFAULT_OPTION_VALUES = DEFAULT_OPTION_VALUES;
124
+ }
57
125
  module.exports = Logger;
@@ -33,14 +33,7 @@ module.exports = class DatabaseAnalyzer {
33
33
  });
34
34
  }
35
35
 
36
- async analyze(databaseConnection, config, allowWarning) {
37
- let analyze;
38
- if (config.dbDialect === 'mongodb') {
39
- analyze = this.mongoAnalyzer;
40
- databaseConnection = databaseConnection.db();
41
- } else {
42
- analyze = this.sequelizeAnalyzer;
43
- }
36
+ async _analyze(analyze, databaseConnection, config, allowWarning) {
44
37
  return analyze(databaseConnection, config, allowWarning)
45
38
  .catch((error) => {
46
39
  if (error instanceof EmptyDatabaseError) {
@@ -49,4 +42,23 @@ module.exports = class DatabaseAnalyzer {
49
42
  throw error;
50
43
  });
51
44
  }
45
+
46
+ async analyzeMongoDb(databaseConnection, config, allowWarning) {
47
+ const analyze = this.mongoAnalyzer.analyzeMongoCollections.bind(this.mongoAnalyzer);
48
+ return this._analyze(analyze, databaseConnection.db(), config, allowWarning);
49
+ }
50
+
51
+ async analyze(databaseConnection, config, allowWarning) {
52
+ let analyze;
53
+ if (config.dbDialect === 'mongodb') {
54
+ analyze = this.mongoAnalyzer.analyzeMongoCollectionsWithoutProgressBar.bind(
55
+ this.mongoAnalyzer,
56
+ );
57
+
58
+ databaseConnection = databaseConnection.db();
59
+ } else {
60
+ analyze = this.sequelizeAnalyzer;
61
+ }
62
+ return this._analyze(analyze, databaseConnection, config, allowWarning);
63
+ }
52
64
  };
@@ -1,48 +1,34 @@
1
1
  const P = require('bluebird');
2
- const Context = require('@forestadmin/context');
2
+ const { ObjectId } = require('mongodb');
3
3
 
4
4
  const EmptyDatabaseError = require('../../../../errors/database/empty-database-error');
5
- const { detectReferences, applyReferences } = require('./mongo-references-analyzer');
6
- const { detectHasMany, applyHasMany } = require('./mongo-hasmany-analyzer');
7
- const { isUnderscored } = require('../../../../utils/fields');
8
- const {
9
- getMongooseTypeFromValue,
10
- isOfMongooseType,
11
- } = require('../../../../utils/mongo-primitive-type');
12
- const {
13
- isSystemCollection,
14
- getCollectionName,
15
- } = require('../../../../utils/mongo-collections');
5
+
16
6
  const {
17
- getMongooseArraySchema,
18
- getMongooseEmbeddedSchema,
19
7
  getMongooseSchema,
20
- haveSameEmbeddedType,
21
8
  hasEmbeddedTypes,
22
- mergeAnalyzedSchemas,
23
- } = require('./mongo-embedded-analyzer');
24
-
25
- const mapReduceOptions = {
26
- out: { inline: 1 },
27
- limit: 100,
28
- scope: {
29
- getMongooseArraySchema,
30
- getMongooseEmbeddedSchema,
31
- getMongooseSchema,
32
- getMongooseTypeFromValue,
33
- haveSameEmbeddedType,
34
- hasEmbeddedTypes,
35
- isOfMongooseType,
36
- },
37
- };
38
-
39
- // NOTICE: This code runs on the MongoDB side (mapReduce feature).
9
+ } = require('../../../../services/schema/update/analyzer/mongo-embedded-analyzer');
10
+
11
+ const MAP_REDUCE_ERROR_STRING = 'MapReduceError';
12
+
13
+ // NOTICE: This code runs on the MongoDB side (mapReduce feature) or locally
14
+ // when the the JS is disabled.
40
15
  // The supported JS version is not the same than elsewhere.
41
16
  // The code used here must work with MongoDB lower version supported.
42
17
  /* eslint-disable vars-on-top, no-var, no-undef, no-restricted-syntax,
43
- sonarjs/cognitive-complexity */
18
+ sonarjs/cognitive-complexity, no-use-before-define */
44
19
  /* istanbul ignore next */
45
- function mapCollection() {
20
+ function mapCollection(keys = this, emitFunction, store) {
21
+ // this block is to inject the emit function when this code is running locally
22
+ var emitAction;
23
+ if (emitFunction && store) {
24
+ emitAction = function emit(key, value) {
25
+ emitFunction(key, value, store);
26
+ };
27
+ } else {
28
+ // when the emit is defined by mongodb
29
+ emitAction = emit;
30
+ }
31
+
46
32
  function allItemsAreObjectIDs(array) {
47
33
  if (!array.length) return false;
48
34
  var itemToCheckCount = array.length > 3 ? 3 : array.length;
@@ -56,25 +42,25 @@ function mapCollection() {
56
42
  return arrayOfObjectIDs;
57
43
  }
58
44
 
59
- for (var key in this) {
60
- if (this[key] instanceof ObjectId && key !== '_id') {
61
- emit(key, 'Mongoose.Schema.Types.ObjectId');
62
- } else if (this[key] instanceof Date) {
63
- emit(key, 'Date');
64
- } else if (typeof this[key] === 'boolean') {
65
- emit(key, 'Boolean');
66
- } else if (typeof this[key] === 'string') {
67
- emit(key, 'String');
68
- } else if (typeof this[key] === 'number' && key !== '__v') {
69
- emit(key, 'Number');
70
- } else if (typeof this[key] === 'object') {
71
- if (Array.isArray(this[key]) && allItemsAreObjectIDs(this[key])) {
72
- emit(key, '[Mongoose.Schema.Types.ObjectId]');
45
+ for (var key in keys) {
46
+ if (keys[key] instanceof ObjectId && key !== '_id') {
47
+ emitAction(key, 'Mongoose.Schema.Types.ObjectId');
48
+ } else if (keys[key] instanceof Date) {
49
+ emitAction(key, 'Date');
50
+ } else if (typeof keys[key] === 'boolean') {
51
+ emitAction(key, 'Boolean');
52
+ } else if (typeof keys[key] === 'string') {
53
+ emitAction(key, 'String');
54
+ } else if (typeof keys[key] === 'number' && key !== '__v') {
55
+ emitAction(key, 'Number');
56
+ } else if (typeof keys[key] === 'object') {
57
+ if (Array.isArray(keys[key]) && allItemsAreObjectIDs(keys[key])) {
58
+ emitAction(key, '[Mongoose.Schema.Types.ObjectId]');
73
59
  } else if (key !== '_id') {
74
- var analysis = getMongooseSchema(this[key]);
60
+ var analysis = getMongooseSchema(keys[key]);
75
61
  if (analysis) {
76
62
  // Notice: Wrap the analysis of embedded in a recognizable object for further treatment
77
- emit(key, { type: 'embedded', schema: analysis });
63
+ emitAction(key, { type: 'embedded', schema: analysis });
78
64
  }
79
65
  }
80
66
  }
@@ -85,97 +71,274 @@ function mapCollection() {
85
71
  /* istanbul ignore next */
86
72
  function reduceCollection(key, analyses) {
87
73
  if (hasEmbeddedTypes(analyses)) {
88
- const formatedAnalysis = { type: 'embedded', schemas: [] };
74
+ const formattedAnalysis = { type: 'embedded', schemas: [] };
89
75
  analyses.forEach((analysis) => {
90
76
  if (analysis.type === 'embedded') {
91
- formatedAnalysis.schemas.push(analysis.schema);
77
+ formattedAnalysis.schemas.push(analysis.schema);
92
78
  } else {
93
- formatedAnalysis.schemas.push(analysis);
79
+ formattedAnalysis.schemas.push(analysis);
94
80
  }
95
81
  });
96
- return formatedAnalysis;
82
+ return formattedAnalysis;
97
83
  }
98
84
 
99
85
  return analyses.length ? analyses[0] : null;
100
86
  }
101
87
 
102
- const mapReduceErrors = (resolve, reject, collectionName) => (err, results) => {
103
- const { logger } = Context.inject();
88
+ /* eslint-disable no-shadow */
89
+ class MongoCollectionsAnalyzer {
90
+ constructor({
91
+ assertPresent, logger, detectReferences,
92
+ applyReferences, detectHasMany, applyHasMany,
93
+ isUnderscored, getMongooseTypeFromValue,
94
+ isOfMongooseType, getMongooseArraySchema,
95
+ getMongooseEmbeddedSchema, getMongooseSchema,
96
+ haveSameEmbeddedType, hasEmbeddedTypes,
97
+ mergeAnalyzedSchemas, isSystemCollection,
98
+ getCollectionName, mapCollection, reduceCollection,
99
+ makeProgressBar,
100
+ }) {
101
+ assertPresent({
102
+ logger,
103
+ detectReferences,
104
+ applyReferences,
105
+ detectHasMany,
106
+ applyHasMany,
107
+ isUnderscored,
108
+ getMongooseTypeFromValue,
109
+ isOfMongooseType,
110
+ getMongooseArraySchema,
111
+ getMongooseEmbeddedSchema,
112
+ getMongooseSchema,
113
+ haveSameEmbeddedType,
114
+ hasEmbeddedTypes,
115
+ mergeAnalyzedSchemas,
116
+ isSystemCollection,
117
+ getCollectionName,
118
+ mapCollection,
119
+ reduceCollection,
120
+ makeProgressBar,
121
+ });
122
+
123
+ this.logger = logger;
124
+ this.detectReferences = detectReferences;
125
+ this.applyReferences = applyReferences;
126
+ this.detectHasMany = detectHasMany;
127
+ this.applyHasMany = applyHasMany;
128
+ this.isUnderscored = isUnderscored;
129
+ this.getCollectionName = getCollectionName;
130
+ this.isSystemCollection = isSystemCollection;
131
+ this.mergeAnalyzedSchemas = mergeAnalyzedSchemas;
132
+ this.mapCollection = mapCollection;
133
+ this.reduceCollection = reduceCollection;
134
+ this.makeProgressBar = makeProgressBar;
135
+
136
+ this.restoreDefaultState();
137
+
138
+ this.mapReduceOptions = {
139
+ out: { inline: 1 },
140
+ limit: 100,
141
+ scope: {
142
+ getMongooseArraySchema,
143
+ getMongooseEmbeddedSchema,
144
+ getMongooseSchema,
145
+ getMongooseTypeFromValue,
146
+ haveSameEmbeddedType,
147
+ hasEmbeddedTypes,
148
+ isOfMongooseType,
149
+ },
150
+ };
151
+ }
152
+
153
+ restoreDefaultState() {
154
+ this.isProgressBarDisplay = true;
155
+ }
156
+
157
+ mergeField(field) {
158
+ if (field.value && field.value.type === 'embedded') {
159
+ const schemas = field.value.schemas ? field.value.schemas : [field.value.schema];
160
+ const mergedSchema = this.mergeAnalyzedSchemas(schemas);
104
161
 
105
- /* eslint-enable */
106
- if (err) {
107
- if (err.message && err.message.startsWith('CMD_NOT_ALLOWED')) {
108
- logger.warn(`Δ [${collectionName}] CMD_NOT_ALLOWED: mapReduce. Please, write manually the Mongoose fields on this collection. Δ`);
109
- logger.warn('If your database is hosted on MongoDB Atlas, it\'s probably due to the Free tier limitations. More info here: https://docs.atlas.mongodb.com/unsupported-commands\n');
110
- return resolve([]);
162
+ return {
163
+ name: field._id,
164
+ type: mergedSchema,
165
+ };
111
166
  }
112
- if (err.codeName && err.codeName === 'CommandNotSupportedOnView') {
113
- // NOTICE: Silently ignore views errors (e.g do not import views).
114
- // See: https://github.com/ForestAdmin/lumber/issues/265
115
- return resolve([]);
167
+ return {
168
+ name: field._id,
169
+ type: field.value,
170
+ };
171
+ }
172
+
173
+ mapReduceErrors(resolve, reject) {
174
+ return (err, results) => {
175
+ if (err) {
176
+ if (err.message && (err.message.startsWith('CMD_NOT_ALLOWED') || err.message.startsWith('MapReduce'))) {
177
+ return resolve(MAP_REDUCE_ERROR_STRING);
178
+ }
179
+ if (err.codeName && err.codeName === 'CommandNotSupportedOnView') {
180
+ // NOTICE: Silently ignore views errors (e.g do not import views).
181
+ // See: https://github.com/ForestAdmin/lumber/issues/265
182
+ return resolve([]);
183
+ }
184
+ return reject(err);
185
+ }
186
+
187
+ return resolve(results.map((result) => this.mergeField(result)));
188
+ };
189
+ }
190
+
191
+ static emit(attributeName, attributesType, fieldsTypes) {
192
+ if (fieldsTypes[attributeName]) {
193
+ fieldsTypes[attributeName].push(attributesType);
194
+ } else {
195
+ fieldsTypes[attributeName] = [attributesType];
116
196
  }
117
- return reject(err);
118
197
  }
119
198
 
120
- return resolve(results.map((r) => {
121
- if (r.value && r.value.type === 'embedded') {
122
- const schemas = r.value.schemas ? r.value.schemas : [r.value.schema];
123
- const mergedSchema = mergeAnalyzedSchemas(schemas);
199
+ getFields(fieldWithTypes) {
200
+ const keys = Object.keys(fieldWithTypes);
201
+ return keys.reduce((fields, key) => {
202
+ const field = this.mergeField({
203
+ _id: key,
204
+ value: this.reduceCollection(key, fieldWithTypes[key]),
205
+ });
206
+ fields.push(field);
207
+ return fields;
208
+ }, []);
209
+ }
124
210
 
125
- return { name: r._id, type: mergedSchema };
211
+ // M0 free clusters and M2/M5 shared clusters do not support server-side JavaScript.
212
+ // Also, JS can be disabled on the mongodb instance.
213
+ // https://docs.atlas.mongodb.com/reference/free-shared-limitations/
214
+ // https://docs.mongodb.com/manual/core/server-side-javascript/
215
+ async analyzeMongoCollectionLocally(databaseConnection, collectionName) {
216
+ const collection = databaseConnection.collection(collectionName);
217
+ const analyze = await this.analyzeCollectionAndDisplayProgressBarIfIsAllow(
218
+ collection, collectionName,
219
+ );
220
+ return this.getFields(analyze);
221
+ }
222
+
223
+ analyzeMongoCollectionRemotely(databaseConnection, collectionName) {
224
+ return new Promise((resolve, reject) => {
225
+ databaseConnection.collection(collectionName).mapReduce(
226
+ this.mapCollection,
227
+ this.reduceCollection,
228
+ this.mapReduceOptions,
229
+ this.mapReduceErrors(resolve, reject),
230
+ );
231
+ });
232
+ }
233
+
234
+ buildSchema(fields) {
235
+ return {
236
+ fields,
237
+ references: [],
238
+ primaryKeys: ['_id'],
239
+ options: {
240
+ timestamps: this.isUnderscored(fields),
241
+ },
242
+ };
243
+ }
244
+
245
+ async applyRelationships(databaseConnection, fields, collectionName) {
246
+ const references = await this.detectReferences(databaseConnection, fields, collectionName);
247
+ this.applyReferences(fields, references);
248
+ const hasMany = await this.detectHasMany(databaseConnection, fields, collectionName);
249
+ this.applyHasMany(fields, hasMany);
250
+ return fields;
251
+ }
252
+
253
+ fetchByChunkFunction(collection, numberOfDocumentAllowed) {
254
+ return async (fieldsTypes, index) => {
255
+ const minIndex = index * numberOfDocumentAllowed;
256
+ const options = { minIndex, limit: numberOfDocumentAllowed };
257
+ const documents = await collection.find({}, options).toArray();
258
+ documents.map((document) =>
259
+ this.mapCollection(document, MongoCollectionsAnalyzer.emit, fieldsTypes));
260
+ return fieldsTypes;
261
+ };
262
+ }
263
+
264
+ async analyzeCollectionAndDisplayProgressBarIfIsAllow(collection, collectionName) {
265
+ const countDocuments = await collection.countDocuments();
266
+ if (countDocuments === 0) {
267
+ return {};
126
268
  }
127
- return { name: r._id, type: r.value };
128
- }));
129
- };
130
-
131
- function analyzeMongoCollection(databaseConnection, collectionName) {
132
- return new Promise((resolve, reject) => {
133
- databaseConnection.collection(collectionName)
134
- .mapReduce(
135
- mapCollection,
136
- reduceCollection,
137
- mapReduceOptions,
138
- mapReduceErrors(resolve, reject, collectionName),
269
+
270
+ const numberOfDocumentAllowed = 50;
271
+ const countIterations = Math.ceil(countDocuments / numberOfDocumentAllowed);
272
+
273
+ let fetchFunction = this.fetchByChunkFunction(collection, numberOfDocumentAllowed);
274
+ if (this.isProgressBarDisplay) {
275
+ const bar = this.makeProgressBar(
276
+ `Analysing the **${collectionName}** collection`,
277
+ countIterations,
139
278
  );
140
- });
141
- }
279
+ bar.update(0);
142
280
 
143
- function analyzeMongoCollections(databaseConnection) {
144
- const schema = {};
281
+ fetchFunction = async (fieldTypes, index) => {
282
+ const wrapper = this.fetchByChunkFunction(collection, numberOfDocumentAllowed);
283
+ await wrapper(fieldTypes, index);
284
+ bar.tick();
285
+ return fieldTypes;
286
+ };
287
+ }
145
288
 
146
- return databaseConnection.collections()
147
- .then(async (collections) => {
148
- if (collections.length === 0) {
149
- throw new EmptyDatabaseError('no collections found', {
150
- orm: 'mongoose',
151
- dialect: 'mongodb',
152
- });
153
- }
289
+ const iterations = [...Array(countIterations).keys()];
290
+ return P.reduce(iterations, fetchFunction, {});
291
+ }
154
292
 
155
- return P.each(collections, async (collection) => {
156
- const collectionName = getCollectionName(collection);
293
+ async analyzeMongoCollectionsWithoutProgressBar(databaseConnection) {
294
+ this.isProgressBarDisplay = false;
295
+ return this.analyzeMongoCollections(databaseConnection);
296
+ }
157
297
 
158
- // Ignore system collections and collection without a valid name.
159
- if (!collectionName || isSystemCollection(collection)) {
160
- return;
298
+ async analyzeMongoCollections(databaseConnection) {
299
+ const collections = await databaseConnection.collections();
300
+ if (collections.length === 0) {
301
+ this.restoreDefaultState();
302
+ throw new EmptyDatabaseError('no collections found', {
303
+ orm: 'mongoose',
304
+ dialect: 'mongodb',
305
+ });
306
+ }
307
+ const collectionsInfos = await databaseConnection.listCollections().toArray();
308
+ const isView = (name) => collectionsInfos.find(
309
+ (info) => !!info.options.viewOn && name === info.name,
310
+ );
311
+
312
+ let isMongodbInstanceSupportJs = true;
313
+ const schema = await P.reduce(collections, async (schema, collection) => {
314
+ const collectionName = this.getCollectionName(collection);
315
+
316
+ // Ignore system collections and collection without a valid name.
317
+ if (!collectionName || this.isSystemCollection(collection)) {
318
+ return schema;
319
+ }
320
+ let analysis = [];
321
+ if (isMongodbInstanceSupportJs && !isView(collectionName)) {
322
+ analysis = await this.analyzeMongoCollectionRemotely(databaseConnection, collectionName);
323
+ if (analysis === MAP_REDUCE_ERROR_STRING) {
324
+ isMongodbInstanceSupportJs = false;
325
+ this.logger.warn('The analyze is running locally instead of in the db instance because your instance does not support javascript.'
326
+ + ' This action can takes a bit of time because it fetches all the collections.');
161
327
  }
328
+ }
162
329
 
163
- const analysis = await analyzeMongoCollection(databaseConnection, collectionName);
164
- const references = await detectReferences(databaseConnection, analysis, collectionName);
165
- applyReferences(analysis, references);
166
- const hasMany = await detectHasMany(databaseConnection, analysis, collectionName);
167
- applyHasMany(analysis, hasMany);
168
- schema[collectionName] = {
169
- fields: analysis,
170
- references: [],
171
- primaryKeys: ['_id'],
172
- options: {
173
- timestamps: isUnderscored(analysis),
174
- },
175
- };
176
- });
177
- })
178
- .then(() => schema);
330
+ if (!isMongodbInstanceSupportJs && !isView(collectionName)) {
331
+ analysis = await this.analyzeMongoCollectionLocally(databaseConnection, collectionName);
332
+ }
333
+
334
+ analysis = await this.applyRelationships(databaseConnection, analysis, collectionName);
335
+ schema[collectionName] = this.buildSchema(analysis);
336
+ return schema;
337
+ }, {});
338
+
339
+ this.restoreDefaultState();
340
+ return schema;
341
+ }
179
342
  }
180
343
 
181
- module.exports = analyzeMongoCollections;
344
+ module.exports = { MongoCollectionsAnalyzer, mapCollection, reduceCollection };
@@ -1,3 +1,4 @@
1
+ const { inject } = require('@forestadmin/context');
1
2
  const P = require('bluebird');
2
3
  const _ = require('lodash');
3
4
  const { plural, singular } = require('pluralize');
@@ -5,7 +6,6 @@ const ColumnTypeGetter = require('./sequelize-column-type-getter');
5
6
  const DefaultValueExpression = require('./sequelize-default-value');
6
7
  const TableConstraintsGetter = require('./sequelize-table-constraints-getter');
7
8
  const EmptyDatabaseError = require('../../../../errors/database/empty-database-error');
8
- const { terminate } = require('../../../../utils/terminator');
9
9
  const stringUtils = require('../../../../utils/strings');
10
10
  const { isUnderscored } = require('../../../../utils/fields');
11
11
 
@@ -455,7 +455,7 @@ async function analyzeSequelizeTables(connection, config, allowWarning) {
455
455
  if (!schemas.length) {
456
456
  const message = 'This schema does not exists.';
457
457
 
458
- return terminate(1, {
458
+ return inject().terminator.terminate(1, {
459
459
  errorCode: 'database_authentication_error',
460
460
  errorMessage: message,
461
461
  logs: [message],
@@ -6,7 +6,6 @@ class Database {
6
6
  terminator,
7
7
  }) {
8
8
  assertPresent({
9
- assertPresent,
10
9
  mongodb,
11
10
  Sequelize,
12
11
  terminator,
@@ -1,5 +1,3 @@
1
- const Context = require('@forestadmin/context');
2
-
3
1
  /**
4
2
  * @typedef {{
5
3
  * errorCode: string;
@@ -12,25 +10,29 @@ const Context = require('@forestadmin/context');
12
10
  * }} MultipleMessages
13
11
  */
14
12
 
15
- module.exports = {
16
- /**
17
- * @param {number} status
18
- * @param {DetailedLog | MultipleMessages | DetailedLog & MultipleMessages} log
19
- */
20
- async terminate(status, {
21
- errorCode, errorMessage, logs, context,
22
- }) {
23
- const { eventSender, exitProcess, logger } = Context.inject();
13
+ module.exports = ({
14
+ assertPresent, eventSender, exitProcess, logger,
15
+ }) => {
16
+ assertPresent({ eventSender, exitProcess, logger });
24
17
 
25
- if (logs.length) {
26
- logger.error(...logs);
27
- }
28
- if (errorCode) {
29
- await eventSender.notifyError(errorCode, errorMessage, context);
30
- } else {
31
- await eventSender.notifyError();
32
- }
18
+ return {
19
+ /**
20
+ * @param {number} status
21
+ * @param {DetailedLog | MultipleMessages | DetailedLog & MultipleMessages} log
22
+ */
23
+ async terminate(status, {
24
+ errorCode, errorMessage, logs, context,
25
+ }) {
26
+ if (logs.length) {
27
+ logger.error(...logs);
28
+ }
29
+ if (errorCode) {
30
+ await eventSender.notifyError(errorCode, errorMessage, context);
31
+ } else {
32
+ await eventSender.notifyError();
33
+ }
33
34
 
34
- return exitProcess(status);
35
- },
35
+ return exitProcess(status);
36
+ },
37
+ };
36
38
  };