-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.boxes.$deviceId.data.$sensorId.ts
More file actions
259 lines (239 loc) · 8.78 KB
/
api.boxes.$deviceId.data.$sensorId.ts
File metadata and controls
259 lines (239 loc) · 8.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import { type Params, type LoaderFunction, type LoaderFunctionArgs } from "react-router";
import { type TransformedMeasurement, transformOutliers } from "~/lib/outlier-transform";
import { getMeasurements } from "~/models/sensor.server";
import { type Measurement } from "~/schema";
import { convertToCsv } from "~/utils/csv";
import { parseDateParam, parseEnumParam } from "~/utils/param-utils";
import { StandardResponse } from "~/utils/response-utils";
/**
* @openapi
* /boxes/{deviceId}/data/{sensorId}:
* get:
* tags:
* - Sensors
* summary: Get up to 10000 measurements from a sensor for a specific time frame
* description: Get up to 10000 measurements from a sensor for a specific time frame, parameters `from-date` and `to-date` are optional. If not set, the last 48 hours are used. The maximum time frame is 1 month. If `download=true` `Content-disposition` headers will be set. Allows for JSON or CSV format.
* parameters:
* - in: path
* name: deviceId
* required: true
* schema:
* type: string
* description: the ID of the senseBox you are referring to
* - in: path
* name: sensorId
* required: true
* schema:
* type: string
* description: the ID of the sensor you are referring to
* - in: query
* name: outliers
* required: false
* schema:
* type: string
* enum:
* - replace
* - mark
* description: Specifying this parameter enables outlier calculation which adds a new field called `isOutlier` to the data. Possible values are "mark" and "replace".
* - in: query
* name: outlier-window
* required: false
* schema:
* type: integer
* minimum: 1
* maximum: 50
* default: 15
* description: Size of moving window used as base to calculate the outliers.
* - in: query
* name: from-date
* required: false
* schema:
* type: string
* description: RFC3339Date
* format: date-time
* description: "Beginning date of measurement data (default: 48 hours ago from now)"
* - in: query
* name: to-date
* required: false
* schema:
* type: string
* descrption: TFC3339Date
* format: date-time
* description: "End date of measurement data (default: now)"
* - in: query
* name: format
* required: false
* schema:
* type: string
* enum:
* - json
* - csv
* default: json
* description: "Can be 'json' (default) or 'csv' (default: json)"
* - in: query
* name: download
* required: false
* schema:
* type: boolean
* description: if specified, the api will set the `content-disposition` header thus forcing browsers to download instead of displaying. Is always true for format csv.
* - in: query
* name: delimiter
* required: false
* schema:
* type: string
* enum:
* - comma
* - semicolon
* default: comma
* description: "Only for csv: the delimiter for csv. Possible values: `semicolon`, `comma`. Per default a comma is used. Alternatively you can use separator as parameter name."
* responses:
* 200:
* description: Success
* content:
* application/json:
* schema:
* type: array
* example: '[{"sensor_id":"6649b23072c4c40007105953","time":"2025-11-06 23:59:57.189+00","value":4.78,"location_id":"5752066"},{"sensor_id":"6649b23072c4c40007105953","time":"2025-11-06 23:57:06.03+00","value":4.13,"location_id":"5752066"}]'
* text/csv:
* example: "createdAt,value
* 2023-09-29T08:06:13.254Z,6.38
* 2023-09-29T08:06:12.312Z,6.38
* 2023-09-29T08:06:11.513Z,6.38
* 2023-09-29T08:06:10.380Z,6.38
* 2023-09-29T08:06:09.569Z,6.38
* 2023-09-29T08:06:05.967Z,6.38"
* 400:
* description: Bad Request
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* message:
* type: string
* 404:
* description: Not found
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* message:
* type: string
* 500:
* description: Internal Server Error
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* message:
* type: string
*/
export const loader: LoaderFunction = async ({
request,
params,
}: LoaderFunctionArgs): Promise<Response> => {
try {
const collected = collectParameters(request, params);
if (collected instanceof Response)
return collected;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const {deviceId, sensorId, outliers, outlierWindow, fromDate, toDate, format, download, delimiter} = collected;
let meas: Measurement[] | TransformedMeasurement[] = await getMeasurements(sensorId, fromDate.toISOString(), toDate.toISOString());
if (meas == null)
return StandardResponse.notFound("Device not found.");
if (outliers)
meas = transformOutliers(meas, outlierWindow, outliers == "replace");
let headers: HeadersInit = {
"content-type": format == "json" ? "application/json; charset=utf-8" : "text/csv; charset=utf-8",
};
if (download)
headers["Content-Disposition"] = `attachment; filename=${sensorId}.${format}`;
const responseInit: ResponseInit = {
status: 200,
headers: headers,
};
if (format == "json")
return Response.json(meas, responseInit);
else {
const csv = getCsv(meas, delimiter == "comma" ? "," : ";");
return new Response(csv, responseInit)
}
} catch (err) {
console.warn(err);
return StandardResponse.internalServerError();
}
};
function collectParameters(request: Request, params: Params<string>):
Response | {
deviceId: string,
sensorId: string,
outliers: string | null,
outlierWindow: number,
fromDate: Date,
toDate: Date,
format: string | null,
download: boolean | null,
delimiter: string
} {
// deviceId is there for legacy reasons
const deviceId = params.deviceId;
if (deviceId === undefined)
return StandardResponse.badRequest("Invalid device id specified");
const sensorId = params.sensorId;
if (sensorId === undefined)
return StandardResponse.badRequest("Invalid sensor id specified");
const url = new URL(request.url);
const outliers = parseEnumParam(url, "outliers", ["replace", "mark"], null)
if (outliers instanceof Response)
return outliers;
const outlierWindowParam = url.searchParams.get("outlier-window")
let outlierWindow: number = 15;
if (outlierWindowParam !== null) {
if (Number.isNaN(outlierWindowParam) || Number(outlierWindowParam) < 1 || Number(outlierWindowParam) > 50)
return StandardResponse.badRequest("Illegal value for parameter outlier-window. Allowed values: numbers between 1 and 50");
outlierWindow = Number(outlierWindowParam);
}
const fromDate = parseDateParam(url, "from-date", new Date(new Date().setDate(new Date().getDate() - 2)))
if (fromDate instanceof Response)
return fromDate
const toDate = parseDateParam(url, "to-date", new Date())
if (toDate instanceof Response)
return toDate
const format = parseEnumParam(url, "format", ["json", "csv"], "json");
if (format instanceof Response)
return format
const downloadParam = parseEnumParam(url, "download", ["true", "false"], null)
if (downloadParam instanceof Response)
return downloadParam
const download = downloadParam == null
? null
: (downloadParam === "true");
const delimiter = parseEnumParam(url, "delimiter", ["comma", "semicolon"], "comma");
if (delimiter instanceof Response)
return delimiter;
return {
deviceId,
sensorId,
outliers,
outlierWindow,
fromDate,
toDate,
format,
download,
delimiter
};
}
function getCsv(meas: Measurement[] | TransformedMeasurement[], delimiter: string): string {
return convertToCsv(["createdAt", "value"], meas, [
measurement => measurement.time.toString(),
measurement => measurement.value?.toString() ?? "null"
], delimiter)
}