Skip to content
This repository has been archived by the owner on Jul 27, 2020. It is now read-only.

Commit

Permalink
Merge pull request #91 from prisma/feature/experimental-extensions
Browse files Browse the repository at this point in the history
[RFR] Add support for express middlewares
  • Loading branch information
Weakky authored Mar 14, 2019
2 parents 00f1c12 + 865a9f4 commit 05d2a40
Show file tree
Hide file tree
Showing 20 changed files with 247 additions and 144 deletions.
6 changes: 0 additions & 6 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ jobs:
- run:
name: update-npm
command: sudo npm install -g npm@latest
- restore_cache:
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: install-package-dependencies
command: yarn run bootstrap:ci
Expand All @@ -22,10 +20,6 @@ jobs:
- run:
name: run-build
command: sudo yarn run build:ci
- save_cache:
key: dependency-cache-{{ checksum "package.json" }}
paths:
- ./node_modules
- run:
name: run lint
command: yarn run lint
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ dist
yalc.lock
yarn.lock
package-lock.json
.idea
.idea
.docz
2 changes: 1 addition & 1 deletion examples/minimal-ejected/.yoga/nexus.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* This file was automatically generated by Nexus 0.9.14
* This file was automatically generated by Nexus 0.10.0
* Do not make changes to this file directly
*/

Expand Down
6 changes: 4 additions & 2 deletions examples/minimal-ejected/src/context.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { yogaContext } from 'yoga'

