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

fix(gatsby-plugin-graphql): Export schema types #916

Merged
merged 2 commits into from
Aug 24, 2021
Merged
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
33 changes: 26 additions & 7 deletions packages/gatsby-plugin-graphql/src/gatsby-node.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
import { join } from 'path'

import { makeExecutableSchema } from '@graphql-tools/schema'
import { parse, printSchema } from 'graphql'
import type { CreatePageArgs, CreateWebpackConfigArgs } from 'gatsby'
import type {
CreatePageArgs,
CreateWebpackConfigArgs,
PluginOptionsSchemaArgs,
} from 'gatsby'

import { WebpackPlugin } from './webpack'

export const onCreateWebpackConfig = async ({
actions: { setWebpackConfig },
store,
stage,
}: CreateWebpackConfigArgs) => {
interface Options {
schemaPath?: string
}

export const pluginOptionsSchema = ({ Joi }: PluginOptionsSchemaArgs) => {
return Joi.object({
schemaPath: Joi.string(),
})
}

export const onCreateWebpackConfig = async (
{ actions: { setWebpackConfig }, store, stage }: CreateWebpackConfigArgs,
options: Options
) => {
if (stage === 'build-html' || stage === 'develop-html') {
return
}
Expand All @@ -23,9 +38,13 @@ export const onCreateWebpackConfig = async ({
const { schema: dirtySchema } = store.getState()
const typeDefs = parse(printSchema(dirtySchema))
const schema = makeExecutableSchema({ typeDefs })
const schemaPath = join(
process.cwd(),
options.schemaPath ?? '/src/typings/schema.graphql.d.ts'
)

setWebpackConfig({
plugins: [new WebpackPlugin(schema)],
plugins: [new WebpackPlugin(schema, { schemaPath })],
})
}

Expand Down
86 changes: 61 additions & 25 deletions packages/gatsby-plugin-graphql/src/webpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ export const publicPath = '/page-data/_graphql'

export const target = join(root, 'public', publicPath)

const disclaimer = `
/**
* Warning: This is an autogenerated file.
*
* Changes in this file won't take effect and will be overwritten
*/
`

const queryCode = ({ name, value, sha256Hash }: QueryNode) => `
export const ${name} = {
query: process.env.NODE_ENV === 'production' ? undefined : ${JSON.stringify(
Expand All @@ -45,22 +53,7 @@ export const ${name} = {
`

const wrapTypes = (types: string, node: QueryNode | null) => `
/**
* Warning: This is an autogenerated file.
*
* Changes in this file won't take effect and will be overwritten
*/

// Base Types
${typeScriptPlugin.EXACT_SIGNATURE}
type Maybe<T> = T | null | undefined
type Scalars = {
Boolean: boolean
String: string
Float: number
Int: number
ID: string
}
${disclaimer}

// Operation related types
${types}
Expand All @@ -69,6 +62,13 @@ ${types}
${node ? queryCode(node) : ''}
`

const wrapSchema = (schema: string) =>
`
${disclaimer}

${schema}
`.trim()

type QueryNode = Node & { sha256Hash: string }
type FragmentNode = Node

Expand All @@ -80,7 +80,10 @@ export class WebpackPlugin {
public queryInfoPath: string
public cachePath: string

constructor(public schema: GraphQLSchema) {
constructor(
public schema: GraphQLSchema,
public options: { schemaPath: string }
) {
this.persistedPath = join(root, 'public', publicPath, persisted)
this.queryInfoPath = join(root, 'public', publicPath, queryInfo)
this.cachePath = join(root, 'public', publicPath, cache)
Expand All @@ -106,7 +109,38 @@ export class WebpackPlugin {
return print(optimized[0])
}

public generateCode = async (nodes: Array<QueryNode | FragmentNode>) => {
public generateSchemaCode = async () =>
codegen({
config: {
allowEnumStringTypes: false,
avoidOptionals: true,
enumsAsTypes: true,
skipTypeNameForRoot: true,
skipTypename: true,
noExport: true,
namingConvention: 'change-case-all#pascalCase',
},
documents: [],
// used by a plugin internally, although the 'typescript' plugin currently
// returns the string output, rather than writing to a file
filename: this.options.schemaPath,
schemaAst: this.schema,
schema: parse(printSchema(this.schema)),
// Plugins to use
pluginMap: {
typeScript: typeScriptPlugin,
},
// Plugins configurations
plugins: [
{
typeScript: {},
},
],
}).then(wrapSchema)

public generateOperationsCode = async (
nodes: Array<QueryNode | FragmentNode>
) => {
return Promise.all(
nodes.map(async (node) => {
const { value, filename, ...rest } = node
Expand All @@ -117,6 +151,7 @@ export class WebpackPlugin {
enumsAsTypes: true,
skipTypeNameForRoot: true,
skipTypename: true,
namingConvention: 'change-case-all#pascalCase',
},
documents: [{ document: parse(value) }],
// used by a plugin internally, although the 'typescript' plugin currently
Expand Down Expand Up @@ -193,23 +228,24 @@ export class WebpackPlugin {

// -------------------------------------
// Generate code using @graphql-codegen
const codeNodes = await this.generateCode([
...optimizedQueries,
...allFragments,
const [schemaNode, operationNodes] = await Promise.all([
this.generateSchemaCode(),
this.generateOperationsCode([...optimizedQueries, ...allFragments]),
])

// write generated files
await Promise.all(
codeNodes.map(async ({ value, filename: filepath, name }) => {
await Promise.all([
...operationNodes.map(async ({ value, filename: filepath, name }) => {
const filename = join(
dirname(filepath),
'__generated__',
`${name}.graphql.ts`
)

return outputFile(filename, value)
})
)
}),
outputFile(this.options.schemaPath, schemaNode),
])

await fsExtraOutputFile(this.cachePath, serialize(manager))
} catch (err) {
Expand Down