Carapacik / swagger_parser

Dart package that takes an OpenApi definition file and generates REST clients based on retrofit and data classes for your project.
https://pub.dev/packages/swagger_parser
MIT License
103 stars 47 forks source link

Is it possible to change the type depending on the status code? #273

Open manabu0926 opened 1 month ago

manabu0926 commented 1 month ago

Use case

when mutate request return error, I don't know how to handle errors.

I'm assuming that I want to process success in then, and process failure in onError. At that time, I would like to get the error message defined in the response.

Proposal

post:
  tags:
    - DriverApi::Talks
  summary: post Message
  operationId: postTalk
  security:
    - bearerAuth: []
  requestBody:
    required: true
    content:
      application/json:
        schema:
          $ref: "#/components/schemas/talk_create_params"
  responses:
    "201":
      description: "Created"
      content:
        application/json:
          schema:
            $ref: "../../../components/schemas/responses.yml#/created"
    "422":
      description: "Unprocessable Entity Error"
      content:
        application/json:
          schema:
            $ref: "../../../components/schemas/responses.yml#/unprocessable_entity_error" ← define errorMessage(string).

want to write, example,

final api = DriverApiTalkClient(dio);
final body = TalkCreateParams(message: 'test');
await api
    .postTalk(body: body)
    .then((response) => showSnackbar(response.message))
    .onError((_, __, response) {
      if(response.statusCode == 400) {
        showSnackbar(response.errorMessage);
      } else if(response.statusCode == 422) {
        otherHandleError();
      }
});

Sorry if this has already been done. I would be happy if you could teach me how to write it! I think this will solve the redundant writing style that I was dissatisfied with with the previous openapi-generator, so I would be happy if you would consider it!

manabu0926 commented 4 weeks ago

e.g. want to generate, 〇〇_client.g.dart

final _result = await _dio.fetch<Map<String, dynamic>>(_options);
if (_result.statusCode != 200) {  ///← not success statusCode
  throw DioException(
    requestOptions: _options,
    response: _result,
  );
}

call function,


await api.postTalk.then(
  (response) => state.value = response.data.todayShift,
  onError: (Object error) => {
    if (error is DioException)
      {
        print(error.response?.statusCode),
        print(error.response?.data['message']),
      },
  },
  );