我使用apollo-client和angular4查询graphql服务,为它提供我想要通过也可以为null的数组检索的字段名。如果Array字段为null,我希望我的客户端返回graphQL方法可用的所有字段名。到现在为止我必须手工编写。默认情况下是否可以选择所有字段名?
或者我的代码完全不好,并且有一些最佳实践来处理动态graphql查询?
示例到这里:
//...
function fieldsToModel(fields: Array<any>, output: string): string {
for (const field in fields) {
if (typeof fields[field] !== 'object') {
output += fields[field].toString() + ',';
} else {
if (Object.keys(fields[field])[0] !== undefined) {
output += Object.keys(fields[field])[0] + '{' + fieldsToModel(fields[field][Object.keys(fields[field])[0]], '') + '},';
}
}
}
return output;
}
// ...
public GetPersons(
personId: number, repId: number, fields: Array<any> = null): Observable<PersonModel> {
fields = fields !== null ? fields : [
'id', '', 'firstname', 'repId', 'lastname', 'sex',
{ 'adress': ['street', 'zip', 'city'] },'birthday'];
const head: String = `query GetPersons($repId:String, $personId:String, $Token:String)
{ viewer { GetPersons(repId: $repId, personId: $personId, Token: $Token) {`;
let body = '';
body = fieldsToModel(fields, body);
const foot: String = '}}}';
const query = head + body + foot;
return this._apollo.watchQuery<any>({
query: gql`${query}`,
variables: {
repID: Id.toString(),
personId: personId.toString(),
Token: environment.Secret
},
})
.map(result => this._processGetPerson(result))
.catch((response_: any) => {
try {
return this._processGetPerson(response_);
} catch (e) {
return <Observable<PersonModel>><any>Observable.throw(e);
}
});
}
private _processGetPerson(result: any): any {
if (result.graphQLErrors) {
return Observable.throw(result);
}
const person = new PersonModel();
if (result.data && result.data.viewer && result.data.viewer.GetPerson) {
person.init(result.data.viewer.GetPerson);
}
return person;
}
// ...
提前谢谢
答案 0 :(得分:0)
您可以先查询所有字段,然后使用结果查询所有字段:
{ __type(name:"Person") {
fields {
name
}
}
}