Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

create-graphql-yoga CLI #2698

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 1,6 @@
---
'@graphql-yoga/template-node-ts': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^3.9.1` ↗︎](https://www.npmjs.com/package/graphql-yoga/v/3.9.1) (from `3.9.1`, in `dependencies`)
- Updated dependency [`graphql@^16.6.0` ↗︎](https://www.npmjs.com/package/graphql/v/16.6.0) (from `16.6.0`, in `dependencies`)
6 changes: 6 additions & 0 deletions .changeset/small-dogs-complain.md
Original file line number Diff line number Diff line change
@@ -0,0 1,6 @@
---
'@graphql-yoga/template-node-ts': patch
'create-graphql-yoga': patch
---

New CLI to create Yoga projects
30 changes: 0 additions & 30 deletions examples/node-ts/build.js

This file was deleted.

14 changes: 6 additions & 8 deletions examples/node-ts/package.json
Original file line number Diff line number Diff line change
@@ -1,18 1,16 @@
{
"name": "example-node-ts",
"private": true,
"version": "1.0.0",
"name": "@graphql-yoga/template-node-ts",
"version": "0.0.0",
"scripts": {
"start": "ts-node src/index.ts",
"build": "node ./build.js",
"check": "tsc --pretty --noEmit"
},
"dependencies": {
"graphql-yoga": "3.9.1",
"graphql": "16.6.0"
"graphql-yoga": "^3.9.1",
"graphql": "^16.6.0"
},
"devDependencies": {
"ts-node": "10.9.1",
"typescript": "5.0.4"
"ts-node": "^10.9.1",
"typescript": "^5.0.4"
}
}
1 change: 0 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,7 1,6 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const { resolve } = require('node:path')
const { pathsToModuleNameMapper } = require('ts-jest')
const fs = require('fs')
const CI = !!process.env.CI

const ROOT_DIR = __dirname
Expand Down
30 changes: 30 additions & 0 deletions packages/create-graphql-yoga/__integration-tests__/cli.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 1,30 @@
import { Request, Response, fetch } from '@whatwg-node/fetch'
import { createGraphQLYoga } from '../src/index.js'
import { createReadStream, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { Readable } from 'node:stream'
import { rimrafSync } from 'rimraf'

describe('create-graphql-yoga', () => {
if (process.versions.node.startsWith('14.')) {
// eslint-disable-next-line @typescript-eslint/no-empty-function
it('noop', () => {})
}
const testProjectName = 'test-project'
const testProjectDir = join(process.cwd(), testProjectName)
afterEach(() => {
rimrafSync(testProjectDir)
})
it('creates a new project with node-ts example by default', async () => {
await createGraphQLYoga({
argv: ['node', 'create-graphql-yoga'],
input: Readable.from('test-project\n'),
output: process.stdout,
fetchFn: fetch,
})
const packageJsonPath = join(process.cwd(), 'test-project', 'package.json')
const packageJsonContent = readFileSync(packageJsonPath, 'utf-8')
const packageJson = JSON.parse(packageJsonContent)
expect(packageJson.name).toEqual('test-project')
})
})
73 changes: 73 additions & 0 deletions packages/create-graphql-yoga/package.json
Original file line number Diff line number Diff line change
@@ -0,0 1,73 @@
{
"name": "create-graphql-yoga",
"version": "0.0.0",
"description": "",
"repository": {
"type": "git",
"url": "https://github.com/dotansimha/graphql-yoga.git",
"directory": "packages/create-graphql-yoga"
},
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"bin": {
"create-graphql-yoga": "dist/cjs/bin.js"
},
"buildOptions": {
"bin": {
"create-graphql-yoga": {
"input": "src/bin.ts"
}
},
"./package.json": "./package.json"
},
"scripts": {
"check": "tsc --pretty --noEmit"
},
"keywords": [
"graphql",
"server",
"api",
"graphql-server"
],
"author": "Arda TANRIKULU <[email protected]>",
"license": "MIT",
"exports": {
".": {
"require": {
"types": "./dist/typings/index.d.cts",
"default": "./dist/cjs/index.js"
},
"import": {
"types": "./dist/typings/index.d.ts",
"default": "./dist/esm/index.js"
},
"default": {
"types": "./dist/typings/index.d.ts",
"default": "./dist/esm/index.js"
}
},
"./package.json": "./package.json"
},
"typings": "dist/typings/index.d.ts",
"typescript": {
"definition": "dist/typings/index.d.ts"
},
"publishConfig": {
"directory": "dist",
"access": "public"
},
"dependencies": {
"@whatwg-node/fetch": "^0.8.5",
"get-npm-tarball-url": "^2.0.3",
"ora": "^5.4.1",
"tslib": "^2.3.1",
"tar": "^6.1.13"
},
"devDependencies": {
"@types/tar": "^6.1.4",
"ts-node": "^10.9.1",
"rimraf": "^5.0.0"
},
"type": "module",
"sideEffects": false
}
13 changes: 13 additions & 0 deletions packages/create-graphql-yoga/src/bin.ts
Original file line number Diff line number Diff line change
@@ -0,0 1,13 @@
#!/usr/bin/env node
import { createGraphQLYoga, spinner } from './index.js'
import { fetch } from '@whatwg-node/fetch'

createGraphQLYoga({
argv: process.argv,
input: process.stdin,
output: process.stdout,
fetchFn: fetch,
}).catch((e) => {
spinner.fail(e.message)
process.exit(1)
})
133 changes: 133 additions & 0 deletions packages/create-graphql-yoga/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 1,133 @@
import ora from 'ora'
import { parseArgs } from 'node:util'
import tar from 'tar'
import { join } from 'node:path'
import { Readable } from 'node:stream'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { createInterface } from 'node:readline'
import getNpmTarballUrl from 'get-npm-tarball-url'

export const spinner = ora()

const options = {
template: {
type: 'string',
short: 't',
},
} as const

function getRegistryAPIUrl(packageName: string, version: string) {
return `https://registry.npmjs.org/${packageName}/${version}`
}

