FLUTTER ECOSYSTEM

ihorbokov/graphql_2_rest

모든 HTTP 클라이언트를 사용하여 요청을 수행하기 위해 GraphQL 쿼리를 REST로 변환하는 간단한 방법입니다.

graphql_2_rest 프로젝트 이미지
Stars
3
Forks
1
최근 푸시(UTC)
2024. 10. 6.
프로젝트 상태
활성
Ihor Bokov GitHub avatar
GITHUB User

Ihor Bokov ↗

Crazy Flutter Developer

Ukraine
언어DartSwiftKotlinObjective-C

이 저장소가 배포한 패키지

사용 중인 의존성

의존성 목록 1 개

원본 README

아래는 영문 원문 스냅샷입니다. 최신 내용은 GitHub에서 확인하세요.

README 펼치기 / 접기

GraphQL to REST

Pub style: very good analysis License: MIT

A lightweight library for converting GraphQL queries into REST format, enabling the use of any HTTP client for executing requests.

Usage

To work effectively with the graphql_2_rest library, you primarily need to use two key components: GraphQLQueryPayload and GraphQLQueryBuilder.

  1. GraphQLQueryPayload is responsible for providing the arguments and input models to be used in a GraphQL query. For example, if you have queries like:
const queryA = '''query {
  user(age: %age, firstName: %firstName) {
    first_name
    last_name
    site {
      site_name
    }
  }
}''';

const queryB = '''query {
  user(@userInput) {
    first_name
    last_name
    site {
      site_name
    }
  }
}''';

then you need to create the following GraphQLQueryPayloads with arguments or/and inputs:

class UserQueryPayloadA with GraphQLQueryPayload {
  const UserQueryPayloadA(
    this.age,
    this.firstName,
  );

  final int age;
  final String firstName;

  @override
  Map<String, dynamic> get arguments {
    return {
      'age': age,
      'firstName': firstName,
    };
  }
}

class UserQueryPayloadB with GraphQLQueryPayload {
  const UserQueryPayloadB(
    this.age,
    this.firstName,
  );

  final int age;
  final String firstName;

  @override
  Map<String, Map<String, dynamic>> get inputs {
    return {
      'userInput': {
        'age': age,
        'firstName': firstName,
      },
    };
  }
}
  1. GraphQLQueryBuilder automatically replaces all argument placeholders in the query using values provided by the GraphQLQueryPayload. By default, GraphQLQueryBuilder uses the following prefixes:
  • % for arguments
  • @ for input models

These default prefixes can be customized by specifying different values for argumentPrefix and inputPrefix when creating an instance of the class.

After building the query, you can use any HTTP client to perform the request, but keep in mind that the request must use the POST method:

final dio = Dio(BaseOptions(baseUrl: 'https://endpoint/'));

final queryBuilder = GraphQLQueryBuilder(
  transformer: (query) => query.replaceAll(RegExp(r'\s+'), ' ').trim(),
);

dio.post<dynamic>(
  'graphql/',
  data: queryBuilder.build(
    queryA, //or queryB
    UserQueryPayloadA(27, 'John'), //or UserQueryPayloadB(27, 'John')
  ),
);