I am writing a resolver to fetch data from REST api to graphql backend function using typescript and type-graphql.The issue I am facing is I am getting data from API with all props but I want to return only selected fields in front end. How to return only selected fields?
Here is my scenario. I have react app as front end. I will write all graphql queries in fronetend app. There is apollo client in front end which connects to graphql in backend. Backend is node app written in typescript. My backend fetches data from rest api and serves to front end via apollo server. We use type-graphql in backend
Here in this question I have doubts for backend.
I have following type (defined in backend as personInfo.ts)
import { ObjectType, Field } from "type-graphql";
@ObjectType("PersonInfo")
export class PersonInfo {
@Field({ nullable: true }) firstName: string;
@Field({ nullable: true }) lastName: string;
@Field({ nullable: true }) registrationNo: string;
@Field({ nullable: true }) personCode: string;
@Field({ nullable: true }) personCapabilities: string;
}
I am using above type in my resolver like below: (defined in backend as personInfoResolver.ts) This graphql resolver will fetch data from rest api using function written in next part. This function has issue as stated in code below.
import { Query, Resolver, Arg } from "type-graphql";
import { PersonInfo } from "../types";
import { GetPersonInfo } from "./api/helpers";
@Resolver((of) => PersonInfo)
export class PersonInfoResolver {
@Query((returns) => PersonInfo, { nullable: true })
async PersonInfo(@Arg("serialNo") serialNo: string) {
console.log(await GetPersonInfo(serialNo)); //<--this logs full object received from api with all the fields
return await GetPersonInfo(serialNo); //when queried from graphql playground, i get null for selected values even if previous line prints all data
}
}
Here is function to get data in api helper (Defined in backend to connect to api and get data.) WOrks fine and gets all objects from rest api.
export const GetPersonInfo = async (serialNo: string) => {
var personInfoURL = "url" + serialNo;
if (!serialNo) {
return "";
}
const response = await posApi
.get(personInfoURL)
.then(function (response) {
return response.data;
})
.catch(function (error) {});
const data = await response;
return data;
};
I am testing above code using graphql playground using following query.
{
PersonInfo(serialNo:"201123030"){
firstName
lastName
registrationNo
registrationNo
personCapabilities
}
}