forest-cli 2.5.1 → 2.5.2

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,10 @@
1
+ ## [2.5.2](https://github.com/ForestAdmin/toolbelt/compare/v2.5.1...v2.5.2) (2021-12-30)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **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))
7
+
1
8
  ## [2.5.1](https://github.com/ForestAdmin/toolbelt/compare/v2.5.0...v2.5.1) (2021-12-10)
2
9
 
3
10
 
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.1","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.2","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.1",
4
+ "version": "2.5.2",
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'));
@@ -23,14 +23,22 @@ class Logger {
23
23
  color: null,
24
24
  prefix: null,
25
25
  std: null,
26
+ lineColor: null,
26
27
  ...options,
27
28
  };
28
29
 
29
30
  let actualPrefix = '';
30
31
  if ([undefined, null, ''].indexOf(options.prefix) === -1) actualPrefix = `${options.prefix} `;
31
- if (actualPrefix && options.color) actualPrefix = chalk.bold[options.color](actualPrefix);
32
+ if (actualPrefix && options.color) {
33
+ actualPrefix = Logger._setBoldColor(options.color, actualPrefix);
34
+ }
35
+
36
+ let actualMessage = message;
37
+ if (options.lineColor) {
38
+ actualMessage = `${Logger._setColor(options.lineColor, actualMessage)}`;
39
+ }
32
40
 
33
- const actualMessage = `${actualPrefix}${message} \n`;
41
+ actualMessage = `${actualPrefix}${actualMessage}\n`;
34
42
 
35
43
  if (options.std === 'err') {
36
44
  this.stderr.write(actualMessage);
@@ -39,8 +47,31 @@ class Logger {
39
47
  }
40
48
  }
41
49
 
42
- _logLines(messages, options) {
43
- messages.forEach((message) => this._logLine(message, options));
50
+ _logLines(messagesWithPotentialGivenOptions, baseOptions) {
51
+ const { options, messages } = Logger._extractGivenOptionsFromMessages(
52
+ messagesWithPotentialGivenOptions,
53
+ );
54
+ messages.forEach((message) => this._logLine(message, { ...baseOptions, ...options }));
55
+ }
56
+
57
+ static _setColor(color, message) {
58
+ return chalk[color](message);
59
+ }
60
+
61
+ static _setBoldColor(color, message) {
62
+ return chalk.bold[color](message);
63
+ }
64
+
65
+ // this method is a hack to keep the signature of all existing public methods.
66
+ static _extractGivenOptionsFromMessages(messages) {
67
+ let options = {};
68
+ const potentialGivenOption = messages[messages.length - 1];
69
+
70
+ if (typeof potentialGivenOption === 'object') {
71
+ options = { ...options, ...potentialGivenOption };
72
+ return { messages: messages.slice(0, -1), options };
73
+ }
74
+ return { messages, options };
44
75
  }
45
76
 
46
77
  error(...messages) { this._logLines(messages, { color: 'red', prefix: '×', std: 'err' }); }
@@ -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,265 @@ 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.isDisplayProgressBar = true;
137
+ this.mapReduceOptions = {
138
+ out: { inline: 1 },
139
+ limit: 100,
140
+ scope: {
141
+ getMongooseArraySchema,
142
+ getMongooseEmbeddedSchema,
143
+ getMongooseSchema,
144
+ getMongooseTypeFromValue,
145
+ haveSameEmbeddedType,
146
+ hasEmbeddedTypes,
147
+ isOfMongooseType,
148
+ },
149
+ };
150
+ }
151
+
152
+ mergeField(field) {
153
+ if (field.value && field.value.type === 'embedded') {
154
+ const schemas = field.value.schemas ? field.value.schemas : [field.value.schema];
155
+ const mergedSchema = this.mergeAnalyzedSchemas(schemas);
104
156
 
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([]);
157
+ return {
158
+ name: field._id,
159
+ type: mergedSchema,
160
+ };
111
161
  }
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([]);
162
+ return {
163
+ name: field._id,
164
+ type: field.value,
165
+ };
166
+ }
167
+
168
+ mapReduceErrors(resolve, reject) {
169
+ return (err, results) => {
170
+ if (err) {
171
+ if (err.message && (err.message.startsWith('CMD_NOT_ALLOWED') || err.message.startsWith('MapReduce'))) {
172
+ return resolve(MAP_REDUCE_ERROR_STRING);
173
+ }
174
+ if (err.codeName && err.codeName === 'CommandNotSupportedOnView') {
175
+ // NOTICE: Silently ignore views errors (e.g do not import views).
176
+ // See: https://github.com/ForestAdmin/lumber/issues/265
177
+ return resolve([]);
178
+ }
179
+ return reject(err);
180
+ }
181
+
182
+ return resolve(results.map((result) => this.mergeField(result)));
183
+ };
184
+ }
185
+
186
+ static emit(attributeName, attributesType, fieldsTypes) {
187
+ if (fieldsTypes[attributeName]) {
188
+ fieldsTypes[attributeName].push(attributesType);
189
+ } else {
190
+ fieldsTypes[attributeName] = [attributesType];
116
191
  }
117
- return reject(err);
118
192
  }
