budibase/packages/cli/src/commands/init/initHandler.js

80 lines
2.2 KiB
JavaScript

const inquirer = require("inquirer");
const { mkdir, exists, copy } = require("fs-extra");
const chalk = require("chalk");
const { serverFileName, getAppContext } = require("../../common");
const passwordQuestion = require("@inquirer/password");
const createMasterDb = require("@budibase/server/initialise/createMasterDb");
var localDatastore = require("@budibase/datastores/datastores/local");
module.exports = (opts) => {
run(opts);
}
const run = async (opts) => {
opts.datapath = "./.data";
await prompts(opts);
await createDataFolder(opts);
await createDevConfig(opts);
await initialiseDatabase(opts);
}
const prompts = async (opts) => {
const questions = [
{
type: "input",
name: "username",
message: "Username for Admin: ",
validate: function(value) {
return !!value || "Please enter a username"
}
}
]
const answers = await inquirer.prompt(questions);
const password = await passwordQuestion({
message: "Password for Admin: ", mask: "*"
});
const passwordConfirm = await passwordQuestion({
message: "Confirm Password: ", mask: "*"
});
if(password !== passwordConfirm)
throw new Exception("Passwords do not match!");
opts.username = answers.username;
opts.password = password;
}
const createDataFolder = async (opts) => {
if(await exists(opts.datapath)) {
const err = `The path ${opts.datapath} already exists - has budibase already been initialised? Remove the directory to try again.`;
throw new Error(err);
}
await mkdir(opts.datapath);
}
const createDevConfig = async (opts) => {
if(await exists("config.js")) {
console.log(chalk.yellow("Config file already exists (config.js) - keeping your existing config"));
} else {
const srcConfig = serverFileName("config.dev.js");
const destFile = "./config.js";
await copy(srcConfig, destFile);
}
}
const initialiseDatabase = async (opts) => {
const appContext = await getAppContext({masterIsCreated:false});
await createMasterDb(
appContext,
localDatastore,
opts.username,
opts.password);
}