From 8683b850f0ede832e6ac735a6a40fa7fb23f7840 Mon Sep 17 00:00:00 2001 From: Harry Chen Date: Sat, 2 Sep 2023 17:40:07 +0800 Subject: [PATCH] docs: for faas change (#3219) * docs: change doc struct * docs: update env format --- site/blog/2023-08-14-release-3.12.md | 6 + site/docs/env_config.md | 286 ++++----- site/docs/esm.md | 2 +- site/docs/extensions/bull.md | 6 + site/docs/quick_guide.md | 2 +- site/docs/quickstart.md | 2 +- site/docs/sidebars.json | 2 +- .../current/env_config.md | 548 +++++++++--------- .../current/esm.md | 2 +- .../current/extensions/bull.md | 6 + .../current/quick_guide.md | 2 +- .../current/quickstart.md | 2 +- .../en/docusaurus-theme-classic/navbar.json | 6 +- site/lib/navbar.js | 2 +- 14 files changed, 460 insertions(+), 414 deletions(-) diff --git a/site/blog/2023-08-14-release-3.12.md b/site/blog/2023-08-14-release-3.12.md index 095ce7ca5838..2d7475afc37b 100644 --- a/site/blog/2023-08-14-release-3.12.md +++ b/site/blog/2023-08-14-release-3.12.md @@ -37,6 +37,12 @@ tags: [release] 从 v3.12.0 开始,Midway FaaS 使用全新的一套架构支持现有的 Serverless 平台,这一部分后续将会在文档中体现。 +主要的变化: + +- Midway 不再提供 “应用部署到弹性容器” 的兼容方案,如果平台支持使用传统应用部署 Serverless 容器,可以直接使用标准项目部署 +- Midway 不再提供 f.yml 的维护工作,也不再提供部署功能,仅提供将现有函数信息写入平台配置的能力,所有的函数部署将由平台自己的工具进行部署 +- 移除了原有通过 `@midwayjs/serverless-app` 启动和开发的模式,作为替代,将使用 `@midwayjs/fc-starter` 来进行开发 + ## 其他的一些变化 diff --git a/site/docs/env_config.md b/site/docs/env_config.md index 430d77672bc7..a14b3313b63a 100644 --- a/site/docs/env_config.md +++ b/site/docs/env_config.md @@ -2,18 +2,34 @@ 配置是我们常用的功能,而且在不同的环境,经常会使用不同的配置信息。 - 本篇我们来介绍 Midway 如何加载不同环境的业务配置。 -## 业务配置文件 +## 配置文件 + +最为简单的就是使用框架提供的业务配置文件能力。 +该能力可以在所有业务代码和组件中使用,贯穿整个 Midway 生命周期。 -框架提供了可扩展的配置功能,可以自动合并应用、框架、组件的配置,且可以根据环境维护不同的配置。 +配置文件可以以两种格式导出,**对象形式** 和 **函数形式**。 + +:::tip +经过我们的实践,**对象形式** 会更加的简单友好,可以规避许多错误用法。 + +大部分文档中我们都将以此形式进行展示。 + +::: + + + +### 配置文件目录 + +我们可以自定义一个目录,在其中放入配置文件。 + +比如 `src/config` 目录。 -我们可以自定义目录,在其中放入多个环境的配置文件,如下列常见的目录结构,具体环境的概念请查看 [运行环境](environment)。 ``` ➜ my_midway_app tree . @@ -30,48 +46,116 @@ └── tsconfig.json ``` -`config.default.ts` 为默认的配置文件,所有环境都会加载这个配置文件,一般也会作为开发环境的默认配置文件。 +配置文件的名字有一些特定的约定。 + +`config.default.ts` 为默认的配置文件,所有环境都会加载这个配置文件。 +其余的文件名,使用 `config.环境` 作为文件名,具体环境的概念请查看 [运行环境](environment)。 配置不是 **必选项**,请酌情添加自己需要的环境配置。 -## 加载业务配置 +### 对象形式 -然后我们可以在 `src/configuration.ts` 中配置这个文件(目录),框架就知道加载它了。 + +配置文件导出的格式为 object,比如: ```typescript -// src/configuration.ts -import { Configuration } from '@midwayjs/core'; -import { join } from 'path'; +// src/config/config.default.ts +import { MidwayConfig } from '@midwayjs/core'; -@Configuration({ - importConfigs: [ - join(__dirname, './config/'), - ] -}) -export class MainConfiguration { +export default { + keys: '1639994056460_8009', + koa: { + port: 7001, + }, +} as MidwayConfig; +``` + + + +### 函数形式 + + +配置文件为一个带有 `appInfo` 参数的函数。这个函数在框架初始化时会被自动执行,将返回值合并进完整的配置对象。 + +```typescript +// src/config/config.default.ts +import { MidwayAppInfo, MidwayConfig } from '@midwayjs/core'; + +export default (appInfo: MidwayAppInfo): MidwayConfig => { + return { + keys: '1639994056460_8009', + koa: { + port: 7001, + }, + view: { + root: path.join(appInfo.appDir, 'view'), + }, + }; } + ``` -下面我们将介绍加载配置的两种方式。 +这个函数的参数为 `MidwayAppInfo` 类型,值为以下内容。 + + +| **appInfo** | **说明** | +| ----------- | ------------------------------------------------------------ | +| pkg | package.json | +| name | 应用名,同 pkg.name | +| baseDir | 应用代码的 src (本地开发)或者 dist (上线后)目录 | +| appDir | 应用代码的目录 | +| HOME | 用户目录,如 admin 账户为 /home/admin | +| root | 应用根目录,只有在 local 和 unittest 环境下为 baseDir,其他都为 HOME。 | + + + +### 配置文件定义 + +Midway 提供了 `MidwayConfig` 作为统一的配置项定义,所有的组件都会将定义合并到此配置项定义中。每当一个组件被开启(在 `configuration.ts` 中被 `imports` ),`MidwayConfig` 就会自动包含该组件的配置定义。 + +为此,请尽可能使用文档推荐的格式,以达到最佳的使用效果。 + +每当启用一个新组件时,配置定义都会自动加入该组件的配置项,通过这个行为,也可以变相的检查是否启用了某个组件。 + +比如,我们启用了 view 组件的效果。 + +![](https://img.alicdn.com/imgextra/i2/O1CN013sHGlA1o3uQ4Pg0nO_!!6000000005170-2-tps-1416-572.png) + +:::tip + +为什么不使用普通 key 导出形式而使用对象? + +1、用户在不了解配置项的情况下,依旧需要查看文档了解每项含义,除了第一层有一定的提示作用外,后面的层级提示没有很明显的效率提升 + +2、key 导出的形式在过深的结构下展示没有优势 + +3、key 导出可能会出现重复,但是代码层面不会有警告或者报错,难以排查,这一点对象形式较为友好 + +::: + +### 对象形式加载配置文件 -### 1、对象形式加载 -从 Midway v3 开始,我们将以标准的对象加载方式作为主推的配置引入形式。 +框架提供了加载不同环境的配置文件的功能,需要在 `src/configuration.ts` 文件中开启。 -在一些场景下,比如单文件构建等和目录结构无关的需求,只支持这种标准的模块加载方式来加载配置。 + +配置加载有两种方式,**对象形式** 和 **指定目录形式** 加载。 + +从 Midway v3 开始,我们将以 **对象形式** 作为主推的配置加载形式。 + +在单文件构建、ESM 等场景下,只支持这种标准的模块加载方式来加载配置。 每个环境的配置文件 **必须显式指定添加**,后续框架会根据实际的环境进行合并。 ```typescript // src/configuration.ts import { Configuration } from '@midwayjs/core'; -import { join } from 'path'; import * as DefaultConfig from './config/config.default'; import * as LocalConfig from './config/config.local'; @@ -91,11 +175,11 @@ export class MainConfiguration { -### 2、指定目录或者文件加载 - +### 指定目录、文件加载配置 指定加载一个目录,目录里所有的 `config.*.ts` 都会被扫描加载。 +ESM,单文件部署等方式不支持目录配置加载。 :::info `importConfigs` 这里只是指定需要加载的文件,实际运行时会**自动选择当前的环境**来找对应的文件后缀。 @@ -183,106 +267,9 @@ export class MainConfiguration { -## 配置格式 - -Midway 提供了 `MidwayConfig` 定义,每当一个组件被开启(在 `configuration.ts` 中被 `imports` ),`MidwayConfig` 就会自动包含该组件的配置定义。 -配置可以以两种格式导出。 - -:::tip - -经过我们的实践,以对象导出会更加的简单友好,可以规避许多错误用法。 - -组件的配置我们都将以此格式编写文档。 - -::: - - - -### 1、对象形式 - - -配置文件格式为 object,比如: - -```typescript -// src/config/config.default.ts -import { MidwayConfig } from '@midwayjs/core'; - -export default { - keys: '1639994056460_8009', - koa: { - port: 7001, - }, -} as MidwayConfig; -``` - - - -### 2、函数形式 - - -配置文件为一个带有 `appInfo` 参数的函数。通过这样返回方法的形式,在运行期会被自动执行,将返回值合并进完整的配置对象。 - -```typescript -// src/config/config.default.ts -import { MidwayAppInfo, MidwayConfig } from '@midwayjs/core'; - -export default (appInfo: MidwayAppInfo): MidwayConfig => { - return { - keys: '1639994056460_8009', - koa: { - port: 7001, - }, - view: { - root: path.join(appInfo.appDir, 'view'), - }, - }; -} - -``` - -这个函数的参数为 `MidwayAppInfo` 类型,值为以下内容。 - - -| **appInfo** | **说明** | -| ----------- | ------------------------------------------------------------ | -| pkg | package.json | -| name | 应用名,同 pkg.name | -| baseDir | 应用代码的 src (本地开发)或者 dist (上线后)目录 | -| appDir | 应用代码的目录 | -| HOME | 用户目录,如 admin 账户为 /home/admin | -| root | 应用根目录,只有在 local 和 unittest 环境下为 baseDir,其他都为 HOME。 | - - - -## 配置定义 - -Midway 提供了 `MidwayConfig` 作为统一的配置项定义,所有的组件都会将定义合并到此配置项定义中。 - -为此,请尽可能使用文档推荐的格式,以达到最佳的使用效果。 - -每当启用一个新组件时,配置定义都会自动加入该组件的配置项,通过这个行为,也可以变相的检查是否启用了某个组件。 - -比如,我们启用了 view 组件的效果。 - -![](https://img.alicdn.com/imgextra/i2/O1CN013sHGlA1o3uQ4Pg0nO_!!6000000005170-2-tps-1416-572.png) - -:::tip - -为什么不使用普通 key 导出形式而使用对象? - -1、用户在不了解配置项的情况下,依旧需要查看文档了解每项含义,除了第一层有一定的提示作用外,后面的层级提示没有很明显的效率提升 - -2、key 导出的形式在过深的结构下展示没有优势 - -3、key 导出可能会出现重复,但是代码层面不会有警告或者报错,难以排查,这一点对象形式较为友好 - -::: - - - -## 配置加载顺序 +### 配置加载顺序 配置存在优先级(应用代码 > 组件),相对于此运行环境的优先级会更高。 @@ -300,7 +287,7 @@ Midway 提供了 `MidwayConfig` 作为统一的配置项定义,所有的组件 -## 配置合并规则 +### 配置合并规则 默认会加载 `**/config.defaut.ts` 的文件以及 `**/config.{环境}.ts` 文件。 @@ -490,48 +477,69 @@ export class MainConfiguration { } ``` -注意,`onConfigLoad` 生命周期会在 egg 插件(若有)初始化之后执行,所以不能用于覆盖 egg 插件所使用的配置。 +:::caution + +`onConfigLoad` 生命周期会在 egg 插件(若有)初始化之后执行,不能用于覆盖 egg 插件的配置。 + +::: -### bootstrap 中添加配置 +### 启动时修改 -可以在启动代码之前添加配置。 +可以在启动代码之前,使用 Bootstrap 的 `configure` 方法添加配置。 + +`configure` 方法可以传递一个 `globalConfig` 的属性,可以在应用启动前传递一个全局配置。 + +如果传递数组,则可以区分环境。 ```typescript // bootstrap.js const { Bootstrap } = require('@midwayjs/bootstrap'); Bootstrap .configure({ - globalConfig: { - default: { - keys: 'abcde', - koa: { - port: 7001 - } - }, - unittest: { - koa: { - port: null + globalConfig: [ + { + default: { + abc: '123' + }, + unittest: { + abc: '321' } } - } + ] }) .run(); + +// in unittest, app.getConfig('abc') => '321' ``` -`configure` 方法可以传递一个 `globalConfig` 的属性,可以在应用启动前传递一个全局配置,结构和 “对象形式的配置一致”,区分环境。 +如果传递对象,则直接覆盖。 + +```typescript +// bootstrap.js +const { Bootstrap } = require('@midwayjs/bootstrap'); +Bootstrap + .configure({ + globalConfig: { + abc: 'text' + } + }) + .run(); + +// app.getConfig('abc') => 'text' +``` -### 使用 API 添加配置 +### 使用 API 修改 其他场景的修改配置,可以使用 midway 提供的 [API](./built_in_service#midwayconfigservice)。 -## 使用环境变量 +## 环境变量和配置 社区有一些库,比如 `dotenv` 可以加载 `.env` 文件注入到环境中,从而将一些秘钥放在环境中,在 Midway 中可以直接依赖它使用。 diff --git a/site/docs/esm.md b/site/docs/esm.md index 5abdb7aeacb7..ba53d7354f2c 100644 --- a/site/docs/esm.md +++ b/site/docs/esm.md @@ -26,7 +26,7 @@ 由于改动较多,Midway 提供了全新的 ESM 格式的脚手架,如有 ESM 的需求,我们推荐用户重新创建后再来开发业务。 ```bash -$ npm init midway +$ npm init midway@latest -y ``` 选择 esm 分组中的脚手架。 diff --git a/site/docs/extensions/bull.md b/site/docs/extensions/bull.md index 37c9eb7cc63a..61a207a97d91 100644 --- a/site/docs/extensions/bull.md +++ b/site/docs/extensions/bull.md @@ -734,6 +734,12 @@ export default { +## 关于 Redis 版本 + +请尽可能选择最新的版本( >=5 ),目前在低版本 redis 上有发现定时任务创建失败的问题。 + + + ## Bull UI 在分布式场景中,我们可以资利用 Bull UI 来简化管理。 diff --git a/site/docs/quick_guide.md b/site/docs/quick_guide.md index 2b524c5b1456..a25706c7c38b 100644 --- a/site/docs/quick_guide.md +++ b/site/docs/quick_guide.md @@ -16,7 +16,7 @@ 我们推荐直接使用脚手架,只需几条简单指令,即可快速生成项目。 ```bash -$ npm init midway +$ npm init midway@latest -y ``` 选择 `koa-v3` 项目进行初始化创建,项目名可以自定,比如 `weather-sample`。 diff --git a/site/docs/quickstart.md b/site/docs/quickstart.md index 2f5e471d8021..6aa00952a8dd 100644 --- a/site/docs/quickstart.md +++ b/site/docs/quickstart.md @@ -23,7 +23,7 @@ Midway 有多套技术方案可以选择,我们以部署的方式来做区分 使用 `npm init midway` 查看完整的脚手架列表,选中某个项目后,Midway 会自动创建示例目录,代码,以及安装依赖。 ```bash -$ npm init midway +$ npm init midway@latest -y ``` 针对 v3 项目,请选择 `koa-v3`,注意 [Node.js 环境要求](/docs/intro#环境准备工作)。 diff --git a/site/docs/sidebars.json b/site/docs/sidebars.json index d96448354750..74db91958841 100644 --- a/site/docs/sidebars.json +++ b/site/docs/sidebars.json @@ -8,6 +8,7 @@ "items": [ "intro", "quick_guide", + "how_to_update_midway", "upgrade_v3" ] }, @@ -325,7 +326,6 @@ "collapsed": false, "collapsible": false, "items": [ - "how_to_update_midway", "faq/framework_problem", "faq/git_problem", "faq/npm_problem", diff --git a/site/i18n/en/docusaurus-plugin-content-docs/current/env_config.md b/site/i18n/en/docusaurus-plugin-content-docs/current/env_config.md index b51108034df3..f7d1f9837346 100644 --- a/site/i18n/en/docusaurus-plugin-content-docs/current/env_config.md +++ b/site/i18n/en/docusaurus-plugin-content-docs/current/env_config.md @@ -1,19 +1,35 @@ # Multi-environment configuration -Configuration is a common function, and different configuration information is often used in different environments. - +Configuration is a commonly used function, and different configuration information is often used in different environments. In this article, we will introduce how Midway loads business configurations for different environments. -## Business profile +## Configuration file + +The simplest is to use the business configuration file capabilities provided by the framework. + +This capability is available across all business code and components throughout the Midway lifecycle. + +Configuration files can be exported in two formats, **object form** and **function form**. + +:::tip + +After our practice, **object form** will be simpler and more friendly, and can avoid many wrong usages. + +We will display it in this form in most documents. + +::: + + +### Configuration file directory -The framework provides extensible configuration functions, which can automatically merge the configurations of applications, frameworks, and components, and can maintain different configurations according to the environment. +We can customize a directory and put the configuration file in it. +For example, the `src/config` directory. -You can customize the directory and put the configuration files of multiple environments in it. For example, the following common directory structures are used. For more information about the specific environment, see [Running environment](environment). ``` ➜ my_midway_app tree . @@ -30,75 +46,144 @@ You can customize the directory and put the configuration files of multiple envi └── tsconfig.json ``` -`Config. default.ts` is the default configuration file. All environments will load this configuration file and will generally be used as the default configuration file for the development environment. +There are some specific conventions for configuration file names. + +`config.default.ts` is the default configuration file, and all environments will load this configuration file. +For the rest of the file names, use `config.environment` as the file name. For the concept of specific environment, please see [Running Environment](environment). -The configuration is not **required**. You must add the required environment. +Configuration is not **required**, please add the environment configuration you need as appropriate. -## Load business configuration +### Object form -Then we can configure this file (directory) in `src/configuration.ts`, and the framework will know to load it. + +The configuration file export format is object, for example: ```typescript -// src/configuration.ts -import { Configuration } from '@midwayjs/core'; -import { join } from 'path'; +// src/config/config.default.ts +import { MidwayConfig } from '@midwayjs/core'; -@Configuration({ - importConfigs: [ - join(__dirname, './config/') - ] -}) -export class MainConfiguration { +export default { + keys: '1639994056460_8009', + koa: { + port: 7001, + }, +} as MidwayConfig; +``` + + + +### Function form + + +The configuration file is a function with `appInfo` parameters. This function will be automatically executed when the framework is initialized, and the return value will be merged into the complete configuration object. + +```typescript +// src/config/config.default.ts +import { MidwayAppInfo, MidwayConfig } from '@midwayjs/core'; + +export default (appInfo: MidwayAppInfo): MidwayConfig => { + return { + keys: '1639994056460_8009', + koa: { + port: 7001, + }, + view: { + root: path.join(appInfo.appDir, 'view'), + }, + }; } + ``` -Below we will introduce two ways to load the configuration. +The parameter of this function is `MidwayAppInfo` type, and the value is as follows. + + +| **appInfo** | **Description** | +| ----------- | ------------------------------------------------------------ | +| pkg | package.json | +| name | application name, same as pkg.name | +| baseDir | src (local development) or dist (online) directory of the application code | +| appDir | directory for application code | +| HOME | user directory, such as /home/admin for the admin account | +| root | Application root directory, baseDir only in local and unittest environments, and HOME in others. | + + + +### Configuration file definition + +Midway provides `MidwayConfig` as a unified configuration item definition, and all components will merge their definitions into this configuration item definition. Whenever a component is enabled (`imports` in `configuration.ts`), `MidwayConfig` will automatically include the configuration definition for that component. + +For this reason, please use the format recommended by the documentation as much as possible to achieve the best usage effect. + +Whenever a new component is enabled, the configuration definition will automatically add the configuration items of the component. Through this behavior, you can also check whether a certain component is enabled in disguise. + +For example, we enable the effect of the view component. + +![](https://img.alicdn.com/imgextra/i2/O1CN013sHGlA1o3uQ4Pg0nO_!!6000000005170-2-tps-1416-572.png) + +:::tip + +Why use objects instead of plain key exports? + +1. If the user does not understand the configuration items, he still needs to check the document to understand the meaning of each item. Except for the first level of prompts, the subsequent levels of prompts do not have obvious efficiency improvements. + +2. The form of key export has no advantage in displaying under an overly deep structure + +3. The key export may be repeated, but there will be no warnings or errors at the code level, which is difficult to troubleshoot. The object form is more friendly + +::: + + + +### Load configuration file in object form +The framework provides the function of loading configuration files for different environments, which needs to be enabled in the `src/configuration.ts` file. -### 1. Object form loading -Starting from Midway v3, we will introduce the standard object loading method as the configuration of the main push. +There are two ways to load configuration, **object format** and **specified directory format** loading. -In some scenarios, such as single-file construction and other requirements that are not related to the directory structure, only this standard module loading method is supported to load the configuration. +Starting from Midway v3, we will use **object form** as the main configuration loading form. -The configuration files of each environment **must be explicitly specified and added**. Subsequent frames are merged based on the actual environment. +In scenarios such as single-file construction and ESM, only this standard module loading method is supported to load configurations. + +The configuration file of each environment **must explicitly specify to add**, and subsequent frameworks will be merged according to the actual environment. ```typescript // src/configuration.ts import { Configuration } from '@midwayjs/core'; -import { join } from 'path'; import * as DefaultConfig from './config/config.default'; import * as LocalConfig from './config/config.local'; @Configuration({ - importConfigs: [ - { - default: DefaultConfig - local: LocalConfig - } - ] + importConfigs: [ + { + default: DefaultConfig, + local: LocalConfig + } + ] }) export class MainConfiguration { } ``` -The array in the `importConfigs` passes configuration objects. The key of each object is the environment, and the value is the configuration value corresponding to the environment. midway loads the corresponding configuration according to the environment during startup. +Configuration objects are passed in the array in `importConfigs`. The key of each object is the environment, and the value is the configuration value corresponding to the environment. Midway will load the corresponding configuration according to the environment during startup. -### 2. Specify directory or file loading +### Specify directory and file loading configuration -Specifies that a directory is loaded. All `config.*.ts` in the directory are scanned and loaded. +Specify a directory to load, and all `config.*.ts` in the directory will be scanned and loaded. +ESM, single-file deployment, etc. do not support directory configuration loading. :::info -`importConfigs` here, only the files to be loaded are specified. In actual runtime, the current environment** will be **automatically selected to find the corresponding file suffix. +`importConfigs` here just specify the files that need to be loaded, and the actual runtime will **automatically select the current environment** to find the corresponding file suffix. ::: @@ -106,12 +191,12 @@ The rules for the configuration file are: - 1. You can specify a directory, the traditional `src/config` directory is recommended, or you can specify a file -- 2. file designation does not require TS suffix -- 3. The configuration file **must be explicitly specified and added**. +- 2. The file specification does not require the ts suffix +- 3. Configuration file **Must be explicitly specified to add** -**Example: Specify a directory** +**Example: specify directory** ```typescript // src/configuration.ts @@ -119,19 +204,19 @@ import { Configuration } from '@midwayjs/core'; import { join } from 'path'; @Configuration({ - importConfigs: [ - join(__dirname, './config/'), - ] + importConfigs: [ + join(__dirname, './config/'), + ] }) export class MainConfiguration { } ``` -**Example: Specify a specific file** +**Example: specifying a specific file** -When you manually specify a batch of files, an error will be reported if the file does not exist at this time. +When manually specifying a batch of files, if the files do not exist at this time, an error will be reported. ```typescript @@ -140,18 +225,18 @@ import { Configuration } from '@midwayjs/core'; import { join } from 'path'; @Configuration({ - importConfigs: [ - join(__dirname, './config/config.default'), - join(__dirname, './config/config.local'), - join(__dirname, './config/custom.local') // You can use custom naming, as long as the middle part has an environment - ] + importConfigs: [ + join(__dirname, './config/config.default'), + join(__dirname, './config/config.local'), + join(__dirname, './config/custom.local') // You can use custom naming, as long as the middle part has an environment + ] }) export class MainConfiguration { } ``` -You can also use configurations outside the project, but use the absolute path and the `*.js` suffix. +You can also use the configuration outside the project, but please use the absolute path and `*.js` suffix. For example, the directory structure is as follows (note the `customConfig.default.js` file): @@ -172,10 +257,10 @@ import { Configuration } from '@midwayjs/core'; import { join } from 'path'; @Configuration({ - importConfigs: [ - join(__dirname, './config/') - join(__dirname, '../customConfig.default') - ] + importConfigs: [ + join(__dirname, './config/'), + join(__dirname, '../customConfig.default'), + ] }) export class MainConfiguration { } @@ -183,184 +268,88 @@ export class MainConfiguration { -## Configuration format - -Midway provides a `MidwayConfig` definition. Whenever a component is turned on (`imports` in `configuration.ts` ), the `MidwayConfig` will automatically include the configuration definition of the component. - -Configurations can be exported in two formats. - -:::tip - -Through our practice, exporting objects will be simpler and more friendly, and many wrong usages can be avoided. - -The configuration of the components will be documented in this format. - -::: - - - - -### 1. Object Form - - -The configuration file format is object, for example: - -```typescript -// src/config/config.default.ts -import { MidwayConfig } from '@midwayjs/core'; - -export default { - keys: '1639994056460_8009', - koa: { - port: 7001, - }, -} as MidwayConfig; -``` - - - -### 2. Function form - - -The configuration file is a function with `appInfo` parameters. In the form of this return method, it will be automatically executed during the runtime, merging the return values into the complete configuration object. - -```typescript -// src/config/config.default.ts -import { MidwayAppInfo, MidwayConfig } from '@midwayjs/core'; - -export default (appInfo: MidwayAppInfo): MidwayConfig => { - return { - keys: '1639994056460_8009', - koa: { - port: 7001 - }, - view: { - root: path.join(appInfo.appDir, 'view') - }, - }; -} - -``` - -The parameter of this function is of `MidwayAppInfo` type and the value is the following. - - -| **appInfo** | **Description** | -| ----------- | ------------------------------------------------------------ | -| pkg | package.json | -| name | Application name, same as pkg.name | -| baseDir | The src (locally developed) or dist (after online) directory of the application code | -| appDir | Directory of application code | -| HOME | The user directory, for example, the admin account is/home/admin. | -| root | The root directory of the application is only baseDir in local and unittest environments, and the others are HOME. | - - - -## Configuration definition - -Midway provides `MidwayConfig` as a unified configuration item definition, and all components merge the definition into this configuration item definition. - -To do this, please use the format recommended by the document as much as possible to achieve the best effect. - -Whenever a new component is enabled, the configuration definition will automatically add the configuration items of the component. Through this behavior, you can also check whether a component is enabled in disguise. - -For example, we have enabled the effect of the view component. - -![](https://img.alicdn.com/imgextra/i2/O1CN013sHGlA1o3uQ4Pg0nO_!!6000000005170-2-tps-1416-572.png) - -:::tip - -Why not use the normal key export form and use the object? - -1. If the user does not understand the configuration items, he still needs to check the document to understand the meaning of each item. Except that the first layer has a certain prompt function, the later level prompts have no obvious efficiency improvement. - -2. The form of key export has no advantage in the deep structure. - -3. Key export may be duplicated, but there will be no warning or error at the code level, which is difficult to troubleshoot. This object form is relatively friendly. - -::: - -## Configure load order +### Configure loading order -There is a priority in the configuration (application code> component), and the priority will be higher relative to this operating environment. +There is a priority for configuration (Application Code > Component), and the priority will be higher relative to this running environment. -For example, the loading sequence of a configuration in the prod environment is as follows, and the subsequent loading will overwrite the previous configuration with the same name. +For example, the loading sequence for loading a configuration in the prod environment is as follows. The later loaded configuration will overwrite the previous configuration with the same name. ```typescript --> component config.default.ts --> apply config.default.ts +-> Component config.default.ts +-> Apply config.default.ts -> component config.prod.ts -> apply config.prod.ts ``` -## Configure merge rules +### Configure merge rules -By default, the `**/config.defaut.ts` file and the `**/config.{environment}.ts` file are loaded. +By default, the `**/config.defaut.ts` file and the `**/config.{environment}.ts` file will be loaded. +For example, the following code will search for `config.default.*` and `config.local.*` files in the `local` environment. If it is in other environments, it will only search for `config.default.*` and `config.{Current environment}.*`, if the file does not exist, it will not be loaded and no error will be reported. -For example, the following code will find the `config.default.*` and `config.local.*` files in the `local` environment. If the file is in other environments, only `config.default.*` and `config.{current environment}.*` will be found. If the file does not exist, it will not be loaded or an error will be reported. ```typescript // src/configuration.ts import { Configuration } from '@midwayjs/core'; import { join } from 'path'; @Configuration({ - importConfigs: [ - join(__dirname, './config/'), - ] + importConfigs: [ + join(__dirname, './config/'), + ] }) export class MainConfiguration { } ``` -In order to be forward compatible, we have done some processing on configuration reading for some special environments. The value of the environment here refers to the [result](environment#AxjGQ) obtained from the combination of `NODE_ENV` and `MIDWAY_SERVER_ENV` values. +For forward compatibility, we have done some processing on the configuration reading of some special environments. The value of the environment here refers to the [result](environment#AxjGQ) based on the values of `NODE_ENV` and `MIDWAY_SERVER_ENV`. -| **Environment Value** | **Read configuration file** | -| --- | --- | -| prod | *.default.ts + *.prod.ts | -| production | *.default.ts + *.production.ts + *.prod.ts | -| unittest | *.default.ts + *.unittest.ts | -| test | *.default.ts + *.test.ts + *.unittest.ts | +| **Environment value** | **Configuration file read** | +| --------------------- | ------------------------------------------ | +| prod | *.default.ts + *.prod.ts | +| production | *.default.ts + *.production.ts + *.prod.ts | +| unittest | *.default.ts + *.unittest.ts | +| test | *.default.ts + *.test.ts + *.unittest.ts | -Except for the above table, the rest are values of `*.default.ts + *.{current environment}.ts`. +Except for the above table, the rest are the values of `*.default.ts + *.{current environment}.ts`. -In addition, the configured merge uses the [extend2](https://github.com/eggjs/extend2) module for deep copy, [extend2](https://github.com/eggjs/extend2) fork from [extend](https://github.com/justmoon/node-extend), and there will be differences in array processing. +In addition, the configuration is merged using the [extend2](https://github.com/eggjs/extend2) module for deep copying, and the [extend2](https://github.com/eggjs/extend2) fork from [extend](https ://github.com/justmoon/node-extend), there will be differences when handling arrays. ```javascript const a = { - arr: [ 1, 2 ], + arr: [ 1, 2 ], }; const b = { - arr: [ 3 ], + arr: [ 3 ], }; extend(true, a, b); // => { arr: [ 3 ] } ``` -According to the above example, the framework directly covers the array instead of merging. + +According to the example above, the framework directly overwrites the array instead of doing the merge. -## Get configuration +## get configuration -Midway saves all the configurations in the internal configuration service. The entire structure is an object. When using the Midway service code, use the `@Config` decorator to inject the configuration. +Midway will save the configuration in the internal configuration service. The entire structure is an object, which is injected using the `@Config` decorator when used by Midway business code. ### Single configuration value -By default, it is obtained from the configuration object based on the string parameter value of the decorator. +By default, it will be obtained from the configuration object according to the string parameter value of the decorator. ```typescript @@ -368,21 +357,21 @@ import { Config } from '@midwayjs/core'; export class IndexHandler { - @Config('userService') - userConfig; + @Config('userService') + userConfig; - async handler() { - console.log(this.userConfig); // { appname: 'test'} - } + async handler() { + console.log(this.userConfig); // { appname: 'test'} + } } ``` -### Deep level configuration value +### Deep level configuration values -If the value of the configuration object is deep in the object, it can be obtained in Cascade. +If the value of the configuration object is deep in the object, it can be obtained in a cascaded manner. For example, the data source is: @@ -390,28 +379,31 @@ For example, the data source is: ```json { - "userService": { - "appname": { - "test": { - "data": "xxx" - } - } - } + "userService": { + "appname": { + "test": { + "data": "xxx" + } + } + } } ``` -You can write complex fetch expressions to fetch values, as shown in the following example. + +You can write complex acquisition expressions to acquire values, examples are as follows. + ```typescript import { Config } from '@midwayjs/core'; export class IndexHandler { - @Config('userService.appname.test.data') - data; + @Config('userService.appname.test.data') + data; - async handler() { - console.log(this.data); // xxx - } + async handler() { + console.log(this.data); // xxx + } } + ``` @@ -419,50 +411,51 @@ export class IndexHandler { ### The entire configuration object -You can also use the `ALL` attribute to obtain the entire configured object. +You can also get the entire configuration object through the special attribute `ALL`. + ```typescript import { Config, ALL } from '@midwayjs/core'; export class IndexHandler { - @Config(ALL) - allConfig; + @Config(ALL) + allConfig; - async handler() { - console.log(this.allConfig); // { userService: { appname: 'test'}} - } + async handler() { + console.log(this.allConfig); // { userService: { appname: 'test'}} + } } ``` -## Modify configuration +## Change setting -In the coding process, we have some places that can dynamically modify the configuration for different scenarios. +During the coding process, we have some places where the configuration can be dynamically modified for use in different scenarios. -### Modification in Life Cycle +### Modification during life cycle -midway adds an asynchronous configuration loading lifecycle that can be executed after the configuration is loaded. +midway has added an asynchronous configuration loading life cycle, which can be executed after the configuration is loaded. ```typescript // src/configuration.ts -import { Configuration, IMidwayContainer, IMidwayContainer } from '@midwayjs/core'; +import { Configuration, IMidwayContainer } from '@midwayjs/core'; import { join } from 'path'; -import { RemoteConfigService } from '../service/remote'; // Custom Get Remote Configuration Service +import { RemoteConfigService } from '../service/remote'; // Customized access to remote configuration service @Configuration({ - importConfigs: [ - join(__dirname, './config/') - ] + importConfigs: [ + join(__dirname, './config/'), + ] }) export class MainConfiguration { - + async onConfigLoad(container: IMidwayContainer) { // Here you can modify the global configuration - const remoteConfigService = await container.getAsync(RemoteConfigService); + const remoteConfigService = await container. getAsync(RemoteConfigService); const remoteConfig = await remoteConfigService.getData(); // The return value here will be merged with the global config @@ -484,65 +477,92 @@ export class MainConfiguration { // } // } // } + return remoteConfig; } } ``` -Note that the `onConfigLoad` lifecycle is executed after the egg plug-in (if any) is initialized, so it cannot be used to override the configuration used by the egg plug-in. +:::caution + +The `onConfigLoad` lifecycle is executed after the egg plugin (if any) is initialized and cannot be used to override the configuration of the egg plugin. + +::: + + +### Modify at startup +You can add configuration using Bootstrap's `configure` method before starting the code. -### Add configuration in bootstrap +The `configure` method can pass a `globalConfig` attribute, which can pass a global configuration before the application starts. -You can add configuration before starting the code. +If you pass an array, you can differentiate between environments. ```typescript // bootstrap.js const { Bootstrap } = require('@midwayjs/bootstrap'); Bootstrap .configure({ - globalConfig: { - default: { - keys: 'abcde', - koa: { - port: 7001 - } - }, - unittest: { - koa: { - port: null + globalConfig: [ + { + default: { + abc: '123' + }, + unittest: { + abc: '321' } } + ] + }) + .run(); + +// in unittest, app.getConfig('abc') => '321' +``` + +If an object is passed, it is overridden directly. + +```typescript +// bootstrap.js +const { Bootstrap } = require('@midwayjs/bootstrap'); +Bootstrap + .configure({ + globalConfig: { + abc: 'text' } }) .run(); + +// app.getConfig('abc') => 'text' ``` -`configure` method can pass a `globalConfig` attribute, and can pass a global configuration before the application starts. The structure is consistent with the configuration of the object form to distinguish the environment. +### Modify using API -### Use API to add configuration +To modify the configuration in other scenarios, you can use the [API](./built_in_service#midwayconfigservice) provided by midway. -You can use the [API](./built_in_service#midwayconfigservice) provided by midway to modify the configuration in other scenarios. +## Environment variables and configuration -## Use environmental variables +There are some libraries in the community, such as `dotenv`, which can load `.env` files and inject them into the environment, thereby placing some keys in the environment, which can be directly relied on in Midway. -The community has some libraries, such as `dotenv`, which can load `.env` files and inject them into the environment, so as to put some keys in the environment, which can be directly used in Midway. ```bash $ npm i dotenv --save ``` -We can initialize in entry points like `bootstrap.js` or `configuration` . + +You can add a `.env` file in the project root directory, such as the following: + ``` -OSS_SECRET = 12345 -OSS_ACCESSKEY = 54321 +OSS_SECRET=12345 +OSS_ACCESSKEY=54321 ``` -We can initialize in the portal, such as `bootstrap.js` or `configuration`. + +We can initialize it in the entry, such as `bootstrap.js` or `configuration`. + ```typescript import { Configuration } from '@midwayjs/core'; import * as dotenv from 'dotenv'; @@ -551,44 +571,44 @@ import * as dotenv from 'dotenv'; dotenv.config(); @Configuration({ - //... + //... }) export class MainConfiguration { - async onReady(container) { + async onReady(container) { - } + } } ``` We can use it in the environment configuration. + ```typescript // src/config/config.default export const oss = { - accessKey: process.env.OSS_ACCESSKEY, // 54321 - secret: process.env.OSS_SECRET // 12345 + accessKey: process.env.OSS_ACCESSKEY, // 54321 + secret: process.env.OSS_SECRET // 12345 } ``` -## Common errors - +## Common mistakes -There are many possibilities that the configuration does not take effect, and the troubleshooting ideas are as follows: -- 1. Check whether `importConfigs` related files or directories are explicitly configured in the configuration file -- 2. Check whether the environment in which the application is started is consistent with the configuration file. For example, the configuration of prod will definitely not appear in local -- 3. Check whether ordinary export and method callback export are mixed, such as the following mixed use +There are many possibilities for the configuration not taking effect. The troubleshooting ideas are as follows: +- 1. Check whether the files or directories related to `importConfigs` are explicitly configured in the configuration file. +- 2. Check whether the application startup environment is consistent with the configuration file. For example, the prod configuration will definitely not appear in local. +- 3. Check whether ordinary export and method callback export are mixed use, such as the following mixed use situation -### 1. Get the value injected by @Config in the constructor (constructor) +### 1. Obtain the value injected by @Config in the constructor -**Please do not get the attribute injected by `@Config()` in the constructor**, which will make the result undefined. The reason is that the properties injected by the decorator are assigned only after the instance is created (new). In this case, use the `@Init` decorator. +**Please don’t **get the properties injected by `@Config()` in the constructor, which will make the result undefined. The reason is that the attributes injected by the decorator will not be assigned until the instance is created (new). In this case, use the `@Init` decorator. ```typescript @Provide() @@ -598,12 +618,12 @@ export class UserService { redisConfig; constructor() { - console.log(this.redisConfig); // undefined + console.log(this.redisConfig); // undefined } @Init() async initMethod() { - console.log(this.redisConfig); // has value + console.log(this.redisConfig); // has value } } @@ -611,52 +631,52 @@ export class UserService { -### 2. Mixed use of callback and export writing +### 2. Mix callback and export writing methods -**The following is the wrong usage.** +**The following is incorrect usage. ** ```typescript export default (appInfo) => { - const config = {}; + const config = {}; - // xxx - return config; + // xxx + return config; }; export const keys = '12345'; ``` -The value defined by `export const` is ignored. +Values defined with `export const` are ignored. -### 3. mix export default and export const +### 3. Mix export default and export const -**The following is the wrong usage.** +**The following is incorrect usage. ** ```typescript export default { - keys: '12345', + keys: '12345', } export const anotherKey = '54321'; ``` -The following configuration will be ignored. -### 4. export = mixed with other +Configurations located later will be ignored. -If the `export =` parameter is mixed, the value of the `export =` parameter is ignored. +### 4. Export= mixed with others + +When `export=` is mixed, if there are other configurations later, the value of `export=` will be ignored. ```typescript export = { - a: 1 + a: 1 } export const b = 2; ``` -Compiled results: +Compiled result: ```typescript export const b = 2; ``` - diff --git a/site/i18n/en/docusaurus-plugin-content-docs/current/esm.md b/site/i18n/en/docusaurus-plugin-content-docs/current/esm.md index 9c5d64e5a5b9..bc064f53a668 100644 --- a/site/i18n/en/docusaurus-plugin-content-docs/current/esm.md +++ b/site/i18n/en/docusaurus-plugin-content-docs/current/esm.md @@ -26,7 +26,7 @@ Recommended reading: Due to many changes, Midway provides a brand-new scaffolding in ESM format. If there is a need for ESM, we recommend that users re-create it before developing business. ```bash -$ npm init midway +$ npm init midway@latest -y ``` Select the scaffolding in the esm group. diff --git a/site/i18n/en/docusaurus-plugin-content-docs/current/extensions/bull.md b/site/i18n/en/docusaurus-plugin-content-docs/current/extensions/bull.md index be5ec808e754..e15aa9016a1b 100644 --- a/site/i18n/en/docusaurus-plugin-content-docs/current/extensions/bull.md +++ b/site/i18n/en/docusaurus-plugin-content-docs/current/extensions/bull.md @@ -731,6 +731,12 @@ export default { +## About Redis version + +Please choose the latest version (>=5) if possible. Currently, there is a problem of scheduled task creation failure on lower versions of redis. + + + ## Bull UI In a distributed scenario, we can leverage the Bull UI to simplify management. diff --git a/site/i18n/en/docusaurus-plugin-content-docs/current/quick_guide.md b/site/i18n/en/docusaurus-plugin-content-docs/current/quick_guide.md index 6e887686e027..a3077de41cd1 100644 --- a/site/i18n/en/docusaurus-plugin-content-docs/current/quick_guide.md +++ b/site/i18n/en/docusaurus-plugin-content-docs/current/quick_guide.md @@ -16,7 +16,7 @@ If you haven't touched Midway, it doesn't matter. In this chapter, we will build We recommend using scaffolding directly, with only a few simple instructions, you can quickly generate the project. ```bash -$ npm init midway +$ npm init midway@latest -y ``` Select `koa-v3` to initialize the project. You can customize the project name, such as `weather-sample`. diff --git a/site/i18n/en/docusaurus-plugin-content-docs/current/quickstart.md b/site/i18n/en/docusaurus-plugin-content-docs/current/quickstart.md index 921414afffc7..5b53a6b9b523 100644 --- a/site/i18n/en/docusaurus-plugin-content-docs/current/quickstart.md +++ b/site/i18n/en/docusaurus-plugin-content-docs/current/quickstart.md @@ -23,7 +23,7 @@ This chapter and subsequent documents will use the **pure Node.js project** as t Use `npm init midway` to view the complete list of scaffolds. After a project is selected, Midway automatically creates sample directories, codes, and installation dependencies. ```bash -$ npm init midway +$ npm init midway@latest -y ``` For a v3 project, select `koa-v3`, pay attention to [Node.js environment requirements](/docs/intro#environmental-preparation). diff --git a/site/i18n/en/docusaurus-theme-classic/navbar.json b/site/i18n/en/docusaurus-theme-classic/navbar.json index d9f9d1d96487..81034ddbb179 100644 --- a/site/i18n/en/docusaurus-theme-classic/navbar.json +++ b/site/i18n/en/docusaurus-theme-classic/navbar.json @@ -3,9 +3,9 @@ "message": "Midway", "description": "The title in the navbar" }, - "item.label.标准项目": { - "message": "Standard Project", - "description": "Navbar item with label 标准项目" + "item.label.使用文档": { + "message": "Document", + "description": "Navbar item with label 使用文档" }, "item.label.一体化": { "message": "Integration", diff --git a/site/lib/navbar.js b/site/lib/navbar.js index 3532a831da20..2a2e2b161f0f 100644 --- a/site/lib/navbar.js +++ b/site/lib/navbar.js @@ -2,7 +2,7 @@ module.exports = [ { "type": "doc", "docId": "intro", - "label": "标准项目", + "label": "使用文档", "position": "left" }, {