async function getVersionByTag(
packageName: string,
tag: string,
fetchFn: typeof fetch,
) {
const url = getRegistryAPIUrl(packageName, tag)
const response = await fetchFn(url)
if (response.status === 404) {
throw new Error(`Package not found: ${packageName}`)
}
if (!response.ok) {
throw new Error(
`Failed to fetch package ${packageName} with ${
response.status
}: ${await response.text()}`,
)
}
const { version } = await response.json()
return version
}

function getPackageNameAndTagForTemplate(template: string) {
const [suffix, tag] = template.split('@')
return {
packageName: `@graphql-yoga/template-${suffix}`,
tag: tag ?? 'latest',
}
}

export interface CreateGraphQLYogaOpts {
argv: string[]
input: Readable
output: NodeJS.WritableStream
fetchFn: typeof fetch
}

export async function createGraphQLYoga({
argv,
input,
output,
fetchFn,
}: CreateGraphQLYogaOpts) {
const args = [...argv]
while (args[0].startsWith('/') || args[0] === '--') {
args.shift()
}
const rl = createInterface({
input,
output,
})

const projectName = await new Promise<string>((resolve) => {
rl.question('What is the name of your project? ', (answer) => {
resolve(answer)
})
})

const {
values: { template = 'node-ts' },
} = parseArgs({ args, options, allowPositionals: true })
spinner.start(`Fetching template ${template}...`)
const { packageName, tag } = getPackageNameAndTagForTemplate(template)
const version = await getVersionByTag(packageName, tag, fetchFn)
const url = getNpmTarballUrl(packageName, version)
const response = await fetchFn(url)
if (response.status === 404) {
throw new Error(`Template not found: ${template}`)
}
if (!response.ok) {
throw new Error(
`Failed to fetch template ${template} with ${
response.status
}: ${await response.text()}`,
)
}
if (!response.body) {
throw new Error(`Failed to fetch template ${template} with empty body`)
}
const nodeStream = Readable.from(
response.body as unknown as AsyncIterable<Uint8Array>,
)
const targetDir = join(process.cwd(), projectName)
if (existsSync(targetDir)) {
throw new Error(`Target directory ${targetDir} already exists.`)
}
mkdirSync(targetDir, { recursive: true })
await new Promise<void>((resolve, reject) => {
const extractedTarStream = tar.extract({
strip: 1,
cwd: targetDir,
})
nodeStream
.pipe(extractedTarStream)
.once('error', (err) => {
reject(new Error(`Failed to extract template ${template} with ${err}`))
})
.once('close', () => {
resolve()
})
})
const packageJsonPath = join(targetDir, 'package.json')
const packageJsonContent = readFileSync(packageJsonPath, 'utf-8')
const packageJson = JSON.parse(packageJsonContent)
packageJson.name = projectName
delete packageJson.version
packageJson.private = true
const newPackageJsonContent = JSON.stringify(packageJson, null, 2)
writeFileSync(packageJsonPath, newPackageJsonContent)

spinner.succeed(`Project ${projectName} created on ${targetDir}.`)
}
6 changes: 6 additions & 0 deletions packages/create-graphql-yoga/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 1,6 @@
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "nodenext"
}
}
Loading