Skip to content

Commit

Permalink
chore: readme gen, vercel deploy link gen, db env name swaps
Browse files Browse the repository at this point in the history
  • Loading branch information
denolfe committed Jun 3, 2024
1 parent 3bdaa6d commit edc9239
Show file tree
Hide file tree
Showing 14 changed files with 1,079 additions and 138 deletions.
12 changes: 7 additions & 5 deletions packages/create-payload-app/src/lib/configure-payload-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import { dbReplacements, storageReplacements } from './replacements.js'
/** Update payload config with necessary imports and adapters */
export async function configurePayloadConfig(args: {
dbType?: DbType
envNames?: {
dbUri: string
}
packageJsonName?: string
projectDirOrConfigPath: { payloadConfigPath: string } | { projectDir: string }
storageAdapter?: StorageAdapterType
Expand Down Expand Up @@ -116,15 +119,14 @@ export async function configurePayloadConfig(args: {
if (dbConfigEndLineIndex) dbConfigEndLineIndex += 1
}

if (!dbConfigStartLineIndex || !dbConfigEndLineIndex) {
warning('Unable to update payload.config.ts with database adapter import')
} else {
// Replaces lines between `// database-adapter-config-start` and `// database-adapter-config-end`
if (dbConfigStartLineIndex && dbConfigEndLineIndex) {
configLines.splice(
dbConfigStartLineIndex,
dbConfigEndLineIndex - dbConfigStartLineIndex + 1,
...dbReplacement.configReplacement,
...dbReplacement.configReplacement(args.envNames?.dbUri),
)
} else {
warning('Unable to update payload.config.ts with database adapter import')
}

fse.writeFileSync(payloadConfigPath, configLines.join('\n'))
Expand Down
2 changes: 1 addition & 1 deletion packages/create-payload-app/src/lib/create-project.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ describe('createProject', () => {

expect(content).not.toContain('// database-adapter-config-start')
expect(content).not.toContain('// database-adapter-config-end')
expect(content).toContain(dbReplacement.configReplacement.join('\n'))
expect(content).toContain(dbReplacement.configReplacement().join('\n'))
})
})
})
Expand Down
10 changes: 5 additions & 5 deletions packages/create-payload-app/src/lib/replacements.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
import type { DbType, StorageAdapterType } from '../types.js'

type DbAdapterReplacement = {
configReplacement: string[]
configReplacement: (envName?: string) => string[]
importReplacement: string
packageName: string
}

