hydro cli

This commit is contained in:
undefined committed 2020-07-23 18:08:45 +08:00
1 parent 9e96c471af
commit 81868cafbb
11 files changed
+243 -160

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
/* eslint-disable no-eval */
/* eslint-disable no-await-in-loop */
/* eslint-disable import/no-dynamic-require */
import { argv } from 'yargs';
import {
lib, service, model, script,
builtinLib, builtinScript, builtinModel,
} from './common';
const COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
const ARR = /=>.*$/mg;
function parseParameters(fn: Function) {
const code = fn.toString()
.replace(COMMENTS, '')
.replace(ARR, '');
const result = code.slice(code.indexOf('(') + 1, code.indexOf(')'))
.match(/([^,]+)/g).map((i) => i.trim());
return result === null ? [] : result;
}
async function cli() {
const [, modelName, func, ...args] = argv._;
if (!global.Hydro.model[modelName]) {
return console.error(`Model ${modelName} doesn't exist.`);
}
if (!global.Hydro.model[modelName][func]) {
return console.error(`Function ${func} doesn't exist in model ${modelName}.`);
}
if (typeof global.Hydro.model[modelName][func] !== 'function') {
return console.error(`${func} in model ${modelName} is not a function.`);
}
const parameterMin = global.Hydro.model[modelName][func].length;
const parameters = parseParameters(global.Hydro.model[modelName][func]);
const parameterMax = parameters.length;
if (args.length > parameterMax) {
console.error(`Too many arguments. Max ${parameterMax}`);
return console.error(parameters.join(', '));
}
if (args.length < parameterMin) {
console.error(`Too few arguments. Min ${parameterMin}`);
return console.error(parameters.join(', '));
}
let result = global.Hydro.model[modelName][func](...args);
if (result instanceof Promise) result = await result;
return console.log(result);
}
export async function load(call, args) {
let pending = args;
const fail = [];
const active = [];
require('../lib/i18n');
require('../utils');
require('../error');
require('../options');
const bus = require('../service/bus');
await new Promise((resolve) => {
const h = () => {
bus.unsubscribe(['system_database_connected'], h);
resolve();
};
bus.subscribe(['system_database_connected'], h);
require('../service/db');
});
for (const i of builtinLib) require(`../lib/${i}`);
await lib(pending, fail);
require('../service/gridfs');
await service(pending, fail);
for (const i of builtinModel) require(`../model/${i}`);
await model(pending, fail);
for (const i in global.Hydro.service) {
if (global.Hydro.service[i].postInit) {
try {
await global.Hydro.service[i].postInit();
} catch (e) {
console.error(e);
}
}
}
for (const i of builtinScript) require(`../script/${i}`);
await script(pending, fail, active);
for (const postInit of global.Hydro.postInit) {
await postInit();
}
pending = [];
await cli();
return { active, fail };
}
+1 -2
View File
@@ -21,12 +21,11 @@ export async function load(call) {
bus.subscribe(['system_database_connected'], h);
require('../service/db');
});
require('../service/monitor');
for (const i of builtinModel) require(`../model/${i}`);
const modelSystem = require('../model/system');
const dbVer = await modelSystem.get('db.ver');
if (dbVer !== 1) {
const ins = require('../script/install');
const ins = require('../script/upgrade0_1');
await ins.run({ username: 'Root', password: 'rootroot' });
}
for (const i in global.Hydro.service) {
+69 -63
View File
@@ -2,12 +2,14 @@ import os from 'os';
import path from 'path';
import http from 'http';
import fs from 'fs-extra';
import Koa from 'koa';
import Koa, { Context } from 'koa';
import Body from 'koa-body';
import Router from 'koa-router';
import cache from 'koa-static-cache';
import nunjucks from 'nunjucks';
import mongodb from 'mongodb';
import { argv } from 'yargs';
const listenPort = argv.port || 8888;
class Loader {
getSource(name: string) { // eslint-disable-line class-methods-use-this
@@ -83,7 +85,7 @@ class Loader {
const env = new nunjucks.Environment(new Loader(), { autoescape: true, trimBlocks: true });
function render(name) {
function render(name: string) {
return new Promise((resolve, reject) => {
env.render(name, {
_: (str: string) => str,
@@ -94,70 +96,74 @@ function render(name) {
});
}
async function get(ctx: Context) {
ctx.body = await render('setup.html');
ctx.response.type = 'text/html';
}
async function post(ctx: Context) {
const {
host, port, name, username, password,
} = ctx.request.body;
let mongourl = 'mongodb://';
if (username) mongourl += `${username}:${password}@`;
mongourl += `${host}:${port}/${name}`;
try {
const Database = await mongodb.MongoClient.connect(mongourl, {
useNewUrlParser: true, useUnifiedTopology: true,
});
const db = Database.db(name);
await Promise.all([
db.collection('system').updateOne(
{ _id: 'server.host' },
{ $set: { value: ctx.request.host } },
{ upsert: true },
),
db.collection('system').updateOne(
{ _id: 'server.hostname' },
{ $set: { value: ctx.request.hostname } },
{ upsert: true },
),
db.collection('system').updateOne(
{ _id: 'server.url' },
{ $set: { value: ctx.request.href } },
{ upsert: true },
),
db.collection('system').updateOne(
{ _id: 'server.port' },
{ $set: { value: parseInt(listenPort as string, 10) } },
{ upsert: true },
),
]);
fs.ensureDirSync(path.resolve(os.homedir(), '.hydro'));
fs.writeFileSync(path.resolve(os.homedir(), '.hydro', 'config.json'), JSON.stringify({
host, port, name, username, password,
}));
ctx.body = `<h1>This page will reload in 3 secs.</h1>
<script>
setTimeout(function (){
window.location.href = '/';
}, 3000);
</script>`;
setTimeout(() => process.exit(0), 500);
} catch (e) {
ctx.body = `Error connecting to database: ${e.message}\n${e.stack}`;
}
}
export function load() {
const app = new Koa();
const server = http.createServer(app.callback());
const router = new Router();
app.keys = ['Hydro'];
app.use(cache(path.join(os.tmpdir(), 'hydro', 'public'), {
maxAge: 365 * 24 * 60 * 60,
}));
app.use(Body());
router.get('/', async (ctx) => {
ctx.body = await render('setup.html');
ctx.response.type = 'text/html';
});
const listenPort = global.argv.port || 8888;
router.post('/', async (ctx) => {
const {
host, port, name, username, password,
} = ctx.request.body;
let mongourl = 'mongodb://';
if (username) mongourl += `${username}:${password}@`;
mongourl += `${host}:${port}/${name}`;
try {
const Database = await mongodb.MongoClient.connect(mongourl, {
useNewUrlParser: true, useUnifiedTopology: true,
});
const db = Database.db(name);
await Promise.all([
db.collection('system').updateOne(
{ _id: 'server.host' },
{ $set: { value: ctx.request.host } },
{ upsert: true },
),
db.collection('system').updateOne(
{ _id: 'server.hostname' },
{ $set: { value: ctx.request.hostname } },
{ upsert: true },
),
db.collection('system').updateOne(
{ _id: 'server.url' },
{ $set: { value: ctx.request.href } },
{ upsert: true },
),
db.collection('system').updateOne(
{ _id: 'server.port' },
{ $set: { value: parseInt(listenPort, 10) } },
{ upsert: true },
),
]);
fs.ensureDirSync(path.resolve(os.homedir(), '.hydro'));
fs.writeFileSync(path.resolve(os.homedir(), '.hydro', 'config.json'), JSON.stringify({
host, port, name, username, password,
}));
ctx.body = `<h1>This page will reload in 3 secs.</h1>
<script>
setTimeout(function (){
window.location.href = '/';
}, 3000);
</script>`;
setTimeout(() => process.exit(0), 500);
} catch (e) {
ctx.body = `Error connecting to database: ${e.message}\n${e.stack}`;
}
});
app.use(router.routes()).use(router.allowedMethods());
app
.use(cache(path.join(os.tmpdir(), 'hydro', 'public'), {
maxAge: 365 * 24 * 60 * 60,
}))
.use(Body())
.use((ctx) => {
if (ctx.request.method.toLowerCase() === 'post') return post(ctx);
return get(ctx);
});
server.listen(listenPort);
console.log('Server listening at:', listenPort);
}