Supabase Edge Functions: Hướng dẫn tạo API serverless
Supabase Edge Functions là một tính năng mạnh mẽ của Supabase, cho phép bạn chạy code JavaScript hoặc TypeScript gần người dùng, giúp giảm latency và tăng hiệu năng. Trong bài viết này, chúng ta sẽ khám phá cách tạo API serverless sử dụng Supabase Edge Functions.
Tại sao nên sử dụng Supabase Edge Functions?
Supabase Edge Functions được xây dựng trên Deno Deploy, cho phép bạn triển khai code JavaScript/TypeScript lên mạng lưới toàn cầu của Supabase. Điều này có nghĩa là function của bạn sẽ chạy trên server gần nhất với người dùng, giảm đáng kể thời gian phản hồi.
So với các giải pháp serverless truyền thống, Supabase Edge Functions có một số ưu điểm:
- Tốc độ: Vì được triển khai trên edge network, latency thấp hơn đáng kể. - Đơn giản: Không cần cấu hình phức tạp, tích hợp sẵn với Supabase. - Bảo mật: Tự động đi kèm với Row Level Security của Supabase.
Cài đặt và chuẩn bị
Để bắt đầu với Supabase Edge Functions, bạn cần:
1. Cài đặt Supabase CLI: Đây là công cụ chính để quản lý và triển khai functions.
npm install -g supabase
2. Đăng nhập vào Supabase:
supabase login
3. Khởi tạo project: Nếu bạn chưa có project Supabase, hãy tạo một project mới trên dashboard.supabase.com.
4. Tạo thư mục project:
mkdir my-supabase-project
cd my-supabase-project
supabase init
Tạo function đầu tiên
Bây giờ chúng ta sẽ tạo function đầu tiên. Supabase Edge Functions được đặt trong thư mục supabase/functions/.
1. Tạo function mới:
supabase functions new hello-world
2. Mở file supabase/functions/hello-world/index.ts:
import { serve } from 'https://deno.land/[email protected]/http/server.ts';
console.log('Hello from Supabase Edge Function!');
serve(async (req) => {
return new Response(
JSON.stringify({
message: 'Hello, world!',
timestamp: new Date().toISOString(),
}),
{
headers: {
'Content-Type': 'application/json',
},
}
);
});
3. Deploy function:
supabase functions deploy hello-world
Sau khi deploy thành công, bạn sẽ nhận được URL để truy cập function. Thử mở URL này trong trình duyệt hoặc dùng curl để kiểm tra.
Tạo API CRUD hoàn chỉnh
Hãy xây dựng một API CRUD hoàn chỉnh để quản lý products. Đây là ví dụ chi tiết:
1. Tạo function CRUD:
supabase functions new products
2. Cài đặt Supabase client:
supabase functions install @supabase/supabase-js
3. Cập nhật file supabase/functions/products/index.ts:
Quảng cáo
300x250 In-Content Advertisement
import { serve } from 'https://deno.land/[email protected]/http/server.ts';
import { createClient } from '@supabase/supabase-js';
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseKey = Deno.env.get('SUPABASE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseKey);
console.log('Products API is running');
serve(async (req) => {
const url = new URL(req.url);
const method = req.method;
try {
switch (method) {
case 'GET':
if (url.pathname === '/products') {
const { data, error } = await supabase
.from('products')
.select('*');
if (error) throw error;
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
});
}
if (url.pathname.startsWith('/products/')) {
const id = url.pathname.split('/').pop()!;
const { data, error } = await supabase
.from('products')
.select('*')
.eq('id', id)
.single();
if (error) throw error;
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
});
}
break;
case 'POST':
if (url.pathname === '/products') {
const body = await req.json();
const { data, error } = await supabase
.from('products')
.insert(body)
.select('*')
.single();
if (error) throw error;
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
});
}
break;
case 'PUT':
if (url.pathname.startsWith('/products/')) {
const id = url.pathname.split('/').pop()!;
const body = await req.json();
const { data, error } = await supabase
.from('products')
.update(body)
.eq('id', id)
.select('*')
.single();
if (error) throw error;
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
});
}
break;
case 'DELETE':
if (url.pathname.startsWith('/products/')) {
const id = url.pathname.split('/').pop()!;
const { error } = await supabase
.from('products')
.delete()
.eq('id', id);
if (error) throw error;
return new Response(JSON.stringify({ message: 'Deleted' }), {
headers: { 'Content-Type': 'application/json' },
});
}
break;
default:
return new Response('Method not allowed', { status: 405 });
}
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
return new Response('Not found', { status: 404 });
});
4. Deploy function:
supabase functions deploy products
Các best practices khi làm việc với Edge Functions
Khi làm việc với Supabase Edge Functions, hãy lưu ý một số best practices sau:
- Sử dụng environment variables: Không hardcode credentials, luôn dùng environment variables. - Xử lý lỗi: Implement error handling tốt để tránh function crash. - Giới hạn payload: Vì Edge Functions có timeout ngắn, hạn chế xử lý dữ liệu lớn. - Cache: Tận dụng browser caching khi có thể để giảm latency. - Security: Validate input data và sử dụng Row Level Security của Supabase.
Debugging và testing
Supabase cung cấp một số công cụ để debug và test functions:
1. Local testing:
supabase functions serve
2. Logs:
supabase functions logs
3. Invoke function:
supabase functions invoke products --data '{"name": "Test"}'
Kết luận
Supabase Edge Functions là một giải pháp mạnh mẽ để xây dựng API serverless nhanh chóng và hiệu quả. Với khả năng chạy code gần người dùng, tích hợp sẵn với Supabase, và đơn giản trong việc triển khai, đây là lựa chọn tuyệt vời cho nhiều use cases từ API CRUD đến webhook và background jobs.
Hy vọng qua hướng dẫn này, bạn đã có cái nhìn tổng quan về cách tạo và sử dụng Supabase Edge Functions. Hãy bắt đầu xây dựng API serverless của riêng bạn và trải nghiệm sức mạnh của edge computing!