Skip to main content

如何启动后端服务

启动服务

nocobase通过yarn dev会同时启动前端服务和后端服务。

在根目录package.jsonscripts找不到我们启动服务端的命令,只看到了关键字nocobase

"scripts": {
"nocobase": "nocobase",
"pm": "nocobase pm",
"dev": "nocobase dev",
"start": "nocobase start",
...
},

通过node_modules/.bin目录下可以找到nocobase的启动文件,它是/nocobase/packages/core/cli/bin/index.js映射而来的

/nocobase/packages/core/cli/src/commands存储着各种命令的文件

Untitled

通过dev.js调用runAppCommand,在runAppCommand通过设置APP_PACKAGE_ROOT='app'

exports.isDev() = true执行exports.run('ts-node', argv)便启动了服务端代码

// 文件地址:/packages/core/cli/src/commands/dev.js
await runAppCommand('install', ['--silent']);

// 文件地址:/packages/core/cli/src/util.js
exports.runAppCommand = async (command, args = []) => {
const { APP_PACKAGE_ROOT } = process.env;

if (exports.isDev()) {
const argv = [
'-P',
'./tsconfig.server.json',
'-r',
'tsconfig-paths/register',
`./packages/${APP_PACKAGE_ROOT}/server/src/index.ts`,
command,
...args,
];
await exports.run('ts-node', argv);
}
};

进入到/packages/app/server/src/index.ts执行了两段代码

const app = new Application(config);
app.runAsCLI();

其中的config取自 /packages/app/server/src/config/database.ts

import { IDatabaseOptions } from '@nocobase/database';

export default {
logging: process.env.DB_LOGGING == 'on' ? customLogger : false,
dialect: process.env.DB_DIALECT as any,
storage: process.env.DB_STORAGE,
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
host: process.env.DB_HOST,
port: process.env.DB_PORT as any,
timezone: process.env.DB_TIMEZONE,
tablePrefix: process.env.DB_TABLE_PREFIX,
schema: process.env.DB_SCHEMA,
underscored: process.env.DB_UNDERSCORED === 'true',
} as IDatabaseOptions;

因此,在 env 的环境变量中决定了使用哪种类型的数据库。

new Applicationconstructor中,创建数据库

this._db = this.createDatabase(options);

private createDatabase(options: ApplicationOptions) {
const db = new Database();
return db;
}

在 DataBase 的类中,执行了以下功能

1、 初始化 Sequelize

/packages/core/database/src/database.ts
class Database {
constructor() {
this.sequelize = new Sequelize(this.sequelizeOptions(this.options));
}
}

runAsCLI连接数据库

await this.db.auth({ retry: 30 }); // retry 重新连接次数

在这里的this.db = this._db_idconstructor时候执行了init函数后,进行了数据库创建

this._db = this.createDatabase(options);

auth方法中测试数据库是否的连接成功

// 文件地址:/packages/core/database/src/database.ts
async auth(options) {
const authenticate = async () => {
await this.sequelize.authenticate(others);
};
return await authenticate();
}

其中sequelize的值

import { Sequelize } from 'sequelize';
this.sequelize = new Sequelize(this.sequelizeOptions(this.options));

如何用可视化工具查看数据库

1、下载navicate

2、打开sqlite连接

Untitled

3、设置datebasefile地址 /nocobase/storage/db/nocobase.sqlite

Untitled

4、完成

Untitled