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

Refactor GraphQL Server and CreateYoga to Support "api serve" with Fastify Server #8339

Merged
Merged
Show file tree
Hide file tree
Changes from 16 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
10 changes: 8 additions & 2 deletions docs/docs/graphql.md
Original file line number Diff line number Diff line change
Expand Up @@ -1452,9 +1452,9 @@ The [GraphQL Playground](https://www.graphql-yoga.com/docs/features/graphiql) is

> Because both introspection and the playground share possibly sensitive information about your data model, your data, your queries and mutations, best practices for deploying a GraphQL Server call to disable these in production, RedwoodJS **, by default, only enables introspection and the playground when running in development**. That is when `process.env.NODE_ENV === 'development'`.

However, there may be cases where you want to enable introspection. You can enable introspection by setting the `allowIntrospection` option to `true`.
However, there may be cases where you want to enable introspection as well as the GraphQL PLaygrouns. You can enable introspection by setting the `allowIntrospection` option to `true` and enable GraphiQL by setting `allowGraphiQL` to `true`.

Here is an example of `createGraphQLHandler` function with the `allowIntrospection` option set to `true`:
Here is an example of `createGraphQLHandler` function with the `allowIntrospection` and `allowGraphiQL` options set to `true`:
```ts {8}
export const handler = createGraphQLHandler({
authDecoder,
Expand All @@ -1464,6 +1464,7 @@ export const handler = createGraphQLHandler({
sdls,
services,
allowIntrospection: true, // 👈 enable introspection in all environments
allowGraphiQL: true, // 👈 enable introspection in all environments
dthyresson marked this conversation as resolved.
Show resolved Hide resolved
onException: () => {
// Disconnect from your database with an unhandled exception.
db.$disconnect()
Expand All @@ -1475,8 +1476,13 @@ export const handler = createGraphQLHandler({

Enabling introspection in production may pose a security risk, as it allows users to access information about your schema, queries, and mutations. Use this option with caution and make sure to secure your GraphQL API properly.

The may be cases where one wants to allow introspection, but not GraphiQL.

Or, you may want to enable GraphiQL, but not allow introspection; for example, to try out known queries, but not to share the entire set of possible operations and types.

:::


### GraphQL Armor Configuration

[GraphQL Armor](https://escape.tech/graphql-armor/) is a middleware that adds a security layer the RedwoodJS GraphQL endpoint configured with sensible defaults.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,40 +1,49 @@
import path from 'path'

// import { useLiveQuery } from '@envelop/live-query'
import chalk from 'chalk'
import { config } from 'dotenv-defaults'
import Fastify from 'fastify'
import { OperationTypeNode } from 'graphql'

import {
coerceRootPath,
redwoodFastifyWeb,
redwoodFastifyAPI,
redwoodFastifyGraphQLServer,
DEFAULT_REDWOOD_FASTIFY_CONFIG,
} from '@redwoodjs/fastify'
import { getPaths, getConfig } from '@redwoodjs/project-config'

import directives from 'src/directives/**/*.{js,ts}'
import sdls from 'src/graphql/**/*.sdl.{js,ts}'
import services from 'src/services/**/*.{js,ts}'

import { logger } from './lib/logger'

async function serve() {
// Load .env files
const redwoodProjectPaths = getPaths()
const redwoodConfig = getConfig()

const apiRootPath = coerceRootPath(redwoodConfig.web.apiUrl)
const port = redwoodConfig.web.port

const tsServer = Date.now()

config({
path: path.join(redwoodProjectPaths.base, '.env'),
defaults: path.join(redwoodProjectPaths.base, '.env.defaults'),
multiline: true,
})

const tsServer = Date.now()
console.log(chalk.italic.dim('Starting API and Web Servers...'))

// Configure Fastify
const fastify = Fastify({
...DEFAULT_REDWOOD_FASTIFY_CONFIG,
})

const redwoodConfig = getConfig()

const apiRootPath = coerceRootPath(redwoodConfig.web.apiUrl)
const port = redwoodConfig.web.port

await fastify.register(redwoodFastifyWeb)

await fastify.register(redwoodFastifyAPI, {
Expand All @@ -43,6 +52,24 @@ async function serve() {
},
})

await fastify.register(redwoodFastifyGraphQLServer, {
loggerConfig: {
logger: logger,
options: { query: true, data: true, level: 'trace' },
},
graphiQLEndpoint: '/yoga',
sdls,
services,
directives,
allowIntrospection: true,
allowGraphiQL: true,
allowedOperations: [
OperationTypeNode.SUBSCRIPTION,
OperationTypeNode.QUERY,
OperationTypeNode.MUTATION,
],
})

// Start
fastify.listen({ port })

Expand All @@ -55,7 +82,7 @@ async function serve() {
console.log(`API serving from ${apiServer}`)
console.log(`API listening on ${on}`)
const graphqlEnd = chalk.magenta(`${apiRootPath}graphql`)
console.log(`GraphQL endpoint at ${graphqlEnd}`)
console.log(`GraphQL serverless function endpoint at ${graphqlEnd}`)
dthyresson marked this conversation as resolved.
Show resolved Hide resolved
})

process.on('exit', () => {
Expand Down
1 change: 1 addition & 0 deletions packages/fastify/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ await esbuild.build({
entryPoints: [
'src/api.ts',
'src/config.ts',
'src/graphql.ts',
'src/index.ts',
'src/types.ts',
'src/web.ts',
Expand Down
1 change: 1 addition & 0 deletions packages/fastify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@fastify/http-proxy": "9.1.0",
"@fastify/static": "6.10.1",
"@fastify/url-data": "5.3.1",
"@redwoodjs/graphql-server": "5.0.0",
"@redwoodjs/project-config": "5.0.0",
"ansi-colors": "4.1.3",
"fast-glob": "3.2.12",
Expand Down
43 changes: 43 additions & 0 deletions packages/fastify/src/graphql.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { FastifyInstance } from 'fastify'

import type { GraphQLYogaOptions } from '@redwoodjs/graphql-server'
import { createGraphQLYoga } from '@redwoodjs/graphql-server'
/**
* Encapsulates the routes
* @param {FastifyInstance} fastify Encapsulated Fastify Instance
* @param {Object} options plugin options, refer to https://www.fastify.io/docs/latest/Reference/Plugins/#plugin-options
*/
export async function redwoodFastifyGraphQLServer(
fastify: FastifyInstance,
options: GraphQLYogaOptions
) {
try {
const { yoga } = createGraphQLYoga(options)

fastify.route({
url: yoga.graphqlEndpoint,
method: ['GET', 'POST', 'OPTIONS'],
handler: async (req, reply) => {
const response = await yoga.handleNodeRequest(req, {
req,
reply,
})

for (const [name, value] of response.headers) {
reply.header(name, value)
}

reply.status(response.status)
reply.send(response.body)

return reply
},
})

fastify.ready(() => {
console.log(`GraphQL Yoga Server endpoint at ${yoga.graphqlEndpoint}`)
})
} catch (e) {
console.log(e)
}
}
1 change: 1 addition & 0 deletions packages/fastify/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export function createFastifyInstance(options?: FastifyServerOptions) {

export { redwoodFastifyAPI } from './api.js'
export { redwoodFastifyWeb } from './web.js'
export { redwoodFastifyGraphQLServer } from './graphql.js'

export type * from './types.js'

Expand Down
2 changes: 1 addition & 1 deletion packages/graphql-server/src/__tests__/cors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { createLogger } from '@redwoodjs/api/logger'

import { createGraphQLHandler } from '../functions/graphql'

jest.mock('../makeMergedSchema/makeMergedSchema', () => {
jest.mock('../makeMergedSchema', () => {
const { makeExecutableSchema } = require('@graphql-tools/schema')
// Return executable schema
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const bazingaSchema = gql`
const barSchema = gql`
directive @bar on FIELD_DEFINITION
`
test('Should map globs to defined structure correctly', async () => {
test('Should map directives globs to defined structure correctly', async () => {
// Mocking what our import-dir plugin would do
const directiveFiles = {
foo_directive: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import {
makeDirectivesForPlugin,
createTransformerDirective,
createValidatorDirective,
} from '../../directives/makeDirectives'
} from '../directives/makeDirectives'
import { makeMergedSchema } from '../makeMergedSchema'
import {
GraphQLTypeWithFields,
ServicesGlobImports,
SdlGlobImports,
} from '../../types'
import { makeMergedSchema } from '../makeMergedSchema'
} from '../types'

jest.mock('@redwoodjs/project-config', () => {
return {
Expand Down Expand Up @@ -138,6 +138,7 @@ describe('makeMergedSchema', () => {
const schema = makeMergedSchema({
sdls,
services,
subscriptions: [],
directives: makeDirectivesForPlugin(directiveFiles),
})

Expand Down
70 changes: 70 additions & 0 deletions packages/graphql-server/src/__tests__/makeSubscriptions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import gql from 'graphql-tag'

import { makeSubscriptions } from '../subscriptions/makeSubscriptions'
const countdownSchema = gql`
type Subscription {
countdown(from: Int!, interval: Int!): Int!
}
`

const newMessageSchema = gql`
type Message {
from: String
body: String
}
type Subscription {
newMessage(roomId: ID!): Message!
}
`
describe('Should map subscription globs to defined structure correctly', () => {
it('Should map a subscribe correctly', async () => {
// Mocking what our import-dir plugin would do
const subscriptionFiles = {
countdown_subscription: {
schema: countdownSchema,
countdown: {
async *subscribe(_, { from, interval }) {
for (let i = from; i >= 0; i--) {
await new Promise((resolve) =>
setTimeout(resolve, interval ?? 1000)
)
yield { countdown: i }
}
},
},
},
}

const [countdownSubscription] = makeSubscriptions(subscriptionFiles)

expect(countdownSubscription.schema.kind).toBe('Document')
expect(countdownSubscription.name).toBe('countdown')
expect(countdownSubscription.resolvers.subscribe).toBeDefined()
expect(countdownSubscription.resolvers.resolve).not.toBeDefined()
})

it('Should map a subscribe and resolve correctly', async () => {
// Mocking what our import-dir plugin would do
const subscriptionFiles = {
newMessage_subscription: {
schema: newMessageSchema,
newMessage: {
subscribe: (_, { roomId }) => {
return roomId
},
resolve: (payload) => {
return payload
},
},
},
}

const [newMessageSubscription] = makeSubscriptions(subscriptionFiles)

expect(newMessageSubscription.schema.kind).toBe('Document')
expect(newMessageSubscription.name).toBe('newMessage')
expect(newMessageSubscription.resolvers.subscribe).toBeDefined()
expect(newMessageSubscription.resolvers.resolve).toBeDefined()
})
})
Loading