cloudfare làm việc với workers với ví dụ đơn giản
Workers là 1 dịch vụ mà các bạn nên dùng để có thể xử lý những tác vụ serverless 1 cách đơn giản và hiệu quả ,khi kết hợp với r2 và d1 database sẽ mang đến cho chúng ta nhiều điều thú vị
Dưới đây là 1 demo về việc lấy ID của video youtube :
/**
* 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) {
const url = new URL(request.url);
const api_key = url.searchParams.get('key');
const youtube_url = url.searchParams.get('url');
// kiểm tra key
if (api_key !== env.API_KEY) {
return new Response('Đây là link xử lý dữ liệu đầu vào url youtube đầu ra là id video ,Link demo :https://youtubegetidbylink.shang9x.workers.dev/?url=https://www.youtube.com/watch?v=Adh_NrYml1o&key=xxxx', { status: 400 });
}
if (!youtube_url) {
const data = {
url: youtube_url,
status: 0,
message: 'Lỗi url',
};
return new Response(JSON.stringify(data), { status: 400 });
}
const video_id = convertYoutube(youtube_url);
if (!video_id) {
const data = {
url: youtube_url,
status: 0,
message: 'error không chuyển được video id',
};
return new Response(JSON.stringify(data), { status: 400 });
}
const data = {
url: youtube_url,
video_id: video_id,
status: 1,
message: 'success',
};
return new Response(JSON.stringify(data), { status: 200 });
// lấy method
const method = request.method;
// lấy pathname loại bỏ các khoảng trống
const paths = url.pathname.split('/').filter(Boolean);
if (paths[0] == 'admin') {
return new Response('xin chào các bạn');
}
return new Response(`Path: ${path}, Method: ${method}`);
return new Response(api_key);
return new Response('Hello World!');
},
};
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function convertYoutube(url) {
const youtubeRegex = /(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
const match = url.match(youtubeRegex);
if (match && match[1]) {
if (!validateVideoId(match[1])) {
return Response("Video ID khong dung", { status: 200 });
}
return match[1];
} else {
return null;
}
}
function validateVideoId(videoId) {
if (videoId.length !== 11) {
return false;
}
const regex = /^[a-zA-Z0-9_-]{11}$/;
return regex.test(videoId);
}
Với đoạn mã trong đó env.API_KEY được config trong file wrangler.jsonc
/**
* For more details on how to configure Wrangler, refer to:
* https://developers.cloudflare.com/workers/wrangler/configuration/
*/
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "youtubegetidbylink",
"main": "src/index.js",
"compatibility_date": "2025-04-06",
"observability": {
"enabled": true
},
"r2_buckets": [
{
"binding": "BUCKET",
"bucket_name": "youtubedata"
}
],
/**
* Smart Placement
* Docs: https://developers.cloudflare.com/workers/configuration/smart-placement/#smart-placement
*/
// "placement": { "mode": "smart" },
/**
* Bindings
* Bindings allow your Worker to interact with resources on the Cloudflare Developer Platform, including
* databases, object storage, AI inference, real-time communication and more.
* https://developers.cloudflare.com/workers/runtime-apis/bindings/
*/
/**
* Environment Variables
* https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables
*/
"vars": {
"API_KEY": "xxxx"
},
/**
* Note: Use secrets to store sensitive data.
* https://developers.cloudflare.com/workers/configuration/secrets/
*/
/**
* Static Assets
* https://developers.cloudflare.com/workers/static-assets/binding/
*/
// "assets": { "directory": "./public/", "binding": "ASSETS" },
/**
* Service Bindings (communicate between multiple Workers)
* https://developers.cloudflare.com/workers/wrangler/configuration/#service-bindings
*/
// "services": [{ "binding": "MY_SERVICE", "service": "my-service" }]
}
API_KEY = biến bạn ghi vào