119
193
 
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);
194
+ getFields(fieldWithTypes) {
195
+ const keys = Object.keys(fieldWithTypes);
196
+ return keys.reduce((fields, key) => {
197
+ const field = this.mergeField({
198
+ _id: key,
199
+ value: this.reduceCollection(key, fieldWithTypes[key]),
200
+ });
201
+ fields.push(field);
202
+ return fields;
203
+ }, []);
204
+ }
205
+
206
+ // M0 free clusters and M2/M5 shared clusters do not support server-side JavaScript.
207
+ // Also, JS can be disabled on the mongodb instance.
208
+ // https://docs.atlas.mongodb.com/reference/free-shared-limitations/
209
+ // https://docs.mongodb.com/manual/core/server-side-javascript/
210
+ async analyzeMongoCollectionLocally(databaseConnection, collectionName) {
211
+ const collection = databaseConnection.collection(collectionName);
212
+ const analyze = await this.analyzeCollectionAndDisplayProgressBarIfIsAllow(
213
+ collection, collectionName,
214
+ );
215
+ return this.getFields(analyze);
216
+ }
124
217
 
125
- return { name: r._id, type: mergedSchema };
218
+ analyzeMongoCollectionRemotely(databaseConnection, collectionName) {
219
+ return new Promise((resolve, reject) => {
220
+ databaseConnection.collection(collectionName).mapReduce(
221
+ this.mapCollection,
222
+ this.reduceCollection,
223
+ this.mapReduceOptions,
224
+ this.mapReduceErrors(resolve, reject),
225
+ );
226
+ });
227
+ }
228
+
229
+ buildSchema(fields) {
230
+ return {
231
+ fields,
232
+ references: [],
233
+ primaryKeys: ['_id'],
234
+ options: {
235
+ timestamps: this.isUnderscored(fields),
236
+ },
237
+ };
238
+ }
239
+
240
+ async applyRelationships(databaseConnection, fields, collectionName) {
241
+ const references = await this.detectReferences(databaseConnection, fields, collectionName);
242
+ this.applyReferences(fields, references);
243
+ const hasMany = await this.detectHasMany(databaseConnection, fields, collectionName);
244
+ this.applyHasMany(fields, hasMany);
245
+ return fields;
246
+ }
247
+
248
+ fetchByChunkFunction(collection, numberOfDocumentAllowed) {
249
+ return async (fieldsTypes, index) => {
250
+ const minIndex = index * numberOfDocumentAllowed;
251
+ const options = { minIndex, limit: numberOfDocumentAllowed };
252
+ const documents = await collection.find({}, options).toArray();
253
+ documents.map((document) =>
254
+ this.mapCollection(document, MongoCollectionsAnalyzer.emit, fieldsTypes));
255
+ return fieldsTypes;
256
+ };
257
+ }
258
+
259
+ async analyzeCollectionAndDisplayProgressBarIfIsAllow(collection, collectionName) {
260
+ const countDocuments = await collection.countDocuments();
261
+ if (countDocuments === 0) {
262
+ return {};
126
263
  }
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),
264
+
265
+ const numberOfDocumentAllowed = 50;
266
+ const countIterations = Math.ceil(countDocuments / numberOfDocumentAllowed);
267
+
268
+ let fetchFunction = this.fetchByChunkFunction(collection, numberOfDocumentAllowed);
269
+ if (this.isDisplayProgressBar) {
270
+ const bar = this.makeProgressBar(
271
+ `Analysing the **${collectionName}** collection`,
272
+ countIterations,
139
273
  );
140
- });
141
- }
274
+ bar.update(0);
142
275
 
