官术网_书友最值得收藏!

Advancing the REST API

This API will be far more useful and will provide us with the ability to add data so that the current web data feed is not the only data source.

The sample code in the georestwebservice project (of this chapter) is an updated version of the API with the new recordFeature method in the georestwebservice.dart file:

 @ApiMethod(path: 'record', method: 'POST')
QuakeResponse recordFeature(QuakeRequest request) {
  DaoQuakeAPI quakeAPI = new DaoQuakeAPI();
  quakeAPI.recordFeature(getFeatureAsJSON(request));

  QuakeResponse quakeResponse = new QuakeResponse();
  quakeResponse.result = "1";

  return quakeResponse;
}

This method will use the standard HTTP POST verb in order to receive the input from the client application. As the rpc package wraps the entire method and composes and sends error responses, there is no need for error handling in this method. If, for example, something goes wrong while storing a result in the database, the client will receive an error message.

The following getFeatureAsJSON function, that is found in the helpers.dart file, converts the incoming QuakeRequest object into a JSON string:

String getFeatureAsJSON(QuakeRequest request) {
  String feature = jsonData;
  feature = feature.replaceAll("MAG", request.magnitude.toString());
  feature = feature.replaceFirst("TIME", request.time.toString());
  feature = feature.replaceFirst("LAT", request.latitude.toString());
  feature = feature.replaceFirst("LONG", request.longitude.toString());
  return feature;
}

The jsonData string is a template for the GeoJSON feature. The String class has numerous useful methods that are used to match strings, and these are used to generate the final string that is returned from the function. The replaceAll method is used to replace every occurrence of a string; in this case, for the magnitude that appears as a value and in the text description. The replaceFirst method is used to replace the first occurrence of a string and is used in this function for the values that appear only once in the string.

The following API method's parameter is a simple class that is declared in the same file that contains four fields:

class QuakeRequest {

  @ApiProperty(required: true)
  int time;

  @ApiProperty(required: true)
  double magnitude;

  @ApiProperty(required: true)
  double longitude;

  @ApiProperty(required: true)
  double latitude;
}

The fields are annotated, which allows the rpc package to handle the marshaling of data through the REST interface.

主站蜘蛛池模板: 富蕴县| 永善县| 合山市| 尼勒克县| 鲁甸县| 错那县| 罗江县| 新龙县| 府谷县| 蒲江县| 凌海市| 洱源县| 遂溪县| 广昌县| 安化县| 阳原县| 彭州市| 乡宁县| 云安县| 昌都县| 温州市| 噶尔县| 正定县| 肇源县| 泾川县| 交口县| 洮南市| 舟山市| 富阳市| 盐城市| 泰来县| 鹿邑县| 拜城县| 特克斯县| 马龙县| 万年县| 苗栗县| 赣州市| 肥城市| 平阳县| 舟曲县|