postgres-initializer.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. const { Client } = require('pg');
  28. const client = new Client({
  29. host: connectionOptions.host,
  30. port: connectionOptions.port,
  31. user: connectionOptions.username,
  32. password: connectionOptions.password,
  33. database: 'postgres',
  34. });
  35. await client.connect();
  36. return client;
  37. }
  38. private getDbNameFromFilename(filename: string): string {
  39. return 'e2e_' + path.basename(filename).replace(/[^a-z0-9_]/gi, '_');
  40. }
  41. }