From fa1a7037b47f2e0114d8abc5a99d29239bd3637b Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Sun, 10 Jul 2022 16:07:45 +0200 Subject: refactor: local server import/export MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Kristóf Marussy --- src/internal-server/start.ts | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) (limited to 'src/internal-server/start.ts') diff --git a/src/internal-server/start.ts b/src/internal-server/start.ts index 62311b21e..ae28e3313 100644 --- a/src/internal-server/start.ts +++ b/src/internal-server/start.ts @@ -16,36 +16,59 @@ */ import fold from '@adonisjs/fold'; -import { Ignitor } from '@adonisjs/ignitor'; -import { existsSync, readFile, statSync, chmodSync, writeFile } from 'fs-extra'; +import { Ignitor, hooks } from '@adonisjs/ignitor'; +import { readFile, stat, chmod, writeFile } from 'fs-extra'; import { join } from 'path'; import { LOCAL_HOSTNAME } from '../config'; import { isWindows } from '../environment'; process.env.ENV_PATH = join(__dirname, 'env.ini'); -export const server = async (userPath: string, port: number) => { - const dbPath = join(userPath, 'server.sqlite'); - const dbTemplatePath = join(__dirname, 'database', 'template.sqlite'); - - if (!existsSync(dbPath)) { +async function ensureDB(dbPath: string): Promise { + try { + await stat(dbPath); + } catch { + // Database does not exist. // Manually copy file // We can't use copyFile here as it will cause the file to be readonly on Windows + const dbTemplatePath = join(__dirname, 'database', 'template.sqlite'); const dbTemplate = await readFile(dbTemplatePath); await writeFile(dbPath, dbTemplate); // Change permissions to ensure to file is not read-only if (isWindows) { + const stats = await stat(dbPath); // eslint-disable-next-line no-bitwise - chmodSync(dbPath, statSync(dbPath).mode | 146); + await chmod(dbPath, stats.mode | 146); } } +} + +export const server = async (userPath: string, port: number, token: string) => { + const dbPath = join(userPath, 'server.sqlite'); + await ensureDB(dbPath); // Note: These env vars are used by adonis as env vars process.env.DB_PATH = dbPath; process.env.USER_PATH = userPath; process.env.HOST = LOCAL_HOSTNAME; process.env.PORT = port.toString(); + process.env.FERDIUM_LOCAL_TOKEN = token; - new Ignitor(fold).appRoot(__dirname).fireHttpServer().catch(console.error); + return new Promise((resolve, reject) => { + let returned = false; + hooks.after.httpServer(() => { + if (!returned) { + resolve(); + returned = true; + } + }); + new Ignitor(fold).appRoot(__dirname).fireHttpServer().catch((error) => { + console.error(error); + if (!returned) { + returned = true; + reject(error); + } + }); + }); }; -- cgit v1.2.3-54-g00ecf