graphql-compose/graphql-compose-json

working with nested/plural fields

lfender6445 opened this issue ยท 3 comments

Given the following json response

export default {
  "geo": [
    {
      "count": "59",
      "geocode": "27.40285,-82.551309",
      "name": "34270, FL",
      "radius": "10",
      "search_type": "ZIP",
      "seopath": "zip/34270-Apartments-For-Rent/",
      "sortfield": "is34270",
      "location_slug": "34270",
      "map_url": "zip=34270"
    }
  ],
  "listing": [
    {
      "propertyname": "342 Ave E",
      "listingid": "LV140083191",
      "listingseopath": "apartments/New-Jersey/Bayonne/342-Ave-E/LV140083191/"
    }
  ]
}

I was hoping for a type tree that might let me do something like this:

query {
  autocomplete(limit: 1) {
    geo {
      count
    }
    listing {
      listingseopath
    }
  }
}

I've thought about using typecomposer to create custom fields / resolution for geo but was wondering if you had ideas about achieving this with other means

This works but returns all fields

query {
  autocomplete() {
    geo 
    listing
  }
}

I thought about this some more and came up with this solution:

/* tslint:disable */

// @ts-ignore
import composeWithJson from 'graphql-compose-json'

import {
  GraphQLList,
} from 'graphql'

const res = {
  "geo": [
    {
      "count": "59",
      "geocode": "27.40285,-82.551309",
      "name": "34270, FL",
      "radius": "10",
      "search_type": "ZIP",
      "sortfield": "is34270",
      "location_slug": "34270",
      "map_url": "zip=34270"
    }
  ],
  "listing": [
    {
      "propertyname": "342 Ave E",
      "listingid": "LV140083191",
    }
  ]
}

const geoTC = composeWithJson('AutocompleteGeo', res.geo[0])
const listingTC = composeWithJson('AutocompleteListing', res.listing[0])

const geo = () => ({
  description: "a collection of AutocompleteGeo location objects",
  type: new GraphQLList(geoTC.getType()),
})

const listing = () => ({
  description: "a collection of AutocompleteListing objects",
  type: new GraphQLList(listingTC.getType()),
})

const mapping = {
  geo,
  listing,
}

return composeWithJson('Autocomplete', mapping)

This gives me granular control over the inner collections of my autocomplete type

nodkz commented

Try to simplify your code with

const geo = () => ({
  description: "a collection of AutocompleteGeo location objects",
  type: [geoTC],
})

const listing = () => ({
  description: "a collection of AutocompleteListing objects",
  type: [listingTC],
})

Or even shorter without description:

const geo = () => [geoTC];

const listing = () => [listingTC];
nodkz commented

๐ŸŽ‰ This issue has been resolved in version 4.1.0 ๐ŸŽ‰

The release is available on:

Your semantic-release bot ๐Ÿ“ฆ๐Ÿš€