-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
213 lines (181 loc) · 6.67 KB
/
Copy pathroute.ts
File metadata and controls
213 lines (181 loc) · 6.67 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
import { NextRequest, NextResponse } from "next/server";
import { getRequestContext } from "@cloudflare/next-on-pages";
import { Logger } from "../../lib/logger";
export const runtime = "edge";
export const dynamic = "force-dynamic";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Accept",
};
export async function OPTIONS() {
return new NextResponse(null, { headers: corsHeaders });
}
interface D1Database {
prepare(query: string): D1PreparedStatement;
}
type D1Param = string | number | boolean | null;
interface D1PreparedStatement {
bind(...values: D1Param[]): D1PreparedStatement;
all<T = Record<string, unknown>>(): Promise<D1Result<T>>;
run<T = Record<string, unknown>>(): Promise<D1Result<T>>;
}
interface D1Result<T = Record<string, unknown>> {
success: boolean;
results: T[];
}
interface EventEntity {
id: string;
event_id: string;
asset_id: string;
actor_id: string;
timestamp: string;
action_type: string;
energy_kwh: number;
emission_factor: number;
signature: string;
public_key: string;
integrity_status: string;
}
interface CloudflareEnv {
DB: D1Database;
}
interface EventCreateDTO {
id: string;
event_id: string;
asset_id: string;
actor_id: string;
timestamp: string;
action_type: string;
esg_metadata: {
energy_kwh: number;
emission_factor: number;
};
signature: string;
public_key: string;
integrity_status: string;
}
function validateEventCreateDTO(rawPayload: Partial<EventCreateDTO>): string | null {
const requiredFields = [
{ field: "id", value: rawPayload.id },
{ field: "event_id", value: rawPayload.event_id },
{ field: "asset_id", value: rawPayload.asset_id },
{ field: "actor_id", value: rawPayload.actor_id },
{ field: "timestamp", value: rawPayload.timestamp },
{ field: "action_type", value: rawPayload.action_type },
{ field: "signature", value: rawPayload.signature },
{ field: "public_key", value: rawPayload.public_key },
{ field: "integrity_status", value: rawPayload.integrity_status },
];
for (const { field, value } of requiredFields) {
if (value === undefined || value === null) {
return `Missing required field: ${field}`;
}
}
if (
!rawPayload.esg_metadata ||
typeof rawPayload.esg_metadata !== "object" ||
rawPayload.esg_metadata.energy_kwh === undefined ||
rawPayload.esg_metadata.emission_factor === undefined
) {
return "Missing or invalid required field: esg_metadata";
}
return null;
}
export async function GET(request: NextRequest) {
try {
const db = (getRequestContext().env as unknown as CloudflareEnv).DB;
if (!db) {
Logger.error("Database binding 'DB' not found in environment.");
return NextResponse.json({ error: "Service Unavailable: Database binding missing. Please check your environment configuration." }, { status: 500, headers: corsHeaders });
}
const { searchParams } = new URL(request.url);
const statusParam = searchParams.get("status");
const assetIdParam = searchParams.get("asset_id");
let query = "SELECT * FROM events";
const params: string[] = [];
const conditions: string[] = [];
if (statusParam === "alerts") {
conditions.push("integrity_status IN ('INVALID', 'UNAUTHORIZED')");
} else if (statusParam === "INVALID" || statusParam === "UNAUTHORIZED") {
conditions.push("integrity_status = ?");
params.push(statusParam);
}
if (assetIdParam) {
conditions.push("asset_id = ?");
params.push(assetIdParam);
}
if (conditions.length > 0) {
query += " WHERE " + conditions.join(" AND ");
}
query += " ORDER BY timestamp DESC LIMIT 50";
let stmt = db.prepare(query);
if (params.length > 0) stmt = stmt.bind(...params);
const { results } = await stmt.all<EventEntity>();
const events = results.map(row => ({
id: row.id,
event_id: row.event_id,
asset_id: row.asset_id,
actor_id: row.actor_id,
timestamp: row.timestamp,
action_type: row.action_type,
esg_metadata: {
energy_kwh: row.energy_kwh,
emission_factor: row.emission_factor,
},
signature: row.signature,
public_key: row.public_key,
integrity_status: row.integrity_status,
}));
if (assetIdParam && events.length === 0) {
return NextResponse.json({ error: "Asset not found in the global ledger." }, { status: 404, headers: corsHeaders });
}
return NextResponse.json(events, { headers: corsHeaders });
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
Logger.error(`D1 GET /api/events error: ${errorMessage}`, error);
return NextResponse.json({ error: "Failed to fetch events" }, { status: 500, headers: corsHeaders });
}
}
export async function POST(request: NextRequest) {
try {
const db = (getRequestContext().env as unknown as CloudflareEnv).DB;
if (!db) {
Logger.error("Database binding 'DB' not found in environment.");
return NextResponse.json({ error: "Service Unavailable: Database binding missing. Please check your environment configuration." }, { status: 500, headers: corsHeaders });
}
const rawPayload = (await request.json()) as Partial<EventCreateDTO>;
const validationError = validateEventCreateDTO(rawPayload);
if (validationError) {
return NextResponse.json({ error: validationError }, { status: 400, headers: corsHeaders });
}
const payload = rawPayload as EventCreateDTO;
const { success } = await db.prepare(
`INSERT INTO events (
id, event_id, asset_id, actor_id, timestamp, action_type,
energy_kwh, emission_factor, signature, public_key, integrity_status
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).bind(
payload.id,
payload.event_id,
payload.asset_id,
payload.actor_id,
payload.timestamp,
payload.action_type,
payload.esg_metadata.energy_kwh,
payload.esg_metadata.emission_factor,
payload.signature,
payload.public_key,
payload.integrity_status
).run();
if (success) {
return NextResponse.json({ success: true, id: payload.id }, { status: 201, headers: corsHeaders });
} else {
return NextResponse.json({ error: "Database rejected the insertion." }, { status: 500, headers: corsHeaders });
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
Logger.error(`D1 POST /api/events error: ${errorMessage}`, error);
return NextResponse.json({ error: "Failed to create event" }, { status: 500, headers: corsHeaders });
}
}