diff --git a/packages/gatsby-graphiql-explorer/src/app/__tests__/snippets.js b/packages/gatsby-graphiql-explorer/src/app/__tests__/snippets.js new file mode 100644 index 0000000000000..b6073767a1e11 --- /dev/null +++ b/packages/gatsby-graphiql-explorer/src/app/__tests__/snippets.js @@ -0,0 +1,79 @@ +import { removeQueryName } from "../snippets" +import { stripIndent } from "common-tags" + +describe(`removeQueryName`, () => { + function getFullQuery(startOfQuery) { + return `${startOfQuery} + allMarkdownRemark { + nodes { + excerpt + } + } +}` + } + + it(`{`, () => { + const startOfQuery = `{` + expect(removeQueryName(getFullQuery(startOfQuery))).toMatchInlineSnapshot(` + "{ + allMarkdownRemark { + nodes { + excerpt + } + } + }" + `) + }) + + it(`query {`, () => { + const startOfQuery = `query {` + expect(removeQueryName(getFullQuery(startOfQuery))).toMatchInlineSnapshot(` + "query { + allMarkdownRemark { + nodes { + excerpt + } + } + }" + `) + }) + + it(`query NameOfTheQuery {`, () => { + const startOfQuery = `query NameOfTheQuery {` + expect(removeQueryName(getFullQuery(startOfQuery))).toMatchInlineSnapshot(` + "query { + allMarkdownRemark { + nodes { + excerpt + } + } + }" + `) + }) + + it(`query ($args: String) {`, () => { + const startOfQuery = `query ($args: String) {` + expect(removeQueryName(getFullQuery(startOfQuery))).toMatchInlineSnapshot(` + "query ($args: String) { + allMarkdownRemark { + nodes { + excerpt + } + } + }" + `) + }) + + it(`query NameOfTheQuery ($args: String) {`, () => { + const startOfQuery = `query NameOfTheQuery ($args: String) {` + expect(removeQueryName(getFullQuery(startOfQuery))).toMatchInlineSnapshot(` + "query ($args: String) { + allMarkdownRemark { + nodes { + excerpt + } + } + }" + `) + }) +}) diff --git a/packages/gatsby-graphiql-explorer/src/app/snippets.js b/packages/gatsby-graphiql-explorer/src/app/snippets.js index 611d723064fd8..cb0f6e232c753 100644 --- a/packages/gatsby-graphiql-explorer/src/app/snippets.js +++ b/packages/gatsby-graphiql-explorer/src/app/snippets.js @@ -1,7 +1,15 @@ +export function removeQueryName(query) { + return query.replace( + /^[^{(]+([{(])/, + (_match, openingCurlyBracketsOrParenthesis) => + `query ${openingCurlyBracketsOrParenthesis}` + ) +} + const getQuery = (arg, spaceCount) => { const { operationDataList } = arg const { query } = operationDataList[0] - const anonymousQuery = query.replace(/query\s.+{/gim, `{`) + const anonymousQuery = removeQueryName(query) return ( ` `.repeat(spaceCount) + anonymousQuery.replace(/\n/g, `\n` + ` `.repeat(spaceCount)) @@ -16,13 +24,13 @@ const pageQuery = { generate: arg => `import React from "react" import { graphql } from "gatsby" -const ComponentName = ({ data }) =>
{JSON.stringify(data, null, 4)}
+const Page = ({ data }) =>
{JSON.stringify(data, null, 4)}
export const query = graphql\` ${getQuery(arg, 2)} \` -export default ComponentName +export default Page `, }