const mongodbReplacement: DbAdapterReplacement = {
// Replacement between `// database-adapter-config-start` and `// database-adapter-config-end`
configReplacement: [
configReplacement: (envName = 'DATABASE_URI') => [
' db: mongooseAdapter({',
" url: process.env.DATABASE_URI || '',",
` url: process.env.${envName} || '',`,
' }),',
],
importReplacement: "import { mongooseAdapter } from '@payloadcms/db-mongodb'",
packageName: '@payloadcms/db-mongodb',
}

const postgresReplacement: DbAdapterReplacement = {
configReplacement: [
configReplacement: (envName = 'DATABASE_URI') => [
' db: postgresAdapter({',
' pool: {',
" connectionString: process.env.DATABASE_URI || '',",
` connectionString: process.env.${envName} || '',`,
' },',
' }),',
],
Expand Down
111 changes: 106 additions & 5 deletions scripts/generate-template-variations.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
/**
* This script generates variations of the templates into the `templates` directory.
*
* How to use:
*
* pnpm run script:gen-templates
*
* NOTE: You will likely have to commit by using the `--no-verify` flag to avoid the repo linting
* There is no way currently to have lint-staged ignore the templates directory.
*/

import type { DbType, StorageAdapterType } from 'packages/create-payload-app/src/types.js'

import { configurePayloadConfig } from 'create-payload-app/lib/configure-payload-config.js'
import { copyRecursiveSync } from 'create-payload-app/utils/copy-recursive-sync.js'
import * as fs from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import path from 'path'

Expand All @@ -15,8 +27,17 @@ type TemplateVariations = {
dirname: string
db: DbType
storage: StorageAdapterType
vercelDeployButtonLink?: string
envNames?: {
dbUri: string
}
}

main().catch((error) => {
console.error(error)
process.exit(1)
})

async function main() {
const templatesDir = path.resolve(dirname, '../templates')

Expand All @@ -26,12 +47,38 @@ async function main() {
dirname: 'with-vercel-postgres',
db: 'postgres',
storage: 'vercelBlobStorage',
vercelDeployButtonLink:
`https://vercel.com/new/clone?repository-url=` +
encodeURI(
'https://github.com/payloadcms/vercel-deploy-payload-postgres' +
'&project-name=payload-project' +
'&env=PAYLOAD_SECRET' +
'&build-command=pnpm run ci' +
'&stores=[{"type":"postgres"},{"type":"blob"}]', // Postgres and Vercel Blob Storage
),
envNames: {
// This will replace the process.env.DATABASE_URI to process.env.POSTGRES_URL
dbUri: 'POSTGRES_URL',
},
},
{
name: 'payload-vercel-mongodb-template',
dirname: 'with-vercel-mongodb',
db: 'mongodb',
storage: 'vercelBlobStorage',
vercelDeployButtonLink:
`https://vercel.com/new/clone?repository-url=` +
encodeURI(
'https://github.com/payloadcms/vercel-deploy-payload-postgres' +
'&project-name=payload-project' +
'&env=PAYLOAD_SECRET' +
'&build-command=pnpm run ci' +
'&stores=[{"type":"blob"}]' + // Vercel Blob Storage
'&integration-ids=oac_jnzmjqM10gllKmSrG0SGrHOH', // MongoDB Atlas
),
envNames: {
dbUri: 'MONGODB_URI',
},
},
{
name: 'payload-cloud-mongodb-template',
Expand All @@ -41,7 +88,7 @@ async function main() {
},
]

for (const { name, dirname, db, storage } of variations) {
for (const { name, dirname, db, storage, vercelDeployButtonLink, envNames } of variations) {
console.log(`Generating ${name}...`)
const destDir = path.join(templatesDir, dirname)
copyRecursiveSync(path.join(templatesDir, 'blank-3.0'), destDir)
Expand All @@ -53,13 +100,67 @@ async function main() {
packageJsonName: name,
projectDirOrConfigPath: { projectDir: destDir },
storageAdapter: storage,
envNames,
})

await generateReadme({
destDir,
data: {
name,
description: name, // TODO: Add descriptions
attributes: { db, storage },
...(vercelDeployButtonLink && { vercelDeployButtonLink }),
},
})

// Copy in initial migration if db is postgres. This contains user and media.
if (db === 'postgres') {
const migrationSrcDir = path.join(templatesDir, '_data/migrations')
const migrationDestDir = path.join(destDir, 'src/migrations')

// Make directory if it doesn't exist
if ((await fs.stat(migrationDestDir).catch(() => null)) === null) {
await fs.mkdir(migrationDestDir, { recursive: true })
}
console.log(`Copying migrations from ${migrationSrcDir} to ${migrationDestDir}`)
copyRecursiveSync(migrationSrcDir, migrationDestDir)
}

// TODO: Email?

// TODO: Sharp?

console.log(`Done configuring payload config for ${destDir}/src/payload.config.ts`)
}
}

main().catch((error) => {
console.error(error)
process.exit(1)
})
async function generateReadme({
destDir,
data: { name, description, attributes, vercelDeployButtonLink },
}: {
destDir: string
data: {
name: string
description: string
attributes: Pick<TemplateVariations, 'db' | 'storage'>
vercelDeployButtonLink?: string
}
}) {
let header = `# ${name}\n`
if (vercelDeployButtonLink) {
header += `[![Deploy with Vercel](https://vercel.com/button)](${vercelDeployButtonLink})\n`
}

const readmeContent = `${header}
${description}
## Attributes
- **Database**: ${attributes.db}
- **Storage Adapter**: ${attributes.storage}
`

const readmePath = path.join(destDir, 'README.md')
await fs.writeFile(readmePath, readmeContent)
console.log(`Generated README.md in ${readmePath}`)
}
Loading

0 comments on commit edc9239

Please sign in to comment.