postgres-initializer.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import path from 'path';
  2. import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';
  3. import { TestDbInitializer } from './test-db-initializer';
  4. export class PostgresInitializer implements TestDbInitializer<PostgresConnectionOptions> {
  5. private client: import('pg').Client;
  6. async init(
  7. testFileName: string,
  8. connectionOptions: PostgresConnectionOptions,
  9. ): Promise<PostgresConnectionOptions> {
  10. const dbName = this.getDbNameFromFilename(testFileName);
  11. (connectionOptions as any).database = dbName;
  12. (connectionOptions as any).synchronize = true;
  13. this.client = await this.getPostgresConnection(connectionOptions);
  14. await this.client.query(`DROP DATABASE IF EXISTS ${dbName}`);
  15. await this.client.query(`CREATE DATABASE ${dbName}`);
  16. return connectionOptions;
  17. }
  18. async populate(populateFn: () => Promise<void>): Promise<void> {
  19. await populateFn();
  20. }
  21. destroy(): void | Promise<void> {
  22. return this.client.end();
  23. }
  24. private async getPostgresConnection(
  25. connectionOptions: PostgresConnectionOptions,
  26. ): Promise<import('pg').Client> {
  27. // eslint-disable-next-line @typescript-eslint/no-var-requires
  28. const { Client } = require('pg');
  29. const client = new Client({
  30. host: connectionOptions.host,
  31. port: connectionOptions.port,
  32. user: connectionOptions.username,
  33. password: connectionOptions.password,
  34. database: 'postgres',
  35. });
  36. await client.connect();
  37. return client;
  38. }
  39. private getDbNameFromFilename(filename: string): string {
  40. return 'e2e_' + path.basename(filename).replace(/[^a-z0-9_]/gi, '_');
  41. }
  42. }