index.ts 2.2 KB

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