sqljs-initializer.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import fs from 'fs';
  2. import path from 'path';
  3. import { SqljsConnectionOptions } from 'typeorm/driver/sqljs/SqljsConnectionOptions';
  4. import { Mutable } from '../types';
  5. import { TestDbInitializer } from './test-db-initializer';
  6. export class SqljsInitializer implements TestDbInitializer<SqljsConnectionOptions> {
  7. private dbFilePath: string;
  8. private connectionOptions: SqljsConnectionOptions;
  9. /**
  10. * @param dataDir
  11. * @param postPopulateTimeoutMs Allows you to specify a timeout to wait after the population
  12. * step and before the server is shut down. Can resolve occasional race condition issues with
  13. * the job queue.
  14. */
  15. constructor(private dataDir: string, private postPopulateTimeoutMs: number = 0) {}
  16. async init(
  17. testFileName: string,
  18. connectionOptions: SqljsConnectionOptions,
  19. ): Promise<SqljsConnectionOptions> {
  20. this.dbFilePath = this.getDbFilePath(testFileName);
  21. this.connectionOptions = connectionOptions;
  22. (connectionOptions as Mutable<SqljsConnectionOptions>).location = this.dbFilePath;
  23. return connectionOptions;
  24. }
  25. async populate(populateFn: () => Promise<void>): Promise<void> {
  26. if (!fs.existsSync(this.dbFilePath)) {
  27. const dirName = path.dirname(this.dbFilePath);
  28. if (!fs.existsSync(dirName)) {
  29. fs.mkdirSync(dirName);
  30. }
  31. (this.connectionOptions as Mutable<SqljsConnectionOptions>).autoSave = true;
  32. (this.connectionOptions as Mutable<SqljsConnectionOptions>).synchronize = true;
  33. await populateFn();
  34. await new Promise(resolve => setTimeout(resolve, this.postPopulateTimeoutMs));
  35. (this.connectionOptions as Mutable<SqljsConnectionOptions>).autoSave = false;
  36. (this.connectionOptions as Mutable<SqljsConnectionOptions>).synchronize = false;
  37. }
  38. }
  39. destroy(): void | Promise<void> {
  40. return undefined;
  41. }
  42. private getDbFilePath(testFileName: string) {
  43. // tslint:disable-next-line:no-non-null-assertion
  44. const dbFileName = path.basename(testFileName) + '.sqlite';
  45. const dbFilePath = path.join(this.dataDir, dbFileName);
  46. return dbFilePath;
  47. }
  48. }