简体   繁体   English

在操场上运行的 Graphql_flutter 突变在运行设备/模拟器上不起作用

[英]Graphql_flutter mutation running on playground doesn't work on running device/emulator

During my project development, I'm using flutter with graphql, for testing purpose tried mutation on playground and passed the test, but on device and emulator getting error response with 5xx, I know this is "server side" error but tested same mutation from our webpage and it is working too.在我的项目开发过程中,我将 flutter 与 graphql 一起使用,为了测试目的,在操场上尝试了突变并通过了测试,但是在设备和模拟器上得到错误响应为 5xx,我知道这是“服务器端”错误,但测试了相同的突变我们的网页,它也在工作。 Beside with flutter, I am using following packages:除了 flutter 之外,我还使用以下软件包:

  • equatable: ^1.2.5等价的:^1.2.5
  • gql: ^0.12.4 gql: ^0.12.4
  • graphql: ^4.0.0 graphql:^4.0.0
  • graphql_flutter: ^4.0.1 graphql_flutter:^4.0.1
  • json_annotation: ^3.1.1 json_annotation: ^3.1.1
  • meta: ^1.3.0元:^1.3.0
  • artemis: ^6.18.4阿尔忒弥斯:^6.18.4
  • build_runner: ^1.11.1 build_runner:^1.11.1
  • json_serializable: ^3.5.1 json_serializable: ^3.5.1

Till now on this project, I run almost 10 mutations successfully with this file syntax:到目前为止,在这个项目中,我使用以下文件语法成功运行了近 10 个突变:

  • myproject/我的项目/
    • graphql/图ql/
      • queries/查询/
        • register.graphql -> running well register.graphql -> 运行良好
        • createOffer.graphql -> getting 500 error createOffer.graphql -> 出现 500 错误
      • schema.graphql架构.graphql
    • lib/库/
      • models/楷模/
        • ...generatedModels here.. ...在这里生成模型..
      • views/意见/
        • register.dart注册.dart
        • createOffer.dart createOffer.dart

register.graphql寄存器.graphql

mutation signUp(
    $company_name:String!,
    $email: String!,
    $firstname: String!,
    $lastname: String!,
    $phone: String!,
    $tin_ein_number: String!,
) {
    createShipperUser(
        company_name: $company_name,
        email: $email,
        firstname: $firstname,
        lastname: $lastname,
        phone: $phone,
        tin_ein_number: $tin_ein_number,
    ) {
        id
    }
}

register.dart注册.dart

