Skip to content

Commit

Permalink
feat: add dynamic postgres adapter selection
Browse files Browse the repository at this point in the history
  • Loading branch information
maneike committed Nov 7, 2024
1 parent c16405c commit 93f7ef4
Showing 1 changed file with 24 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,39 @@ export const preparePayloadConfig = async (configPath: PathLike) => {
// Read the payload.config.ts file
let data = await fs.readFile(configPath, 'utf8');

// Replace postgresAdapter with vercelPostgresAdapter
const oldImport = `import { postgresAdapter } from '@payloadcms/db-postgres'`;
const newImport = `import { vercelPostgresAdapter as postgresAdapter } from '@payloadcms/db-vercel-postgres'`;
const postgresAdapterImport = `import { postgresAdapter } from '@payloadcms/db-postgres'`;
const vercelPostgresAdapterImport = `import { vercelPostgresAdapter } from '@payloadcms/db-vercel-postgres'`;

data = data.replace(oldImport, newImport);
// Add the vercelPostgresAdapter import after postgresAdapter if it's not already present
if (!data.includes(vercelPostgresAdapterImport)) {
data = data.replace(postgresAdapterImport, `${postgresAdapterImport}\n${vercelPostgresAdapterImport}`);
} else {
console.log('vercelPostgresAdapter import is already present.');
}

// Update the db configuration
const dbConfig = `db: postgresAdapter({
schemaName: "payload",
pool: {
connectionString: process.env.POSTGRES_URL || process.env.DATABASE_URI || "",
},
})`;
// Step 2: Replace the db configuration with conditional configuration
const newDbConfig = `db: process.env.POSTGRES_URL
? vercelPostgresAdapter({
schemaName: "payload",
pool: {
connectionString: process.env.POSTGRES_URL || "",
},
})
: postgresAdapter({
schemaName: "payload",
pool: {
connectionString: process.env.DATABASE_URI || "",
},
})`;

data = data.replace(
/db:\s*postgresAdapter\(\{[\s\S]*?pool:\s*\{[\s\S]*?connectionString:[\s\S]*?\}[\s\S]*?\}\)/m,
dbConfig,
newDbConfig,
);

// Write the updated payload.config.ts back to the file
await fs.writeFile(configPath, data);
} catch (err) {
console.error('Error during processing payload.config.ts', err);
console.error('Error during processing payload.config.ts:', err);
}
};

0 comments on commit 93f7ef4

Please sign in to comment.