Files
payload/packages/create-payload-app/src/lib/download-example.ts
Sasha 6b4842d44d feat(cpa): create project from example using --example CLI arg (#10172)
Adds the ability to create a project using an existing in the Payload
repo example through `create-payload-app`:

For example:
`pnpx create-payload-app --example custom-server` - creates a project
from the
[custom-server](https://github.com/payloadcms/payload/tree/main/examples/custom-server)
example.

This is much easier and faster then downloading the whole repo and
copying the example to another folder.
Note that we don't configure the payload config with the storage / DB
adapter there because examples can be very specific.
2024-12-27 20:16:34 +02:00

47 lines
1.1 KiB
TypeScript

import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { x } from 'tar'
import type { ProjectExample } from '../types.js'
import { debug as debugLog } from '../utils/log.js'
export async function downloadExample({
debug,
example,
projectDir,
}: {
debug?: boolean
example: ProjectExample
projectDir: string
}) {
const branchOrTag = example.url.split('#')?.[1] || 'latest'
const url = `https://codeload.github.com/payloadcms/payload/tar.gz/${branchOrTag}`
const filter = `payload-${branchOrTag.replace(/^v/, '')}/examples/${example.name}/`
if (debug) {
debugLog(`Using example url: ${example.url}`)
debugLog(`Codeload url: ${url}`)
debugLog(`Filter: ${filter}`)
}
await pipeline(
await downloadTarStream(url),
x({
cwd: projectDir,
filter: (p) => p.includes(filter),
strip: 2 + example.name.split('/').length,
}),
)
}
async function downloadTarStream(url: string) {
const res = await fetch(url)
if (!res.body) {
throw new Error(`Failed to download: ${url}`)
}
return Readable.from(res.body as unknown as NodeJS.ReadableStream)
}