Widget buildFormBody(BuildContext context) {
    return Mutation(
      options: MutationOptions(
        document: SignUpMutation().document,
        onCompleted: (dynamic resultData) {
          if (resultData != null) {
            onRegistered();
          }
        },
        if (e.linkException != null) {
            showSnackbar(context,
                'Something went wrong, please check your network connection and try again.');
            return;
        }
        final validationErrors = findValidationErrors(
            e.graphqlErrors,
            [
              'firstname',
              'lastname',
              'email',
              'phone',
              'tin_ein_number',
              'company_name',
            ],
          );
          if (validationErrors.isNotEmpty) {
            setState(() {
              firstnameError = validationErrors['firstname'];
              surnameError = validationErrors['lastname'];
              emailError = validationErrors['email'];
              phoneError = validationErrors['phone'];
              if (isTin) {
                einError = null;
                tinError = validationErrors['tin_ein_number'];
              } else {
                einError = validationErrors['tin_ein_number'];
                tinError = null;
              }
              companyError = validationErrors['company_name'];
            });
            //TODO text
            showSnackbar(context, 'Please check entered fields');
          } else if (e.graphqlErrors.isNotEmpty) {
            showSnackbar(
                context, e.graphqlErrors[0].message ?? 'Something went wrong');
          } else {
            showSnackbar(context, 'Something went wrong');
          }
          builder: (runMutation, result) {
           isLoading = result.isLoading;
           return Form( 
             ElevatedButton(
               onPressed: () => onSubmitTap(runMutation),
               child: Text(
                              'Submit',
                              style: TextStyle(
                                  fontSize: 16, fontWeight: FontWeight.w700),
               ),
             )         
           );
        
  void onSubmitTap(RunMutation runMutation) {
    hideKeyboard();
    if (isLoading) {
      return;
    }

    if (formKey.currentState.validate()) {
      formKey.currentState.save();

      setState(() {
        savedPhone = getPhoneMask(savedPhone);
      });

      runMutation(SignUpArguments(
        company_name: savedCompany,
        email: savedEmail,
        phone: savedPhone,
        tin_ein_number: isTin ? 'tin_$savedTin' : 'ein_$savedEin',
        firstname: savedFirstname,
        lastname: savedSurname,
      ).toJson());
    }
  }

And following are mutation getting 500 error.以下是突变得到 500 错误。

createOffer.graphql createOffer.graphql

Mutation(
                      options: MutationOptions(
                        document: CreateShipmentMutation().document,
                        errorPolicy: ErrorPolicy.all,
                        update: (GraphQLDataProxy cache, QueryResult result) {
                          if (result.hasException) {
                            print(result.exception);
                          }
                        },
                        onCompleted: (dynamic resultData) {
                          if (resultData != null) {
                            print('completed');
                            print(resultData);
                            // onCreated();
                          }
                        },
                        onError: (e) {
                          if (e.linkException != null) {
                            showSnackbar(context,
                                'Something went wrong, please check your network connection and try again.');
                            return;
                          }

                          if (e.graphqlErrors.isNotEmpty) {
                            debugPrint(e.graphqlErrors.toString(),
                                wrapWidth: 1024);
                          } else {
                            showSnackbar(context, 'Something went wrong');
                          }
                        },
                      ),
                      builder: (runMutation, result) {
                        isLoading = result.isLoading;
                        return Card(
                          child: ElevatedButton(
                                    onPressed: () => onReviewTap(runMutation),
                                    style: ElevatedButton.styleFrom(
                                        padding:
                                            EdgeInsets.symmetric(vertical: 14)),
                                    child: AnimatedSwitcher(
                                      duration: Duration(milliseconds: 150),
                                      child: result.isLoading
                                          ? Theme(
                                              data: Theme.of(context).copyWith(
                                                  accentColor: Colors.white),
                                              child:
                                                  const ProgressIndicatorSmall(),
                                            )
                                          : Text(
                                              'Review Shipment',
                                              style: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w700),
                                            ),
                                    ),
                                  ),
                        );

void onReviewTap(RunMutation runMutation) {
    final acces = accessories
        .map((accessory) {
          if (accessory.isChecked) {
            return accessory.enumType;
          }
        })
        .where((element) => element != null)
        .toList();
    final stops = isMultipleStops ? items : p2pitems;

    hideKeyboard();
    if (isLoading) {
      return;
    }

    runMutation(CreateShipmentArguments(
      input: OfferInput(
        openPrice: 30,
        shipment: CreateShipmentInput(
          requestedTruckTypes: [
            TruckTypesEnum.dryVan,
          ],
          accessorials: [
            AccessorialsEnum.twicRequired,
            AccessorialsEnum.ppe,
          ],
          trailer: TrailerInput(
            temperatureMax: 0,
            temperatureMin: 0,
            temperatureUnit: TemperatureUnitsEnum.f,
          ),
          items: [
            ItemInput(
              description: "Items description",
              weight: WeightInput(
                weight: 100,
                weightUnit: WeightUnitTypesEnum.lb,
              ),
              units: UnitInput(
                unitCount: 0,
                unitType: ItemUnitTypesEnum.units,
              ),
              handlingPiece: HandlingPieceInput(
                pieceCount: 0,
                pieceType: ItemPieceTypesEnum.pallets,
              ),
            ),
          ],
          shortName: "Dem23",
          loadDescription: "adhjahsdhajsdj",
          routeDistanceMiles: 0.0,
          routeDurationMinutes: 0,
          stops: [
            CreateStopInput(
                appointmentType: AppointmentTypesEnum.alreadyMade,
                startTime: "2021-05-03T00:00:00+02:00",
                type: StopTypesEnum.pickup,
                loadingType: LoadingTypesEnum.live,
                locationInput: LocationInput(
                  locationName: "HOUSTON",
                  coordinates:
                      CoordinatesInput(lat: 29.608774, lng: -95.516164),
                  address: AddressInput(
                      full:
                          "14810 Fairway Pines Dr, Missouri City, TX 77489, USA",
                      city: "Missouri City",
                      state: "TX",
                      street: "Fairway Pines Drive",
                      streetNumber: 14810),
                  operationalContact: ContactInput(
                      contactName: "mr contact",
                      email: "hojayevkoch@gmail.com",
                      phoneNumber: "862615986",
                      notes: "notes lorem ipsum"),
                  schedulingContact: ContactInput(
                      contactName: "mr contact",
                      email: "hojayevkoch@gmail.com",
                      phoneNumber: "862615986",
                      notes: "notes lorem ipsum"),
                )),
            CreateStopInput(
              appointmentType: AppointmentTypesEnum.toBeMade,
              startTime: "2021-05-14T05:13:30+00:00",
              endTime: "2021-04-27T17:35:00+00:00",
              type: StopTypesEnum.dropoff,
              loadingType: LoadingTypesEnum.live,
              locationInput: LocationInput(
                locationName: "COSTCO WHO,WEBSTER,TX,USA",
                coordinates: CoordinatesInput(lat: 29.533604, lng: -95.136843),
                address: AddressInput(
                  full: "1310 Jasmine St, Webster, TX 77598, USA",
                  city: "Webster",
                  state: "TX",
                  street: "Jasmine Street",
                  streetNumber: 1310,
                ),
                operationalContact: ContactInput(
                    contactName: "mr contact",
                    email: "mrtest@gmail.com",
                    phoneNumber: "862615986",
                    notes: "notes lorem ipsum"),
                schedulingContact: ContactInput(
                    contactName: "mr contact",
                    email: "mrtest@gmail.com",
                    phoneNumber: "862615986",
                    notes: "notes lorem ipsum"),
              ),
            ),
          ],
        ),
      ),
    ).toJson());

Following are the hardcodes on playground for createOffer:以下是在 Playground 上用于 createOffer 的硬代码:

mutation CreateShipment (
  $input: OfferInput!
) {
  createOffer(input: $input){
    uuid
    shipper_id
  }
}
#variables
{
  "input": {
    "open_price": 30,
    "shipment": {
      "requested_truck_types": [
        "DRY_VAN"   
      ],
      "accessorials": [
        "TWIC_REQUIRED",
        "SHIPPER_REQUIRES_MASK_GLOVES",
        "PPE"
      ],
      "items": [
        {
          "description": "Items description",
          "handling_piece": {
            "piece_type": "PALLETS",
            "piece_count": 0
          },
          "units": {
            "unit_type": "UNITS",
            "unit_count": 0
          },
          "weight": {
            "weight": 100,
            "weight_unit": "LB"
          }
        }
      ],
      "trailer": {
        "temperature_max": 0,
        "temperature_min": 0,
        "temperature_unit": "F"
      },
      "short_name": "Dem",
      "load_description": "load descriotajj adaksdjad",
      "route_distance_miles": 0.0,
      "route_duration_minutes": 0,
      "stops": [
        {
          "appointment_type": "ALREADY_MADE",
          "start_time": "2021-05-03T00:00:00+02:00",
          "type": "PICKUP",
          "loading_type": "LIVE",
          "location_input": {
            "location_name": "HOUSTON",
            "coordinates": {
              "lat": 29.608774,
              "lng": -95.516164
            },
            "address": {
              "full": "14810 Fairway Pines Dr, Missouri City, TX 77489, USA",
              "city": "Missouri City",
              "state": "TX",
              "street": "Fairway Pines Drive",
                    "street_number" :14810
            },
            "operational_contact": {
              "contact_name" : "mr contact",
                    "email" : "mrtest@gmail.com",
                    "phone_number" : "862615986",
                  "notes" : "notes lorem ipsum"
            },
            "scheduling_contact": {
              "contact_name" : "mr contact",
                    "email" : "mrtest@gmail.com",
                    "phone_number" : "862615986",
                  "notes" : "notes lorem ipsum"
            }
          }
        },
        {
          "appointment_type": "TO_BE_MADE",
          "start_time": "2021-05-14T05:13:30+00:00",
          "end_time": "2021-04-27T17:35:00+00:00",
          "type": "DROPOFF",
          "loading_type": "LIVE",
          "location_input": {
            "location_name": "COSTCO WHO,WEBSTER,TX,USA",
            "coordinates": {
              "lat": 29.533604,
              "lng": -95.136843
            },
            "address": {
              "full": "1310 Jasmine St, Webster, TX 77598, USA",
              "city": "Webster",
              "state": "TX",
              "street": "Jasmine Street",
                    "street_number" :1310
            },
            "operational_contact": {
              "contact_name" : "mr contact",
                    "email" : "hojayevkoch@gmail.com",
                    "phone_number" : "862615986",
                  "notes" : "notes lorem ipsum"
            },
            "scheduling_contact": {
              "contact_name" : "mr contact",
                    "email" : "hojayevkoch@gmail.com",
                    "phone_number" : "862615986",
                  "notes" : "notes lorem ipsum"
            }
          }
        }
      ]
    }
  }
}

and response和回应

{
  "data": {
    "createOffer": {
      "uuid": "933eee0a-8x82-46d6-xxx-018xxxxxxx40",
      "shipper_id": "3"
    }
  },
  "extensions": {
    "lighthouse_subscriptions": {
      "version": 1,
      "channel": null,
      "channels": []
    }
  }
}

to check if working graphql validation, I made mistake on datetime in starttime/endtime and get this:要检查 graphql 验证是否有效,我在开始时间/结束时间的日期时间上犯了错误并得到这个:

{
  "errors": [
    {
      "message": "Variable \"$input\" got invalid value {\"open_price\":30,\"shipment\":{\"requested_truck_types\":[\"DRY_VAN\"],\"accessorials\":[\"TWIC_REQUIRED\",\"SHIPPER_REQUIRES_MASK_GLOVES\",\"PPE\"],\"items\":[{\"description\":\"Items description\",\"handling_piece\":{\"piece_type\":\"PALLETS\",\"piece_count\":0},\"units\":{\"unit_type\":\"UNITS\",\"unit_count\":0},\"weight\":{\"weight\":100,\"weight_unit\":\"LB\"}}],\"trailer\":{\"temperature_max\":0,\"temperature_min\":0,\"temperature_unit\":\"F\"},\"short_name\":\"Dem\",\"load_description\":\"load descriotajj adaksdjad\",\"route_distance_miles\":0,\"route_duration_minutes\":0,\"stops\":[{\"appointment_type\":\"ALREADY_MADE\",\"start_time\":\"2021-05-03T00:00:00\",\"type\":\"PICKUP\",\"loading_type\":\"LIVE\",\"location_input\":{\"location_name\":\"HOUSTON\",\"coordinates\":{\"lat\":29.608774,\"lng\":-95.516164},\"address\":{\"place_id\":\"EjQxNDgxMCBGYWlyd2F5IFBpbmVzIERyLCBNaXNzb3VyaSBDaXR5LCBUWCA3NzQ4OSwgVVNB\",\"full\":\"14810 Fairway Pines Dr, Missouri City, TX 77489, USA\",\"city\":\"Missouri City\",\"state\":\"TX\",\"street\":\"Fairway Pines Drive\",\"street_number\":14810},\"operational_contact\":{\"contact_name\":\"mr contact\",\"email\":\"hojayevkoch@gmail.com\",\"phone_number\":\"862615986\",\"notes\":\"notes lorem ipsum\"},\"scheduling_contact\":{\"contact_name\":\"mr contact\",\"email\":\"hojayevkoch@gmail.com\",\"phone_number\":\"862615986\",\"notes\":\"notes lorem ipsum\"}}},{\"appointment_type\":\"TO_BE_MADE\",\"start_time\":\"2021-05-14T05:13:30+00:00\",\"end_time\":\"2021-04-27T17:35:00+00:00\",\"type\":\"DROPOFF\",\"loading_type\":\"LIVE\",\"location_input\":{\"location_name\":\"COSTCO WHO,WEBSTER,TX,USA\",\"coordinates\":{\"lat\":29.533604,\"lng\":-95.136843},\"address\":{\"full\":\"1310 Jasmine St, Webster, TX 77598, USA\",\"city\":\"Webster\",\"state\":\"TX\",\"street\":\"Jasmine Street\",\"street_number\":1310},\"operational_contact\":{\"contact_name\":\"mr contact\",\"email\":\"hojayevkoch@gmail.com\",\"phone_number\":\"862615986\",\"notes\":\"notes lorem ipsum\"},\"scheduling_contact\":{\"contact_name\":\"mr contact\",\"email\":\"hojayevkoch@gmail.com\",\"phone_number\":\"862615986\",\"notes\":\"notes lorem ipsum\"}}}]}}; Expected type DateTimeTz at value.shipment.stops[0].start_time; \"Data missing\"",
      "extensions": {
        "category": "graphql"
      },
      "locations": [
        {
          "line": 1,
          "column": 25
        }
      ]
    }
  ],
  "extensions": {
    "lighthouse_subscriptions": {
      "version": 1,
      "channel": null,
      "channels": []
    }
  }
}

which means all fields I was sending are correct, I think.这意味着我发送的所有字段都是正确的,我想。 Maybe requested field types are accepting valid input types from me but causing error while working/parsing them, I don't know, I am struggling with this for almost a week and as you can see two hardcodes (flutter/playground) are the same.也许请求的字段类型正在接受我的有效输入类型,但在工作/解析它们时会导致错误,我不知道,我为此苦苦挣扎了将近一个星期,你可以看到两个硬代码(颤振/游乐场)是相同的. My textfields and other inputs are ready but I can't run hardcode first of all:/ btw this is not expired token, for that I got unathorized action error.我的文本字段和其他输入已准备好,但我首先无法运行硬编码:/顺便说一句,这不是过期的令牌,因为我得到了未经授权的操作错误。

Finally we could solve this issue.最后我们可以解决这个问题。 Issue was occuring on backend while parsing data come from my side.解析数据来自我这边时,后端出现问题。 This was the flow of data:这是数据流:

  • user enters data用户输入数据
  • before mutation, flutter parsing data and graphql_flutter mutate突变前,flutter 解析数据和 graphql_flutter 突变
  • then, backend(in our case, php) does fields validation if all are ok, next, if not send validation errors to the client side.然后,如果一切正常,后端(在我们的例子中是 php)会进行字段验证,如果没有,则将验证错误发送到客户端。
  • after all, server starting storing data on db (here is the key point)毕竟,服务器开始在 db 上存储数据(这是关键点)

My issue was occuring on last stage, unnecessary model property was sent null, we get to know this by reading logs in laravel.log, so removing that field and migrate db, finally download and using "new" schema.graphql from playground resolved this issue. My issue was occuring on last stage, unnecessary model property was sent null, we get to know this by reading logs in laravel.log, so removing that field and migrate db, finally download and using "new" schema.graphql from playground resolved this问题。 I hope this will be helpful later:)我希望这对以后有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在真实设备上运行时,地理位置 package 在 flutter 中不起作用 - GeoLocation package doesn't work in flutter while running on a real device Flutter 应用程序在 Android 模拟器上运行,但不在物理设备上(OnePlus 7T) - Flutter app is running on Android Emulator but not on Physical Device (OnePlus 7T) graphql_flutter 突变查询需要返回语句 - 不确定如何添加它 - graphql_flutter mutation query expects return statement - not sure how to add it Flutter 测试模拟 GraphQL 突变未找到存根 - Flutter Test Mock GraphQL mutation doesn't find stub 如何在 graphql_flutter 中重试对 GraphQLError 的请求 - How to retry a request on GraphQLError in graphql_flutter Flutter (graphql_flutter + gql):找到这个候选,但参数不匹配 - Flutter (graphql_flutter + gql): Found this candidate, but the arguments don't match Websocket 重连循环,graphql_flutter - Websocket reconnection loop, graphql_flutter graphql_flutter 返回 LazyCacheMap,built_value deserializeWith JSON String,如何让它们协同工作 - graphql_flutter return LazyCacheMap, built_value deserializeWith JSON String, how to make them work together 使用 graphql_flutter 连接到 Graphql API 时出错 - Error when connecting to Graphql API using graphql_flutter Mac m1 flutter 项目未在 Android 设备或模拟器上运行 - Mac m1 flutter project not running on Android device or emulator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM