|
5 | 5 | "errors" |
6 | 6 | "fmt" |
7 | 7 | "net/http" |
| 8 | + "time" |
8 | 9 |
|
9 | 10 | "github.com/oklog/ulid/v2" |
10 | 11 | ) |
@@ -111,18 +112,23 @@ func chairPostCoordinate(w http.ResponseWriter, r *http.Request) { |
111 | 112 | } |
112 | 113 | defer tx.Rollback() |
113 | 114 |
|
| 115 | + createdAt := time.Now() |
| 116 | + |
114 | 117 | chairLocationID := ulid.Make().String() |
115 | 118 | if _, err := tx.ExecContext( |
116 | 119 | ctx, |
117 | | - `INSERT INTO chair_locations (id, chair_id, latitude, longitude) VALUES (?, ?, ?, ?)`, |
118 | | - chairLocationID, chair.ID, req.Latitude, req.Longitude, |
| 120 | + `INSERT INTO chair_locations (id, chair_id, latitude, longitude, created_at) VALUES (?, ?, ?, ?, ?)`, |
| 121 | + chairLocationID, chair.ID, req.Latitude, req.Longitude, createdAt, |
119 | 122 | ); err != nil { |
120 | 123 | writeError(w, http.StatusInternalServerError, err) |
121 | 124 | return |
122 | 125 | } |
123 | 126 |
|
124 | | - location := &ChairLocation{} |
125 | | - if err := tx.GetContext(ctx, location, `SELECT * FROM chair_locations WHERE id = ?`, chairLocationID); err != nil { |
| 127 | + if _, err := tx.ExecContext( |
| 128 | + ctx, |
| 129 | + `UPDATE chairs SET total_distance = total_distance + (SELECT IFNULL(ABS(latitude - LAG(latitude) OVER (PARTITION BY chair_id ORDER BY created_at)) + ABS(longitude - LAG(longitude) OVER (PARTITION BY chair_id ORDER BY created_at)),0) AS distance FROM chair_locations WHERE chair_id = ? ORDER BY created_at DESC LIMIT 1), total_distance_updated_at = ? WHERE id = ?`, |
| 130 | + chair.ID, createdAt, chair.ID, |
| 131 | + ); err != nil { |
126 | 132 | writeError(w, http.StatusInternalServerError, err) |
127 | 133 | return |
128 | 134 | } |
@@ -162,7 +168,7 @@ func chairPostCoordinate(w http.ResponseWriter, r *http.Request) { |
162 | 168 | } |
163 | 169 |
|
164 | 170 | writeJSON(w, http.StatusOK, &chairPostCoordinateResponse{ |
165 | | - RecordedAt: location.CreatedAt.UnixMilli(), |
| 171 | + RecordedAt: createdAt.UnixMilli(), |
166 | 172 | }) |
167 | 173 | } |
168 | 174 |
|
|
0 commit comments