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): Throw Typegen errors & add IGatsbyImageData to output #35683

Merged
merged 9 commits into from
May 19, 2022
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
20 changes: 15 additions & 5 deletions packages/gatsby-cli/src/structured-errors/error-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,21 +262,21 @@ const errors = {
${context.sourceMessage}

This can happen if you e.g. accidentally added { } to the field "${context.fieldName}". If you didn't expect "${context.fieldName}" to be of type "${context.fieldType}" make sure that your input source and/or plugin is correct.
However, if you expect "value" to exist, the field might be accessible in another subfield. Please try your query in GraphiQL and use the GraphiQL explorer to see which fields you can query and what shape they have.
However, if you expect "value" to exist, the field might be accessible in another subfield. Please try your query in GraphiQL.

It is recommended to explicitly type your GraphQL schema if you want to use optional fields. This way you don't have to add the mentioned
"dummy content". Visit our docs to learn how you can define the schema for "${context.type}":
https://www.gatsbyjs.com/docs/reference/graphql-data-layer/schema-customization#creating-type-definitions`,
It is recommended to explicitly type your GraphQL schema if you want to use optional fields.`,
type: Type.GRAPHQL,
level: Level.ERROR,
category: ErrorCategory.USER,
docsUrl: `https://gatsby.dev/creating-type-definitions`,
},
"85923": {
text: (context): string =>
`There was an error in your GraphQL query:\n\n${context.sourceMessage}\n\nIf you don't expect "${context.field}" to exist on the type "${context.type}" it is most likely a typo.\nHowever, if you expect "${context.field}" to exist there are a couple of solutions to common problems:\n\n- If you added a new data source and/or changed something inside gatsby-node.js/gatsby-config.js, please try a restart of your development server\n- The field might be accessible in another subfield, please try your query in GraphiQL and use the GraphiQL explorer to see which fields you can query and what shape they have\n- You want to optionally use your field "${context.field}" and right now it is not used anywhere. Therefore Gatsby can't infer the type and add it to the GraphQL schema. A quick fix is to add at least one entry with that field ("dummy content")\n\nIt is recommended to explicitly type your GraphQL schema if you want to use optional fields. This way you don't have to add the mentioned "dummy content". Visit our docs to learn how you can define the schema for "${context.type}":\nhttps://www.gatsbyjs.com/docs/reference/graphql-data-layer/schema-customization#creating-type-definitions`,
`There was an error in your GraphQL query:\n\n${context.sourceMessage}\n\nIf you don't expect "${context.field}" to exist on the type "${context.type}" it is most likely a typo. However, if you expect "${context.field}" to exist there are a couple of solutions to common problems:\n\n- If you added a new data source and/or changed something inside gatsby-node/gatsby-config, please try a restart of your development server.\n- You want to optionally use your field "${context.field}" and right now it is not used anywhere.\n\nIt is recommended to explicitly type your GraphQL schema if you want to use optional fields.`,
type: Type.GRAPHQL,
level: Level.ERROR,
category: ErrorCategory.USER,
docsUrl: `https://gatsby.dev/creating-type-definitions`,
},
"85924": {
text: (context): string =>
Expand Down Expand Up @@ -713,6 +713,16 @@ const errors = {
type: Type.COMPILATION,
category: ErrorCategory.USER,
},
"12100": {
text: (
context
): string => `There was an error while trying to generate TS types from your GraphQL queries:

${context.sourceMessage}`,
level: Level.ERROR,
type: Type.GRAPHQL,
category: ErrorCategory.USER,
},
}

export type ErrorId = string | keyof typeof errors
Expand Down
1 change: 1 addition & 0 deletions packages/gatsby-plugin-image/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"common-tags": "^1.8.2",
"fs-extra": "^10.1.0",
"gatsby-core-utils": "^3.15.0-next.1",
"gatsby-plugin-utils": "^3.9.0-next.2",
"objectFitPolyfill": "^2.3.5",
"prop-types": "^15.8.1"
},
Expand Down
5 changes: 3 additions & 2 deletions packages/gatsby-plugin-image/src/resolver-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
ObjectTypeComposerFieldConfigAsObjectDefinition,
ObjectTypeComposerArgumentConfigMapDefinition,
} from "graphql-compose"
import { hasFeature } from "gatsby-plugin-utils"
import type { ISharpGatsbyImageArgs, IImageSizeArgs } from "./image-utils"

