|
| 1 | +import { DBMigration } from '@internal/database/migrations/types' |
| 2 | +import { ERRORS } from '@internal/errors' |
| 3 | +import { loadMigrationFiles } from 'postgres-migrations' |
| 4 | +import { getConfig } from '../../../config' |
| 5 | + |
| 6 | +const { dbMigrationFreezeAt } = getConfig() |
| 7 | + |
| 8 | +export const loadMigrationFilesCached = memoizePromise(loadMigrationFiles) |
| 9 | + |
| 10 | +export const localMigrationFiles = () => loadMigrationFiles('./migrations/tenant') |
| 11 | + |
| 12 | +export async function lastLocalMigrationName() { |
| 13 | + const migrations = await loadMigrationFilesCached('./migrations/tenant') |
| 14 | + |
| 15 | + if (!dbMigrationFreezeAt) { |
| 16 | + return migrations[migrations.length - 1].name as keyof typeof DBMigration |
| 17 | + } |
| 18 | + |
| 19 | + const migrationIndex = migrations.findIndex((m) => m.name === dbMigrationFreezeAt) |
| 20 | + if (migrationIndex === -1) { |
| 21 | + throw ERRORS.InternalError(undefined, `Migration ${dbMigrationFreezeAt} not found`) |
| 22 | + } |
| 23 | + return migrations[migrationIndex].name as keyof typeof DBMigration |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Memoizes a promise |
| 28 | + * @param func |
| 29 | + */ |
| 30 | +function memoizePromise<T, Args extends unknown[]>( |
| 31 | + func: (...args: Args) => Promise<T> |
| 32 | +): (...args: Args) => Promise<T> { |
| 33 | + const cache = new Map<string, Promise<T>>() |
| 34 | + |
| 35 | + function generateKey(args: Args): string { |
| 36 | + return args |
| 37 | + .map((arg) => { |
| 38 | + if (typeof arg === 'object' && arg !== null) { |
| 39 | + return Object.entries(arg).sort().toString() |
| 40 | + } |
| 41 | + return String(arg) |
| 42 | + }) |
| 43 | + .join('|') |
| 44 | + } |
| 45 | + |
| 46 | + return async function (...args: Args): Promise<T> { |
| 47 | + const key = generateKey(args) |
| 48 | + if (cache.has(key)) { |
| 49 | + return cache.get(key)! |
| 50 | + } |
| 51 | + |
| 52 | + const result = func(...args) |
| 53 | + cache.set(key, result) |
| 54 | + return result |
| 55 | + } |
| 56 | +} |
0 commit comments