Skip to content

Commit

Permalink
add fat measurements to server
Browse files Browse the repository at this point in the history
  • Loading branch information
mucsi96 committed Aug 19, 2023
1 parent 9294488 commit 9ea0a81
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 35 deletions.
16 changes: 7 additions & 9 deletions server/src/main/java/mucsi96/traininglog/weight/Weight.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;

@Data
@Entity
Expand All @@ -20,13 +17,14 @@
@NoArgsConstructor
public class Weight {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@NonNull
@Column(nullable = false)
private ZonedDateTime createdAt;

@Column
private double value;
private double weight;

@Column
private double fatMassWeight;

@Column
private double fatRatio;
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,10 @@ List<WeightMeasurement> weight(
@RequestHeader("X-Timezone") ZoneId zoneId) {
return weightService.getWeight(Optional.ofNullable(period), zoneId).stream().map(measurement -> WeightMeasurement
.builder()
.weight(measurement.getValue())
.date(measurement.getCreatedAt().withZoneSameInstant(zoneId).toOffsetDateTime())
.weight(measurement.getWeight())
.fatRatio(measurement.getFatRatio())
.fatMassWeight(measurement.getFatMassWeight())
.build()).toList();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class WeightService {
private final Clock clock;

public void saveWeight(Weight weight) {
log.info("persisting weight in db with value {}", weight.getValue());
log.info("persisting weight in db with value {}", weight.getWeight());
weightRepository.save(weight);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ private String getMeasureUrl(ZoneId zoneId) {
.fromHttpUrl(withingsConfiguration.getApi().getUri())
.path("/measure")
.queryParam("action", "getmeas")
.queryParam("meastype", 1)
.queryParam("category", 1)
.queryParam("startdate", startTime)
.queryParam("enddate", endTime)
Expand Down Expand Up @@ -71,6 +70,12 @@ private WithingsGetMeasureResponseBody getMeasure(OAuth2AuthorizedClient authori
return response.getBody();
}

private double getMeasurement(List<WithingsMeasure> measures, int type) {
WithingsMeasure measure = measures.stream().filter(m -> m.getType() == type).findFirst().orElseThrow();
double weight = Math.round(measure.getValue() * Math.pow(10, measure.getUnit()) * 100.0) / 100.0;
return weight;
}

private Optional<Weight> getLastMeasureValue(WithingsGetMeasureResponseBody measureResponseBody) {
List<WithingsMeasureGroup> measureGroups = measureResponseBody.getMeasuregrps();

Expand All @@ -86,16 +91,19 @@ private Optional<Weight> getLastMeasureValue(WithingsGetMeasureResponseBody meas
return Optional.empty();
}

WithingsMeasure measure = measures.get(measures.size() - 1);
double weight = Math.round(measure.getValue() * Math.pow(10, measure.getUnit()) * 100.0) / 100.0;
ZonedDateTime createdAt = ZonedDateTime.ofInstant(Instant.ofEpochSecond(measureGroup.getDate()), ZoneOffset.UTC);

return Optional.of(Weight.builder().value(weight).createdAt(createdAt).build());
return Optional.of(
Weight
.builder()
.createdAt(ZonedDateTime.ofInstant(Instant.ofEpochSecond(measureGroup.getDate()), ZoneOffset.UTC))
.weight(getMeasurement(measures, 1))
.fatRatio(getMeasurement(measures, 6))
.fatMassWeight(getMeasurement(measures, 8))
.build());
}

public Optional<Weight> getTodayWeight(OAuth2AuthorizedClient authorizedClient, ZoneId zoneId) {
Optional<Weight> result = getLastMeasureValue(getMeasure(authorizedClient, zoneId));
log.info("Got {}", result.isPresent() ? result.get().getValue() : "null");
log.info("Got {}", result.isPresent() ? result.get().getWeight() : "null");
return result;
}
}
14 changes: 10 additions & 4 deletions server/src/main/resources/api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,19 @@ paths:
title: WeightMeasurement
type: object
required:
- weight
- date
- weight
properties:
weight:
type: number
format: double
date:
type: string
format: date-time
weight:
type: number
format: double
fatRatio:
type: number
format: double
fatMassWeight:
type: number
format: double

7 changes: 4 additions & 3 deletions server/src/main/resources/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ CREATE TABLE IF NOT EXISTS oauth2_authorized_client (
);

CREATE TABLE IF NOT EXISTS weight (
id bigserial NOT NULL,
created_at timestamp NOT NULL,
value float(53),
PRIMARY KEY (id)
weight float(53),
fat_mass_weight float(53),
fat_ratio float(53),
PRIMARY KEY (created_at)
);
Original file line number Diff line number Diff line change
Expand Up @@ -31,27 +31,29 @@ public class WeightControllerTests extends BaseIntegrationTest {
void beforeEach() {
weightRepository.deleteAll();
weightRepository.save(Weight.builder()
.value(108.9)
.weight(108.9)
.createdAt(ZonedDateTime.now(clock).minus(400, ChronoUnit.DAYS))
.build());
weightRepository.save(Weight.builder()
.value(98)
.weight(98)
.createdAt(ZonedDateTime.now(clock).minus(356, ChronoUnit.DAYS))
.build());
weightRepository.save(Weight.builder()
.value(88.3)
.weight(88.3)
.createdAt(ZonedDateTime.now(clock).minus(6, ChronoUnit.DAYS))
.build());
weightRepository.save(Weight.builder()
.value(87.7)
.weight(87.7)
.createdAt(ZonedDateTime.now(clock).minus(5, ChronoUnit.DAYS))
.build());
weightRepository.save(Weight.builder()
.value(87.1)
.weight(87.1)
.fatRatio(31.01)
.fatMassWeight(21.34)
.createdAt(ZonedDateTime.now(clock))
.build());
weightRepository.save(Weight.builder()
.value(87.5)
.weight(87.5)
.createdAt(ZonedDateTime.now(clock).minus(1, ChronoUnit.DAYS))
.build());
}
Expand Down Expand Up @@ -87,9 +89,11 @@ public void returns_today_weight_measurement() throws Exception {
.andReturn().getResponse();

assertThat(JsonPath.parse(response.getContentAsString()).read("$.length()", Integer.class)).isEqualTo(1);
assertThat(JsonPath.parse(response.getContentAsString()).read("$[0].weight", Double.class)).isEqualTo(87.1);
assertThat(JsonPath.parse(response.getContentAsString()).read("$[0].date", String.class))
.isEqualTo("2031-08-22T06:00:00-04:00");
assertThat(JsonPath.parse(response.getContentAsString()).read("$[0].weight", Double.class)).isEqualTo(87.1);
assertThat(JsonPath.parse(response.getContentAsString()).read("$[0].fatRatio", Double.class)).isEqualTo(31.01);
assertThat(JsonPath.parse(response.getContentAsString()).read("$[0].fatMassWeight", Double.class)).isEqualTo(21.34);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public void requests_new_access_token_if_its_expired() throws Exception {
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("withings-authorize.json")));
mockWithingsServer.stubFor(WireMock
.post("/measure?action=getmeas&meastype=1&category=1&startdate=1945137600&enddate=1945224000")
.post("/measure?action=getmeas&category=1&startdate=1945137600&enddate=1945224000")
.willReturn(
WireMock.aResponse()
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
Expand Down Expand Up @@ -265,7 +265,7 @@ public void returns_not_authorized_if_refresh_token_is_invalid() throws Exceptio
public void pulls_todays_weight_from_withings_to_database() throws Exception {
authorizeWithingsOAuth2Client();
mockWithingsServer.stubFor(WireMock
.post("/measure?action=getmeas&meastype=1&category=1&startdate=1945137600&enddate=1945224000")
.post("/measure?action=getmeas&category=1&startdate=1945137600&enddate=1945224000")
.willReturn(
WireMock.aResponse()
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
Expand All @@ -280,8 +280,10 @@ public void pulls_todays_weight_from_withings_to_database() throws Exception {
assertThat(response.getStatus()).isEqualTo(200);
Optional<Weight> weight = weightRepository.findAll().stream().findFirst();
assertThat(weight.isPresent()).isTrue();
assertThat(weight.get().getValue()).isEqualTo(65.76);
assertThat(weight.get().getCreatedAt().format(DateTimeFormatter.ISO_ZONED_DATE_TIME))
.isEqualTo("2020-07-08T22:16:40Z[Etc/UTC]");
assertThat(weight.get().getWeight()).isEqualTo(65.76);
assertThat(weight.get().getFatRatio()).isEqualTo(32.27);
assertThat(weight.get().getFatMassWeight()).isEqualTo(21.76);
}
}
16 changes: 16 additions & 0 deletions server/src/test/resources/__files/withings-measure.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,22 @@
"algo": 3425,
"fm": 1,
"fw": 1000
},
{
"value": 322664,
"type": 6,
"unit": -4,
"algo": 3425,
"fm": 1,
"fw": 1000
},
{
"value": 217634,
"type": 8,
"unit": -4,
"algo": 3425,
"fm": 1,
"fw": 1000
}
],
"comment": "A measurement comment",
Expand Down

0 comments on commit 9ea0a81

Please sign in to comment.