angular、apollo-client、graphQL - Select 来自 graphql 查询的所有字段

angular, apollo-client, graphQL - Select all fields from a graphql query

我用 apollo-client 和 angular4 查询一个 graphql 服务,给它我想通过一个也可以为 null 的数组检索的字段名。如果数组字段为空,我希望我的客户端 return graphQL 方法可用的所有字段名。到现在我必须手写它们。是否可以默认 select 所有字段名?

或者我的代码是否完全糟糕并且有一些处理动态 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;
  }

// ...

提前致谢

您可以先查询所有字段,然后使用结果查询所有字段:

{ __type(name:"Person") {
    fields {
      name
      }  
    }
}