export const ImageFormatType: EnumTypeComposerAsObjectDefinition = {
Expand Down Expand Up @@ -74,7 +75,7 @@ export function getGatsbyImageResolver<TSource, TContext, TArgs>(
IGatsbyImageResolverArgs & TArgs
> {
return {
type: `JSON!`,
type: hasFeature(`graphql-typegen`) ? `GatsbyImageData!` : `JSON!`,
args: {
layout: {
type: ImageLayoutType.name,
Expand Down Expand Up @@ -166,7 +167,7 @@ export function getGatsbyImageFieldConfig<TSource, TContext, TArgs>(
IGatsbyImageFieldArgs & TArgs
> {
return {
type: `JSON!`,
type: hasFeature(`graphql-typegen`) ? `GatsbyImageData!` : `JSON!`,
args: {
layout: {
type: ImageLayoutType.name,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { hasFeature } from "../../has-feature"
import { generateImageUrl } from "../utils/url-generator"
import { getImageFormatFromMimeType } from "../utils/mime-type-helpers"
import { stripIndent } from "../utils/strip-indent"
Expand Down Expand Up @@ -260,7 +261,7 @@ export function generateGatsbyImageFieldConfig(
IGatsbyImageDataArgs
> {
return {
type: `JSON`,
type: hasFeature(`graphql-typegen`) ? `GatsbyImageData!` : `JSON`,
description: `Data used in the <GatsbyImage /> component. See https://gatsby.dev/img for more info.`,
args: {
layout: {
Expand Down
2 changes: 1 addition & 1 deletion packages/gatsby-plugin-utils/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* These types are duplicated from packages/gatsby/src/bootstrap/load-plugins/types.ts
* If you edit this file, make sure to edit that file too!!!
* They are duplicate to avoid a circular dependency between gatsby-plugin-utils <=> gatsby <=> gatsby-plugin-utils
* See gatsbyjs/gatsby#27578 and ping @laurieontech or @mxstbr if you have any questions
* See gatsbyjs/gatsby#27578
*/

export interface IRawSiteConfig {
Expand Down
1 change: 1 addition & 0 deletions packages/gatsby-transformer-sharp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"bluebird": "^3.7.2",
"common-tags": "^1.8.2",
"fs-extra": "^10.1.0",
"gatsby-plugin-utils": "^3.9.0-next.2",
"probe-image-size": "^7.2.3",
"semver": "^7.3.7",
"sharp": "^0.30.3"
Expand Down
5 changes: 4 additions & 1 deletion packages/gatsby-transformer-sharp/src/customize-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const {
traceSVG,
generateImageData,
} = require(`gatsby-plugin-sharp`)
const { hasFeature } = require(`gatsby-plugin-utils`)

const sharp = require(`./safe-sharp`)
const fs = require(`fs-extra`)
Expand Down Expand Up @@ -407,7 +408,9 @@ const imageNodeType = ({
cache,
}) => {
return {
type: new GraphQLNonNull(GraphQLJSON),
type: hasFeature(`graphql-typegen`)
? `GatsbyImageData!`
: new GraphQLNonNull(GraphQLJSON),
args: {
layout: {
type: ImageLayoutType,
Expand Down
2 changes: 1 addition & 1 deletion packages/gatsby/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { GraphQLOutputType } from "graphql"
import { PluginOptionsSchemaJoi, ObjectSchema } from "gatsby-plugin-utils"
import { IncomingMessage, ServerResponse } from "http"

export type AvailableFeatures = "image-cdn"
export type AvailableFeatures = "image-cdn" | "graphql-typegen"

export {
default as Link,
Expand Down
1 change: 1 addition & 0 deletions packages/gatsby/scripts/__tests__/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ it("generates the expected api output", done => {
},
"features": Array [
"image-cdn",
"graphql-typegen",
],
"node": Object {
"createPages": Object {},
Expand Down
2 changes: 1 addition & 1 deletion packages/gatsby/scripts/output-api-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async function outputFile() {
}, {})

/** @type {Array<import("../index").AvailableFeatures>} */
output.features = ["image-cdn"];
output.features = ["image-cdn", "graphql-typegen"];

return fs.writeFile(
path.resolve(OUTPUT_FILE_NAME),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ interface RemoteFile {
fit: RemoteFileFit = COVER
cropFocus: [RemoteFileCropFocus]
quality: Int = 75
): JSON
): GatsbyImageData!
}

type File implements Node @dontInfer {
Expand Down Expand Up @@ -582,7 +582,7 @@ interface RemoteFile {
fit: RemoteFileFit = COVER
cropFocus: [RemoteFileCropFocus]
quality: Int = 75
): JSON
): GatsbyImageData!
}

type File implements Node @dontInfer {
Expand Down Expand Up @@ -981,7 +981,7 @@ interface RemoteFile {
fit: RemoteFileFit = COVER
cropFocus: [RemoteFileCropFocus]
quality: Int = 75
): JSON
): GatsbyImageData!
}

type File implements Node @dontInfer {
Expand Down
2 changes: 2 additions & 0 deletions packages/gatsby/src/schema/schema-composer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { SchemaComposer, GraphQLJSON } from "graphql-compose"
import { addDirectives, GraphQLFieldExtensionDefinition } from "./extensions"
import { GraphQLDate } from "./types/date"
import { IGatsbyResolverContext } from "./type-definitions"
import { GatsbyImageDataScalar } from "./types/media"
import { getNodeInterface } from "./types/node-interface"
import { getOrCreateRemoteFileInterface } from "./types/remote-file-interface"

Expand All @@ -19,6 +20,7 @@ export const createSchemaComposer = <TSource, TArgs>({

schemaComposer.add(GraphQLDate)
schemaComposer.add(GraphQLJSON)
schemaComposer.add(GatsbyImageDataScalar)
addDirectives({ schemaComposer, fieldExtensions })
return schemaComposer
}
1 change: 1 addition & 0 deletions packages/gatsby/src/schema/types/built-in-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ export const builtInScalarTypeNames = [
`Int`,
`JSON`,
`String`,
`GatsbyImageData`,
]

export const internalTypeNames = [
Expand Down
5 changes: 5 additions & 0 deletions packages/gatsby/src/schema/types/media.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { GraphQLScalarType } from "graphql"

export const GatsbyImageDataScalar = new GraphQLScalarType({
name: `GatsbyImageData`,
})
15 changes: 12 additions & 3 deletions packages/gatsby/src/services/graphql-typegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,18 @@ export async function graphQLTypegen({

const { schema, definitions } = store.getState()

await writeGraphQLSchema(directory, schema)
await writeGraphQLFragments(directory, definitions)
await writeTypeScriptTypes(directory, schema, definitions)
try {
await writeGraphQLSchema(directory, schema)
await writeGraphQLFragments(directory, definitions)
await writeTypeScriptTypes(directory, schema, definitions)
} catch (err) {
activity.panicOnBuild({
id: `12100`,
context: {
sourceMessage: err,
},
})
}

activity.end()
}
24 changes: 21 additions & 3 deletions packages/gatsby/src/state-machines/develop/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,16 @@ export const schemaTypegen: ActionFunction<

context.reporter!.verbose(`Re-Generating schema.graphql`)

await writeGraphQLSchema(directory, schema)
try {
await writeGraphQLSchema(directory, schema)
} catch (err) {
context.reporter!.panicOnBuild({
id: `12100`,
context: {
sourceMessage: err,
},
})
}
}

export const definitionsTypegen: ActionFunction<
Expand All @@ -220,8 +229,17 @@ export const definitionsTypegen: ActionFunction<

context.reporter!.verbose(`Re-Generating fragments.graphql & TS Types`)

await writeGraphQLFragments(directory, definitions)
await writeTypeScriptTypes(directory, schema, definitions)
try {
await writeGraphQLFragments(directory, definitions)
await writeTypeScriptTypes(directory, schema, definitions)
} catch (err) {
context.reporter!.panicOnBuild({
id: `12100`,
context: {
sourceMessage: err,
},
})
}
}

export const buildActions: ActionFunctionMap<IBuildContext, AnyEventObject> = {
Expand Down
4 changes: 2 additions & 2 deletions packages/gatsby/src/utils/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,8 +240,8 @@ const activeFlags: Array<IFlag> = [
env: `GATSBY_GRAPHQL_TYPEGEN`,
command: `develop`,
telemetryId: `GraphQLTypegen`,
description: `A built-in way for automatic TypeScript type generation and better GraphQL IntelliSense. See https://github.com/gatsbyjs/gatsby/discussions/35420 for more details.`,
experimental: true,
description: `More easily incorporate content into your pages through automatic TypeScript type generation and better GraphQL IntelliSense. See https://github.com/gatsbyjs/gatsby/discussions/35420 for more details.`,
experimental: false,
noCI: true,
testFitness: (): fitnessEnum => true,
},
Expand Down
4 changes: 1 addition & 3 deletions packages/gatsby/src/utils/graphql-typegen/ts-codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const DEFAULT_TYPESCRIPT_CONFIG: Readonly<TypeScriptPluginConfig> = {
scalars: {
Date: `string`,
JSON: `Record<string, unknown>`,
GatsbyImageData: `import('gatsby-plugin-image').IGatsbyImageData`,
},
// import type {} syntax is nicer
useTypeImports: true,
Expand Down Expand Up @@ -121,8 +122,6 @@ export async function writeTypeScriptTypes(
}
})

const isVerbose = process.env.gatsby_log_level === `verbose`

const codegenOptions: Omit<Types.GenerateOptions, "plugins" | "pluginMap"> = {
// @ts-ignore - Incorrect types
schema: undefined,
Expand All @@ -139,7 +138,6 @@ export async function writeTypeScriptTypes(
skipTypename: true,
flattenGeneratedTypes: true,
},
skipDocumentsValidation: !isVerbose,
}

const result = await codegen({
Expand Down