interface UserModel {
id: string
name: string
Expand All @@ -22,6 +24,6 @@ export interface Context {
users: UserModel[]
}

export default () => ({
export default yogaContext(() => ({
users,
})
}))
2 changes: 1 addition & 1 deletion examples/minimal-ejected/src/schema.graphql
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
### This file was autogenerated by Nexus 0.9.14
### This file was autogenerated by Nexus 0.10.0
### Do not make changes to this file directly


Expand Down
40 changes: 29 additions & 11 deletions examples/minimal-ejected/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,51 @@
import { Server } from 'http'
import * as path from 'path'
import { ApolloServer, makeSchema, Yoga } from 'yoga'
import { ApolloServer, express, makeSchema, yogaEject } from 'yoga'
import context from './context'
import * as types from './graphql'

export default {
server: dirname => {
export default yogaEject({
async server() {
const app = express()

const schema = makeSchema({
types,
outputs: {
schema: path.join(dirname, './schema.graphql'),
typegen: path.join(dirname, '../.yoga/nexus.ts'),
schema: path.join(__dirname, './schema.graphql'),
typegen: path.join(__dirname, '../.yoga/nexus.ts'),
},
typegenAutoConfig: {
sources: [
{
source: path.join(dirname, './context.ts'),
source: path.join(__dirname, './context.ts'),
alias: 'ctx',
},
],
contextType: 'ctx.Context',
},
})

return new ApolloServer({
const apolloServer = new ApolloServer.ApolloServer({
schema,
context,
})

apolloServer.applyMiddleware({ app, path: '/' })

return app
},
async startServer(express) {
return new Promise<Server>((resolve, reject) => {
const httpServer = express
.listen({ port: 4000 }, () => {
console.log(`🚀 Server ready at http://localhost:4000/`)

resolve(httpServer)
})
.on('error', err => reject(err))
})
},
async stopServer(httpServer) {
return httpServer.close()
},
startServer: server =>
server.listen().then(s => console.log(`Server listening at ${s.url}`)),
stopServer: server => server.stop(),
} as Yoga<ApolloServer>
})
1 change: 0 additions & 1 deletion examples/minimal-ejected/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"target": "es5",
"rootDir": ".",
"outDir": "dist",
Expand Down
6 changes: 4 additions & 2 deletions examples/with-db/src/context.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { prisma, Prisma } from '../.yoga/prisma-client'
import { yogaContext } from 'yoga'

export interface Context {
prisma: Prisma
}

export default () => ({
export default yogaContext(({ req }) => ({
req,
prisma,
})
}))
2 changes: 1 addition & 1 deletion packages/create-yoga/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"inquirer-path": "^1.0.0-beta5",
"js-yaml": "^3.12.2",
"meow": "^5.0.0",
"ora": "^3.0.0",
"ora": "^3.2.0",
"parse-github-url": "^1.0.2",
"prettier": "^1.16.4",
"prisma-datamodel": "^1.28.3",
Expand Down
3 changes: 2 additions & 1 deletion packages/yoga/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"yoga": "dist/cli/index.js"
},
"dependencies": {
"apollo-server": "^2.4.2",
"apollo-server-express": "^2.4.8",
"chalk": "^2.4.2",
"chokidar": "^2.1.1",
"create-yoga": "0.0.2",
Expand All @@ -34,6 +34,7 @@
},
"devDependencies": {
"@types/chokidar": "1.7.5",
"@types/express": "^4.16.1",
"@types/graphql": "14.0.7",
"@types/inquirer": "0.0.44",
"@types/js-yaml": "3.12.0",
Expand Down
83 changes: 45 additions & 38 deletions packages/yoga/src/cli/commands/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as path from 'path'
import * as ts from 'typescript'
import { findConfigFile, importYogaConfig } from '../../../config'
import { findFileByExtension } from '../../../helpers'
import { Config, ConfigWithInfo } from '../../../types'
import { ConfigWithInfo } from '../../../types'
import { DEFAULTS } from '../../../yogaDefaults'

const diagnosticHost: ts.FormatDiagnosticsHost = {
Expand Down Expand Up @@ -35,9 +35,8 @@ export default () => {
tsConfigPath,
)
const config = fixConfig(inputConfig, info.projectDir)
const rootNames = getRootNames(info)

compile(rootNames, config.options)
compile(config.fileNames, config.options)

if (!info.yogaConfig.ejectFilePath) {
const ejectFilePath = path.join(
Expand All @@ -46,7 +45,7 @@ export default () => {
'index.ts',
)

writeEntryPoint(info, ejectFilePath!, config)
writeEntryPoint(info, ejectFilePath, config)
} else {
useEntryPoint(info, info.yogaConfig.ejectFilePath, config)
}
Expand All @@ -69,25 +68,6 @@ function compile(rootNames: string[], options: ts.CompilerOptions) {
}
}

function getRootNames(info: ConfigWithInfo) {
const rootNames = findFileByExtension(info.yogaConfig.resolversPath, '.ts')

if (info.yogaConfig.contextPath) {
rootNames.push(info.yogaConfig.contextPath)
}

if (info.yogaConfig.ejectFilePath) {
rootNames.push(info.yogaConfig.ejectFilePath)
}

if (info.yogaConfig.prisma) {
rootNames.push(...findFileByExtension(info.prismaClientDir!, '.ts'))
rootNames.push(...findFileByExtension(info.datamodelInfoDir!, '.ts'))
}

return rootNames
}

/**
* Do post-processing on config options to support `ts-node`.
*/
Expand Down Expand Up @@ -117,14 +97,18 @@ function useEntryPoint(
config: ts.ParsedCommandLine,
) {
const indexFile = `
import yogaServer from '${getRelativePath(
import yoga from '${getRelativePath(
path.dirname(ejectFilePath),
ejectFilePath,
)}'
const serverInstance = yogaServer.server(__dirname)
async function main() {
const serverInstance = await yoga.server()
return yoga.startServer(serverInstance)
}
yogaServer.startServer(serverInstance)
main()
`
const indexFilePath = path.join(path.dirname(ejectFilePath), 'index.ts')

Expand All @@ -138,7 +122,7 @@ function writeEntryPoint(
) {
const ejectFile = info.yogaConfig.prisma
? prismaIndexFile(path.dirname(ejectFilePath), info)
: simpleIndexfile(path.dirname(ejectFilePath), info.yogaConfig)
: simpleIndexfile(path.dirname(ejectFilePath), info)

outputFile(ejectFile, ejectFilePath, config.options, info)

Expand All @@ -151,7 +135,7 @@ function writeEntryPoint(

function prismaIndexFile(filePath: string, info: ConfigWithInfo) {
return `
import { ApolloServer, makePrismaSchema } from 'yoga'
import { ApolloServer, makePrismaSchema, express } from 'yoga'
import datamodelInfo from '${getRelativePath(
filePath,
info.datamodelInfoDir!,
Expand All @@ -170,6 +154,7 @@ function prismaIndexFile(filePath: string, info: ConfigWithInfo) {
info.yogaConfig.resolversPath,
)}'
const schema = makePrismaSchema({
types,
prisma: {
Expand All @@ -179,35 +164,57 @@ function prismaIndexFile(filePath: string, info: ConfigWithInfo) {
outputs: false
})
new ApolloServer({
const apolloServer = new ApolloServer.ApolloServer({
schema,
${info.yogaConfig.contextPath ? 'context' : ''}
}).listen().then(s => console.log(\`🚀 Server listening at \${s.url}\`))
})
const app = express()
apolloServer.applyMiddleware({ app, path: '/' })
app.listen({ port: 4000 }, () => {
console.log(
\`🚀 Server ready at http://localhost:4000/\`,
)
})
`
}

function simpleIndexfile(filePath: string, yogaConfig: Config) {
function simpleIndexfile(filePath: string, info: ConfigWithInfo) {
return `\
import { ApolloServer, makeSchema } from 'yoga'
import { ApolloServer, makeSchema, express } from 'yoga'
${
yogaConfig.contextPath
info.yogaConfig.contextPath
? `import context from '${getRelativePath(
filePath,
yogaConfig.contextPath,
info.yogaConfig.contextPath,
)}'`
: ''
}
import * as types from '${getRelativePath(filePath, yogaConfig.resolversPath)}'
import * as types from '${getRelativePath(
filePath,
info.yogaConfig.resolversPath,
)}'
const schema = makeSchema({
types,
outputs: false
})
new ApolloServer({
const apolloServer = new ApolloServer.ApolloServer({
schema,
context,
}).listen().then(s => console.log(\`🚀 Server listening at \${s.url}\`)),
${info.yogaConfig.contextPath ? 'context' : ''}
})
const app = express()
apolloServer.applyMiddleware({ app, path: '/' })
app.listen({ port: 4000 }, () => {
console.log(
\`🚀 Server ready at http://localhost:4000/\`,
)
})
`
}

Expand Down
4 changes: 1 addition & 3 deletions packages/yoga/src/cli/commands/start/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,5 @@ import { start } from '../../../server'
import { importYogaConfig } from '../../../config'

export default async () => {
const { yogaConfig, prismaClientDir } = importYogaConfig()

return start(yogaConfig, prismaClientDir)
return start(importYogaConfig())
}
2 changes: 1 addition & 1 deletion packages/yoga/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ function getDatamodelInfoDir(
}

if (inputConfig.prisma && inputConfig.prisma.datamodelInfoPath) {
return inputConfig.prisma.datamodelInfoPath
return path.join(projectDir, inputConfig.prisma.datamodelInfoPath)
}

return path.join(projectDir, DEFAULT_META_SCHEMA_DIR)
Expand Down
8 changes: 4 additions & 4 deletions packages/yoga/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ export function importUncached<T extends any = any>(
*/
export function importFile<T extends any = any>(
filePath: string,
exportName: string,
exportName?: string,
invalidateModule: boolean = false,
): T {
const importedModule = importUncached(filePath, invalidateModule)
const importedModule = importUncached<T>(filePath, invalidateModule)

if (importedModule[exportName] === undefined) {
if (exportName && importedModule[exportName] === undefined) {
throw new Error(`\`${filePath}\` must have a '${exportName}' export`)
}

return importedModule[exportName]
return exportName ? importedModule[exportName] : importedModule
}
Loading

0 comments on commit 05d2a40

Please sign in to comment.