json-to-graphql-query icon indicating copy to clipboard operation
json-to-graphql-query copied to clipboard

Feature request: Field aliases

Open komakino opened this issue 4 years ago • 3 comments

Support for aliased fields would be great. The natural format would of course be to set the alias as the property value instead of true.

const query = {
  query: {
    fruits: {
      name: true,
      colour: 'color',
      flavour: 'flavor'
    }
  }
}

should result in:

{
  query: {
    fruits {
      name
      colour: 'color'
      flavour: 'flavor'
    }
  }
}

I do realize however that that would introduce breaking changes for people using truthy values.

komakino avatar Jun 04 '20 22:06 komakino

We support aliased queries via __aliasFor. One option could be to support this lower down the tree too, e.g.:

const query = {
  query: {
    fruits: {
      name: true,
      colour: { __aliasFor: 'color'},
      flavour: { __aliasFor: 'flavor'}
    }
  }
}

becomes

{
  query: {
    fruits {
      name
      colour: color
      flavour: flavor
    }
  }
}

(I presume you meant without the quotes in the graphql)

Thoughts?

I guess this would need a new major release, to be safe :)

dupski avatar Jun 06 '20 11:06 dupski

Sounds great @dupski 🔥

Perhaps if a object is given, we can use new behaviour? So using aliases is opt-in, leaving current behaviour as is if you use a Boolean.

notrab avatar Oct 14 '20 23:10 notrab

Hey, just gave the solution proposed by @dupski a go after checking the source. Unless I've misunderstood the initial issue, it looks like it already works?

For example the JS:

const query = {
    query: {
      __name: "SEARCH",
      __variables: {
        queryString: "String!",
      },
      search: {
        __args: {
          query: new VariableType("queryString"),
        },
        objects: {
          __on: {
            __typeName: "Episode",
            testTitle: {
              __aliasFor: "title",
            },
          },
        },
      },
    },
  };

  const graphQLQuery = jsonToGraphQLQuery(query);

Outputs this query:

query SEARCH($queryString: String!) {
  search(query: $queryString) {
    objects {
      ... on Episode {
        testTitle: title
      }
    }
  }
}

("json-to-graphql-query": "^2.2.4",)

james-wallis avatar Jan 04 '23 14:01 james-wallis