Doc: command (#869)

* docs: add command dev doc

* feat: update doc

Co-authored-by: chenos <chenlinxh@gmail.com>
This commit is contained in:
Junyi 2022-10-01 22:18:26 +08:00 committed by GitHub
parent 2efa704b3b
commit fceebaf50e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 252 additions and 1 deletions

View File

@ -72,6 +72,7 @@ export default {
},
'/development/guide/ui-router',
'/development/guide/settings-center',
'/development/guide/commands',
],
},
{

View File

@ -1 +1,98 @@
# Commands
# 命令行
## 简介
NocoBase Server Application 除了用作 WEB 服务器以外,也是个强大可扩展的 CLI 工具。
新建一个 `app.js` 文件,代码如下:
```ts
const Application = require('@nocobase/server');
// 此处省略具体配置
const app = new Application({/*...*/});
app.runAsCLI();
```
`runAsCLI()` 方式运行的 app.js 是一个 CLI在命令行工具就可以像这样操作了
```bash
node app.js install # 安装
node app.js start # 启动
```
为了更好的开发、构建和部署 NocoBase 应用NocoBase 内置了许多命令,详情查看 [NocoBase CLI](/api/cli) 章节。
## 自定义 Command
NocoBase CLI 的设计思想与 [Laravel Artisan](https://laravel.com/docs/9.x/artisan) 非常相似都是可扩展的。NocoBase CLI 基于 [commander](https://www.npmjs.com/package/commander) 实现,可以这样扩展 Command
```ts
app
.command('echo')
.option('-v, --version');
.action(async ([options]) => {
console.log('Hello World!');
if (options.version) {
console.log('Current version:', app.getVersion());
}
});
```
这个方法定义了以下命令:
```bash
yarn nocobase echo
# Hello World!
yarn nocobase echo -v
# Hello World!
# Current version: 0.7.4-alpha.7
```
更多 API 细节可参考 [Application.command()](/api/server/application#command) 部分。
## 示例
### 定义导出数据表的命令
如果我们希望把应用的数据表中的数据导出成 JSON 文件,可以定义一个如下的子命令:
```ts
import path from 'path';
import * as fs from 'fs/promises';
class MyPlugin extends Plugin {
load() {
this.app
.command('export')
.option('-o, --output-dir')
.action(async (options, ...collections) => {
const { outputDir = path.join(process.env.PWD, 'storage') } = options;
await collections.reduce((promise, collection) => promise.then(async () => {
if (!this.db.hasCollection(collection)) {
console.warn('No such collection:', collection);
return;
}
const repo = this.db.getRepository(collection);
const data = repo.find();
await fs.writeFile(path.join(outputDir, `${collection}.json`), JSON.stringify(data), { mode: 0o644 });
}), Promise.resolve());
});
}
}
```
注册和激活插件之后在命令行调用:
```bash
mkdir -p ./storage/backups
yarn nocobase export -o ./storage/backups users
```
执行后会生成 `./storage/backups/users.json` 文件包含数据表中的数据。
## 小结
本章所涉及示例代码整合在 [packages/samples/command](https://github.com/nocobase/nocobase/tree/main/packages/samples/command) 包中,可以直接在本地运行,查看效果。

View File

@ -0,0 +1,20 @@
# Command sample
## Register
```ts
yarn pm add sample-command
```
## Activate
```bash
yarn pm enable sample-command
```
## Try command
```bash
mkdir -p ./storage/backups
yarn nocobase export -o ./storage/backups users
```

4
packages/samples/command/client.d.ts vendored Executable file
View File

@ -0,0 +1,4 @@
// @ts-nocheck
export * from './lib/client';
export { default } from './lib/client';

View File

@ -0,0 +1,30 @@
"use strict";
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _index = _interopRequireWildcard(require("./lib/client"));
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {};
Object.defineProperty(exports, "default", {
enumerable: true,
get: function get() {
return _index.default;
}
});
Object.keys(_index).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _index[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _index[key];
}
});
});

View File

@ -0,0 +1,16 @@
{
"name": "@nocobase/plugin-sample-command",
"version": "0.7.4-alpha.7",
"main": "lib/server/index.js",
"dependencies": {},
"devDependencies": {
"@nocobase/client": "0.7.4-alpha.7",
"@nocobase/server": "0.7.4-alpha.7",
"@nocobase/test": "0.7.4-alpha.7"
},
"peerDependencies": {
"@nocobase/client": "*",
"@nocobase/server": "*",
"@nocobase/test": "*"
}
}

4
packages/samples/command/server.d.ts vendored Executable file
View File

@ -0,0 +1,4 @@
// @ts-nocheck
export * from './lib/server';
export { default } from './lib/server';

View File

@ -0,0 +1,30 @@
"use strict";
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _index = _interopRequireWildcard(require("./lib/server"));
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {};
Object.defineProperty(exports, "default", {
enumerable: true,
get: function get() {
return _index.default;
}
});
Object.keys(_index).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _index[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _index[key];
}
});
});

View File

@ -0,0 +1,5 @@
import React from 'react';
export default React.memo((props) => {
return <>{props.children}</>;
});

View File

@ -0,0 +1 @@
export { default } from './server';

View File

@ -0,0 +1,43 @@
import path from 'path';
import * as fs from 'fs/promises';
import { InstallOptions, Plugin } from '@nocobase/server';
export class CommandPlugin extends Plugin {
getName(): string {
return this.getPackageName(__dirname);
}
beforeLoad() {
// TODO
}
async load() {
this.app
.command('export')
.option('-o, --output-dir')
.action(async (options, ...collections) => {
const { outputDir = path.join(process.env.PWD, 'storage') } = options;
await collections.reduce((promise, collection) => promise.then(async () => {
if (!this.db.hasCollection(collection)) {
console.warn('No such collection:', collection);
return;
}
const repo = this.db.getRepository(collection);
const data = repo.find();
await fs.writeFile(path.join(outputDir, `${collection}.json`), JSON.stringify(data), { mode: 0o644 });
}), Promise.resolve());
});
}
async disable() {
// this.app.resourcer.removeResource('testHello');
}
async install(options: InstallOptions) {
// TODO
}
}
export default CommandPlugin;