From 4af2ff15393043d67a521923c4fcd95e27b8f6c6 Mon Sep 17 00:00:00 2001 From: tiennm99 Date: Sun, 31 Aug 2025 11:14:07 +0700 Subject: [PATCH] feat: base logic --- src/index.js | 85 ++++++++++++++++++++++++++++++++++++++++------ test/index.spec.js | 36 +++++++++++++++----- 2 files changed, 102 insertions(+), 19 deletions(-) diff --git a/src/index.js b/src/index.js index de66b62..f844360 100644 --- a/src/index.js +++ b/src/index.js @@ -1,15 +1,78 @@ -/** - * Welcome to Cloudflare Workers! This is your first worker. - * - * - Run `npm run dev` in your terminal to start a development server - * - Open a browser tab at http://localhost:8787/ to see your worker in action - * - Run `npm run deploy` to publish your worker - * - * Learn more at https://developers.cloudflare.com/workers/ - */ - export default { async fetch(request, env, ctx) { - return new Response('Hello World!'); + if (request.method !== 'POST') { + return new Response('Method not allowed', { status: 405 }); + } + + try { + const contentType = request.headers.get('content-type'); + let text; + + if (contentType && contentType.includes('application/json')) { + const body = await request.json(); + text = body.text; + } else if (contentType && contentType.includes('application/x-www-form-urlencoded')) { + const formData = await request.formData(); + text = formData.get('text'); + } else { + return new Response('Content-Type must be application/json or application/x-www-form-urlencoded', { status: 400 }); + } + + if (!text) { + return new Response('Missing text parameter', { status: 400 }); + } + + const telegramToken = env.TELEGRAM_TOKEN; + const telegramChatId = env.TELEGRAM_CHAT_ID; + + if (!telegramToken || !telegramChatId) { + return new Response('Missing TELEGRAM_TOKEN or TELEGRAM_CHAT_ID environment variables', { status: 500 }); + } + + const telegramUrl = `https://api.telegram.org/bot${telegramToken}/sendMessage`; + const telegramPayload = { + chat_id: telegramChatId, + text: text + }; + + const telegramResponse = await fetch(telegramUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(telegramPayload) + }); + + const telegramResult = await telegramResponse.json(); + + if (!telegramResponse.ok) { + return new Response(JSON.stringify({ + success: false, + error: 'Telegram API error', + details: telegramResult + }), { + status: 500, + headers: { 'Content-Type': 'application/json' } + }); + } + + return new Response(JSON.stringify({ + success: true, + message: 'Message sent successfully', + telegram_response: telegramResult + }), { + headers: { 'Content-Type': 'application/json' } + }); + + } catch (error) { + return new Response(JSON.stringify({ + success: false, + error: 'Internal server error', + details: error.message + }), { + status: 500, + headers: { 'Content-Type': 'application/json' } + }); + } }, }; diff --git a/test/index.spec.js b/test/index.spec.js index e2807ff..d8252c1 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -2,19 +2,39 @@ import { env, createExecutionContext, waitOnExecutionContext, SELF } from 'cloud import { describe, it, expect } from 'vitest'; import worker from '../src'; -describe('Hello World worker', () => { - it('responds with Hello World! (unit style)', async () => { +describe('Telegram Worker', () => { + it('rejects GET requests', async () => { const request = new Request('http://example.com'); - // Create an empty context to pass to `worker.fetch()`. const ctx = createExecutionContext(); const response = await worker.fetch(request, env, ctx); - // Wait for all `Promise`s passed to `ctx.waitUntil()` to settle before running test assertions await waitOnExecutionContext(ctx); - expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`); + expect(response.status).toBe(405); + expect(await response.text()).toMatchInlineSnapshot(`"Method not allowed"`); }); - it('responds with Hello World! (integration style)', async () => { - const response = await SELF.fetch('http://example.com'); - expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`); + it('requires text parameter in JSON POST', async () => { + const request = new Request('http://example.com', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}) + }); + const ctx = createExecutionContext(); + const response = await worker.fetch(request, env, ctx); + await waitOnExecutionContext(ctx); + expect(response.status).toBe(400); + expect(await response.text()).toMatchInlineSnapshot(`"Missing text parameter"`); + }); + + it('requires environment variables', async () => { + const request = new Request('http://example.com', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ text: 'Hello World!' }) + }); + const ctx = createExecutionContext(); + const response = await worker.fetch(request, {}, ctx); + await waitOnExecutionContext(ctx); + expect(response.status).toBe(500); + expect(await response.text()).toMatchInlineSnapshot(`"Missing TELEGRAM_TOKEN or TELEGRAM_CHAT_ID environment variables"`); }); });