-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.boxes.$deviceId.data.ts
More file actions
58 lines (49 loc) · 1.91 KB
/
api.boxes.$deviceId.data.ts
File metadata and controls
58 lines (49 loc) · 1.91 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
import { type ActionFunction, type ActionFunctionArgs } from "react-router";
import { postNewMeasurements } from "~/lib/measurement-service.server";
import { StandardResponse } from "~/utils/response-utils";
export const action: ActionFunction = async ({
request,
params,
}: ActionFunctionArgs): Promise<Response> => {
try {
const deviceId = params.deviceId;
if (deviceId === undefined)
return StandardResponse.badRequest("Invalid device id specified");
const searchParams = new URL(request.url).searchParams;
const luftdaten = searchParams.get("luftdaten") !== null;
const hackair = searchParams.get("hackair") !== null;
const contentType = request.headers.get("content-type") || "";
const authorization = request.headers.get("authorization");
let body: any;
if (contentType.includes("application/json")) {
body = await request.json();
} else if (contentType.includes("text/csv")) {
body = await request.text();
} else if (contentType.includes("application/sbx-bytes")) {
body = await request.arrayBuffer();
} else {
body = await request.text();
}
await postNewMeasurements(deviceId, body, {
contentType,
luftdaten,
hackair,
authorization,
});
return new Response("Measurements saved in box", {
status: 201,
headers: {
"Content-Type": "text/plain; charset=utf-8",
},
});
} catch (err: any) {
// Handle different error types
if (err.name === "UnauthorizedError")
return StandardResponse.unauthorized(err.message);
if (err.name === "ModelError" && err.type === "UnprocessableEntityError")
return StandardResponse.unprocessableContent(err.message);
if (err.name === "UnsupportedMediaTypeError")
return StandardResponse.unsupportedMediaType(err.message);
return StandardResponse.internalServerError(err.message || "An unexpected error occurred");
}
};