Created
April 14, 2025 18:53
-
-
Save LuisErnestoZamb/2fba895d409a8ec07809faf13aa7ef50 to your computer and use it in GitHub Desktop.
Code: Azure sms cognitive services + cloudflare worker + Turso = collect sms and save this into Turso
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/templates/basic/index.js | |
import { createClient } from "@libsql/client/web"; | |
var basic_default = { | |
async fetch(request, env) { | |
const { headers } = request; | |
const contentType = headers.get("Content-Type") || ""; | |
if (request.method === "POST" && contentType.includes("application/json")) { | |
const client = createClient({ url: env.TURSO_URL, authToken: env.TURSO_AUTH_TOKEN }); | |
const eventGridData = await request.json() ||{}; | |
const smsEvent = eventGridData[0]; | |
if (smsEvent.eventType === "Microsoft.Communication.SMSReceived") { | |
const smsDetails = smsEvent.data; | |
const senderNumber = smsDetails.from; | |
const receiverNumber = smsDetails.to; | |
const messageContent = smsDetails.message; | |
try { | |
await client.execute( | |
`INSERT INTO mensajes (senderNumber, receiverNumber, messageContent) VALUES ('${senderNumber}', '${receiverNumber}', '${messageContent}')` | |
); | |
console.error("SMS content processed and stored:", JSON.stringify(eventGridData)); | |
return new Response("SMS content processed and stored", { status: 200 }); | |
} catch (error) { | |
console.error("Failed to store SMS in Turso:", error); | |
return new Response("Error storing SMS content", { status: 500 }); | |
} | |
} | |
} | |
// Check if the request has JSON data | |
if (contentType.includes("application/json")) { | |
const data = await request.json(); | |
// Check if it's a validation event | |
if (data[0]?.eventType === "Microsoft.EventGrid.SubscriptionValidationEvent") { | |
const validationCode = data[0]?.data?.validationCode; | |
// Respond with the validation code | |
return new Response( | |
JSON.stringify({ validationResponse: validationCode }), | |
{ | |
status: 200, | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
} | |
); | |
} | |
} | |
return new Response(JSON.stringify({}), { | |
status: 200, | |
headers: { | |
"Content-Type": "application/json", | |
} | |
}); | |
} | |
}; | |
export { | |
basic_default as default | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment