Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
// This val creates a webhook endpoint to receive health data from an iOS app and insert it into a Supabase database.
// We'll use the Supabase JavaScript client to interact with the database.
/** @jsxImportSource https://esm.sh/react */
import React from "https://esm.sh/react";
import { renderToString } from "https://esm.sh/react-dom/server";
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
// Initialize Supabase client
const supabaseUrl = Deno.env.get('SUPABASE_PERSONAL_URL');
const supabaseKey = Deno.env.get('SUPABASE_PERSONAL_KEY');
if (!supabaseUrl || !supabaseKey) {
throw new Error('Supabase URL and Key must be set as environment variables');
}
const supabase = createClient(supabaseUrl, supabaseKey);
export default async function server(request: Request): Promise<Response> {
console.log(`Received ${request.method} request`);
try {
if (request.method === 'POST') {
// Parse the JSON payload from the request body
let payload;
try {
payload = await request.json();
} catch (error) {
console.error('Error parsing JSON:', error);
return new Response('Invalid JSON payload', { status: 400 });
}
console.log('Received payload:', payload);
// Process and insert the data
let insertedCount = 0;
let errors = [];
if (payload.data && payload.data.metrics) {
for (const metric of payload.data.metrics) {
for (const dataPoint of metric.data) {
const healthData = {
date: new Date(dataPoint.date).toISOString(),
metric_type: metric.name,
data: {
units: metric.units,
value: dataPoint.qty
},
source: dataPoint.source
};
const { data, error } = await supabase
.from('health_data')
.insert(healthData);
if (error) {
console.error('Error inserting data:', JSON.stringify(error));
errors.push(error.message);
} else {
insertedCount++;
}
}
}
} else {
// If the payload doesn't match the expected structure, insert it as-is
const { data, error } = await supabase
.from('health_data')
.insert({
date: new Date().toISOString(),
data: payload,
metric_type: 'unknown',
source: 'iOS App'
});
if (error) {
console.error('Error inserting data:', JSON.stringify(error));
errors.push(error.message);
} else {
insertedCount++;
}
}
if (errors.length > 0) {
return new Response(`Errors inserting data: ${errors.join(', ')}`, { status: 500 });
}
console.log(`${insertedCount} data points inserted successfully`);
return new Response(`${insertedCount} health data points inserted successfully`, { status: 200 });
} else if (request.method === 'GET') {
// Handle GET requests (e.g., for testing)
let latestUpdate = null;
let errorMessage = null;
const { data, error } = await supabase
.from('health_data')
.select('date')
.order('date', { ascending: false })
.limit(1);
if (error) {
console.error('Error fetching latest data:', error);
errorMessage = `Error fetching latest data: ${error.message}`;
} else if (data && data.length > 0) {
ejfox-healthwebhook.web.val.run
September 10, 2024