File size: 1,626 Bytes
7f0d072
 
 
 
2e6d0d7
7f0d072
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e6d0d7
 
7f0d072
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use strict';

const { getWrappedDb } = require('./index');
const { migrate } = require('./migrate');
const argon2 = require('argon2');
const { SETTING_DEFS } = require('../config/setting-defs');

async function seedSettings({ database = getWrappedDb(), runMigrate = true } = {}) {
  if (runMigrate) migrate();
  const db = database;

  const row = db.prepare('SELECT COUNT(*) as rowCount FROM settings').get();
  if (row.rowCount > 0) {
    console.log('[Settings] Already seeded, skipping.');
    return 0;
  }

  const now = new Date().toISOString();
  const upsert = db.prepare(
    `INSERT INTO settings (key, value, description, updated_at) VALUES (?, ?, ?, ?)
     ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`
  );

  let count = 0;
  for (const def of SETTING_DEFS) {
    const val = process.env[def.key];
    if (val !== undefined) {
      const stored = def.key === 'ADMIN_KEY' ? await argon2.hash(val) : val;
      upsert.run(def.key, stored, def.description, now);
      count++;
    } else {
      upsert.run(def.key, '', def.description, now);
      count++;
    }
  }

  return logResult(count);
}

function logResult(count) {
  console.log(`[Seed] Seeded ${count} settings from environment.`);
  return count;
}

/* v8 ignore next 8 */
if (require.main === module) {
  const { loadEnv } = require('../config/load-env');
  loadEnv();
  seedSettings({ runMigrate: false }).then(() => process.exit(0)).catch((error) => {
    console.error('[Seed] Settings seeding failed:', error.message);
    process.exit(1);
  });
}

module.exports = { seedSettings, SETTING_DEFS };