A returned data object looks like the following:
{
data: {
posts: {
edges: [
{
post: {
id: "1",
title: "Foo"
}
},
{
post: {
id: "2",
title: "Bar"
}
}
]
}
}
}
This is based on the following query:
query MyQuery {
posts {
edges {
post: node {
id
title
}
}
}
}
This works and I can use it, but I’m having to create nested interfaces, unfortunately.
Question: Can I either simplify the returned results OR transform them with JavaScript map()
?
Ideally, I’d like for the GQL response (or resulting object) to be like:
{
data: {
posts: [
{
id: "1",
title: "Foo"
},
{
id: "2",
title: "Bar"
}
]
}
}
Note: I do not have the ability to update the server-side GraphQL schema. The solution must be client/consumer side.
Thanks!
EDIT
Adding my Angular/TS code that calls and processes the GraphQL...
post.service.ts
import { Injectable } from '@angular/core';
import { Apollo, gql } from 'apollo-angular';
import { map, Observable } from 'rxjs';
import { GraphQLResponse } from 'src/app/core/types/graphQLResponse';
import { Post } from '../models/post';
export interface PostResponse {
edges: Post[]
pageInfo: {
startCursor: string
hasPreviousPage: boolean
hasNextPage: boolean
endCursor: string
}
}
export const getPostsQuery = gql`
query getPostsQuery {
posts {
edges {
post: node {
id
title
date
uri
categories {
edges {
category: node {
id
name
uri
}
}
}
}
cursor
}
pageInfo {
startCursor
hasPreviousPage
hasNextPage
endCursor
}
}
}
`;
@Injectable({
providedIn: 'root'
})
export class PostService {
constructor(private apollo: Apollo) { }
public getPosts(): Observable<PostResponse> {
return this.apollo.query<GraphQLResponse<'posts', PostResponse>>({
query: getPostsQuery
}).pipe(map(resp => resp.data.posts));
}
}
model/post.ts
interface CategoryNode {
id: string;
name: string;
uri: string;
}
interface Category {
category: CategoryNode;
}
interface CategoryEdges{
edges: Category[];
}
interface PostNode {
id: string;
title: string;
date: string;
uri: string;
categories: CategoryEdges;
}
export interface Post {
article: PostNode;
cursor: string;
}
As you can see, way too many nested interfaces.
Actual sample response (used for unit testing)
{
data: {
posts: {
edges : [
{
post: {
id: "cG9zdDoxMjc=",
title: "Lorem Ipsum",
date: "2022-01-06T22:00:53",
uri: "\/2022\/01\/06\/lorem-ipsum\/",
categories: {
edges: [
{
category: {
id: "dGVybToy",
name: "General",
uri: "\/category\/general\/"
}
}
]
}
},
cursor: "YXJyYXljb25uZWN0aW9uOjEyNw=="
},
{
post: {
id: "cG9zdDoxMjc=",
title: "Lorem Ipsum",
date: "2022-01-06T22:00:53",
uri: "\/2022\/01\/06\/lorem-ipsum\/",
categories: {
edges: [
{
category: {
id: "dGVybToy",
name: "General",
uri: "\/category\/general\/"
}
},
{
category: {
id: "dGVybToy",
name: "General",
uri: "\/category\/general\/"
}
}
]
}
},
cursor: "YXJyYXljb25uZWN0aW9uOjEyNw=="
},
],
pageInfo: {
startCursor: "YXJyYXljb25uZWN0aW9uOjEyNw==",
hasPreviousPage: false,
hasNextPage: false,
endCursor: "YXJyYXljb25uZWN0aW9uOjEyNw=="
}
}
}
};