|
1 |
| -# We first transform the JSON result object from REST API the Graphql structure |
2 |
| -# and then map the JSON response to the fields corresponding to the GraphQL type. |
| 1 | +# This example demonstartes mapping a JSON response to the fields of the GraphQL. |
3 | 2 |
|
4 | 3 | type Customer {
|
5 | 4 | cId: ID
|
6 | 5 | cName: String
|
7 | 6 | cAddress: Address
|
8 | 7 | }
|
| 8 | + |
9 | 9 | type Address {
|
10 | 10 | city: String
|
11 |
| - countryRegion: String |
12 |
| - stateProvince: String |
| 11 | + country: String |
| 12 | + state: String |
13 | 13 | street: String
|
14 | 14 | postalCode: String
|
15 | 15 | }
|
16 | 16 |
|
17 | 17 | type Query {
|
18 |
| - customer(id: ID): [Customer] |
| 18 | + # ecmascript generates customer data to simulate a REST api with a JSON response. |
| 19 | + # To verify with a real data source (API or a database) it is required to change the `endpoint` argument on the `@rest` directive. |
| 20 | + # https://stepzen.com/docs/connecting-backends/how-to-connect-a-rest-service |
| 21 | + customerByID(id: ID!): Customer |
19 | 22 | @rest(
|
20 |
| - endpoint: "https://json2api-customers-zlwadjbovq-uc.a.run.app/customers?q=id+eq+$id;" |
21 |
| - # The jq expression transform each element of the array. |
22 |
| - # StepZen takes care of calling jq for each element. |
23 |
| - transforms: [ |
24 |
| - { |
25 |
| - pathpattern: [] |
26 |
| - editor: """ |
27 |
| - jq:.[]|{id,name,cAddress:{street, city, stateProvince, countryRegion}} |
28 |
| - """ |
29 |
| - } |
30 |
| - ] |
| 23 | + endpoint: "stepzen:empty" |
| 24 | + ecmascript: """ |
| 25 | + function transformREST() { |
| 26 | + var id = get('id') |
| 27 | + if (id==1) |
| 28 | + return ({"address":{"city":"Raleigh","country":"USA","postalCode":"54321","state":"NC","street":"101 Main St"},"id":"12345","name":"John Doe"}) |
| 29 | + else |
| 30 | + return ({"address":{"city":"Hyderabad","country":"India","postalCode":"654231","state":"TS","street":"J.N.T.U Colony"},"id":"21345","name":"Siddarth A"}) |
| 31 | + } |
| 32 | + """ |
| 33 | + |
31 | 34 | # mapping from JSON response values to the fields of the GraphQL result.
|
32 |
| - setters: [{ field: "cId", path: "id" }, { field: "cName", path: "name" }] |
| 35 | + setters: [ |
| 36 | + { field: "cId", path: "id" } # cId mapped to 'id' |
| 37 | + { field: "cName", path: "name" } # cName mapped to 'name' |
| 38 | + { field: "cAddress", path: "address" } # cAddress mapped to 'address' |
| 39 | + ] |
33 | 40 | )
|
34 | 41 | }
|
0 commit comments