aboutsummaryrefslogtreecommitdiffstats
path: root/src/internal-server/start.ts
blob: c88a61feca1917d905dd45339c4b44b3373842f8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
|--------------------------------------------------------------------------
| Http server
|--------------------------------------------------------------------------
|
| This file bootstraps Adonisjs to start the HTTP server. You are free to
| customize the process of booting the http server.
|
| """ Loading ace commands """
|     At times you may want to load ace commands when starting the HTTP server.
|     Same can be done by chaining `loadCommands()` method after
|
| """ Preloading files """
|     Also you can preload files by calling `preLoad('path/to/file')` method.
|     Make sure to pass a relative path from the project root.
*/

import { join } from 'node:path';
import fold from '@adonisjs/fold';
import { Ignitor, hooks } from '@adonisjs/ignitor';
import { chmod, readFile, stat, writeFile } from 'fs-extra';
import { LOCAL_HOSTNAME } from '../config';
import { isWindows } from '../environment';

process.env.ENV_PATH = join(__dirname, 'env.ini');

async function ensureDB(dbPath: string): Promise<void> {
  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
      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;

  return new Promise<void>((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);
        }
      });
  });
};