index.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { createDBConnection } from '@dzlzv/hydra-processor/lib/db'
  2. import { DatabaseManager, makeDatabaseManager } from '@dzlzv/hydra-db-utils'
  3. import { Connection, getManager, FindConditions } from 'typeorm'
  4. import { bootMembers, IBootstrapMember } from './members'
  5. import { bootWorkers, IBootstrapWorker, IBootstrapWorkers } from './workers'
  6. import { Worker, WorkerType } from 'query-node'
  7. import fs from 'fs'
  8. import path from 'path'
  9. // run bootstrap
  10. init()
  11. // bootstrap flow
  12. async function init() {
  13. // prepare database and import data
  14. const [databaseManager, connection] = await createDatabaseManager()
  15. // escape if db is already initialized
  16. if (await isDbInitialized(databaseManager)) {
  17. await connection.close()
  18. return
  19. }
  20. // load import data
  21. const data = loadData()
  22. // bootstrap entities
  23. await bootMembers(databaseManager, data.members)
  24. await bootWorkers(databaseManager, data.workers)
  25. await connection.close()
  26. }
  27. async function isDbInitialized(db: DatabaseManager): Promise<boolean> {
  28. // simple way to check if db is bootstrapped already - check if there is at least 1 storage provider
  29. const membership = await db.get(Worker, {
  30. where: {
  31. type: WorkerType.STORAGE,
  32. } as FindConditions<Worker>,
  33. })
  34. return !!membership
  35. }
  36. async function createDatabaseManager(): Promise<[DatabaseManager, Connection]> {
  37. // paths in `entities` should be the same as `entities` set in `manifest.yml`
  38. const entities = ['generated/graphql-server/dist/**/*.model.js']
  39. // connect to db and create manager
  40. const connection = await createDBConnection(entities)
  41. const entityManager = getManager(connection.name)
  42. const databaseManager = makeDatabaseManager(entityManager)
  43. return [databaseManager, connection]
  44. }
  45. interface IBootstrapData {
  46. members: IBootstrapMember[]
  47. workers: IBootstrapWorkers
  48. }
  49. function loadData(): IBootstrapData {
  50. return {
  51. members: JSON.parse(fs.readFileSync(process.env.BOOTSTRAP_DATA_FOLDER + '/members.json').toString()),
  52. workers: JSON.parse(fs.readFileSync(process.env.BOOTSTRAP_DATA_FOLDER + '/workers.json').toString()),
  53. }
  54. }