143
- function analyzeMongoCollections(databaseConnection) {
144
- const schema = {};
276
+ fetchFunction = async (fieldTypes, index) => {
277
+ const wrapper = this.fetchByChunkFunction(collection, numberOfDocumentAllowed);
278
+ await wrapper(fieldTypes, index);
279
+ bar.tick();
280
+ return fieldTypes;
281
+ };
282
+ }
145
283
 
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
- }
284
+ const iterations = [...Array(countIterations).keys()];
285
+ return P.reduce(iterations, fetchFunction, {});
286
+ }
287
+
288
+ async analyzeMongoCollectionsWithoutProgressBar(databaseConnection) {
289
+ this.isDisplayProgressBar = false;
290
+ return this.analyzeMongoCollections(databaseConnection);
291
+ }
292
+
293
+ async analyzeMongoCollections(databaseConnection) {
294
+ const collections = await databaseConnection.collections();
295
+ if (collections.length === 0) {
296
+ throw new EmptyDatabaseError('no collections found', {
297
+ orm: 'mongoose',
298
+ dialect: 'mongodb',
299
+ });
300
+ }
301
+ const collectionsInfos = await databaseConnection.listCollections().toArray();
302
+ const isView = (name) => collectionsInfos.find(
303
+ (info) => !!info.options.viewOn && name === info.name,
304
+ );
154
305
 
155
- return P.each(collections, async (collection) => {
156
- const collectionName = getCollectionName(collection);
306
+ let isMongodbInstanceSupportJs = true;
307
+ return P.reduce(collections, async (schema, collection) => {
308
+ const collectionName = this.getCollectionName(collection);
157
309
 
158
- // Ignore system collections and collection without a valid name.
159
- if (!collectionName || isSystemCollection(collection)) {
160
- return;
310
+ // Ignore system collections and collection without a valid name.
311
+ if (!collectionName || this.isSystemCollection(collection)) {
312
+ return schema;
313
+ }
314
+ let analysis = [];
315
+ if (isMongodbInstanceSupportJs && !isView(collectionName)) {
316
+ analysis = await this.analyzeMongoCollectionRemotely(databaseConnection, collectionName);
317
+ if (analysis === MAP_REDUCE_ERROR_STRING) {
318
+ isMongodbInstanceSupportJs = false;
319
+ this.logger.warn('The analyze is running locally instead of in the db instance because your instance does not support javascript.'
320
+ + ' This action can takes a bit of time because it fetches all the collections.');
161
321
  }
322
+ }
162
323
 
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);
324
+ if (!isMongodbInstanceSupportJs && !isView(collectionName)) {
325
+ analysis = await this.analyzeMongoCollectionLocally(databaseConnection, collectionName);
326
+ }
327
+
328
+ analysis = await this.applyRelationships(databaseConnection, analysis, collectionName);
329
+ schema[collectionName] = this.buildSchema(analysis);
330
+ return schema;
331
+ }, {});
332
+ }
179
333
  }
180
334
 
181
- module.exports = analyzeMongoCollections;
335
+ 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
  };