cube.js playground暴露的几个不错的功能
通过源码我们查看playground 提供的功能就会看到自己很不错的直接可以拿来使用的工具
主要代码在packages/cubejs-server-core/src/core/DevServer.ts
获取数据库schema 信息
代码如下,属于一个内部方法,可以基于driver获取数据库的schema
app.get('/playground/db-schema', catchErrors(async (req, res) => {
this.cubejsServer.event('Dev Server DB Schema Load');
const driver = await this.cubejsServer.getDriver({
dataSource: req.body.dataSource || 'default',
authInfo: null,
securityContext: null,
requestId: getRequestIdFromRequest(req),
});
const tablesSchema = await driver.tablesSchema();
this.cubejsServer.event('Dev Server DB Schema Load Success');
if (Object.keys(tablesSchema || {}).length === 0) {
this.cubejsServer.event('Dev Server DB Schema Load Empty');
}
res.json({ tablesSchema });
}));
当然我们也可以自己编写,代码不难
获取定义的schema
核心是利用了FileRepository的能力,我们可以自己扩展(基于s3的。。。。)
app.get('/playground/files', catchErrors(async (req, res) => {
this.cubejsServer.event('Dev Server Files Load');
const files = await this.cubejsServer.repository.dataSchemaFiles();
res.json({
files: files.map(f => ({
absPath: path.resolve(path.join(this.cubejsServer.repository.localPath(), f.fileName))
}))
});
}));
schema 生成
此处利用了schema-compiler 包内部的工具,当然我们也可以利用此工具包,进行schema 的生成
app.post('/playground/generate-schema', catchErrors(async (req, res) => {
this.cubejsServer.event('Dev Server Generate Schema');
if (!req.body) {
throw new Error('Your express app config is missing body-parser middleware. Typical config can look like: `app.use(bodyParser.json({ limit: \'50mb\' }));`');
}
if (!req.body.tables) {
throw new Error('You have to select at least one table');
}
const driver = await this.cubejsServer.getDriver({
dataSource: req.body.dataSource || 'default',
authInfo: null,
securityContext: null,
requestId: getRequestIdFromRequest(req),
});
const tablesSchema = req.body.tablesSchema || (await driver.tablesSchema());
const ScaffoldingTemplate = require('@cubejs-backend/schema-compiler/scaffolding/ScaffoldingTemplate');
const scaffoldingTemplate = new ScaffoldingTemplate(tablesSchema, driver);
const files = scaffoldingTemplate.generateFilesByTableNames(req.body.tables);
const schemaPath = options.schemaPath || 'schema';
await Promise.all(files.map(file => fs.writeFile(path.join(schemaPath, file.fileName), file.content)));
res.json({ files });
}));
参考资料
https://github.com/cube-js/cube.js/blob/master/packages/cubejs-server-core/src/core/DevServer.ts
https://cube.dev/docs/@cubejs-backend-server
https://cube.dev/docs/@cubejs-backend-server-core
https://cube.dev/docs/config