0Pricing
Supabase Backend as a Service · Урок

Введение в пограничные функции

Изучите понятие бессерверных функций и узнайте, как пограничные функции Supabase, созданные на основе Deno, расширяют возможности серверной части.

«Введение в пограничные функции» — бесплатный урок Supabase Backend as a Service на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Supabase Backend as a Service, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Supabase Backend as a Service содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Say Hello to Serverless!

Welcome to Supabase Edge Functions! Before we dive in, let's understand serverless functions. Traditionally, you'd manage servers to run your backend code.

With serverless, you write code, and a cloud provider handles all the server management for you. You just focus on your logic!

Why Go Serverless?

Serverless functions offer some powerful advantages:

  • Automatic Scaling: They scale up or down instantly with demand.
  • Pay-per-use: You only pay for the compute time your functions actually run.
  • Reduced Ops: No servers to provision, patch, or maintain.
  • Faster Development: Focus purely on writing your application logic.

Supabase's Serverless Power

Supabase offers its own brand of serverless functions called Edge Functions. They extend your Supabase project's capabilities without needing to set up a separate server.

Think of them as tiny pieces of backend logic that run on demand, close to your users.

Powered by Deno

Supabase Edge Functions are built on Deno, a secure runtime for JavaScript and TypeScript. Deno is a modern alternative to Node.js.

This means you can write your functions in TypeScript right out of the box, enjoying type safety and modern JavaScript features without complex setup.

How Edge Functions Work

Edge Functions are event-driven. They only execute when triggered by an event, like an HTTP request from your application or a webhook.

They are also stateless, meaning each execution is independent. This design helps them scale efficiently.

What Can They Do?

Edge Functions are incredibly versatile! Here are some common use cases:

  • Custom API Endpoints: Build your own API routes.
  • Webhook Handlers: Process events from other services.
  • Data Transformations: Modify data before or after database operations.
  • Backend Logic: Run complex calculations or integrate with external APIs.

A Simple 'Hello' Function

Let's look at a basic Edge Function. This Deno code defines a function that responds to an HTTP request, expecting a name in its body.

Try running it to see the simple JSON response!

Deno.serve(async (req) => {
  const { name } = await req.json();

  return new Response(
    JSON.stringify({ message: `Hello, ${name || 'World'}!` }),
    {
      headers: { 'Content-Type': 'application/json' },
      status: 200,
    },
  );
});

The Power of the 'Edge'

The 'Edge' in Edge Functions means they run geographically close to your users. This significantly reduces latency, making your applications feel faster and more responsive.

Supabase handles deploying your functions to a global network of servers for optimal performance.

Invoking Your Function

Once deployed, you can easily call your Edge Functions from your client-side application using the Supabase client library. Here's a JavaScript example for our 'hello-world' function:

import { createClient } from '@supabase/supabase-js';

// Replace with your actual Supabase project URL and Anon Key
const supabaseUrl = 'https://your-project-ref.supabase.co';
const supabaseAnonKey = 'YOUR_ANON_KEY';

const supabase = createClient(supabaseUrl, supabaseAnonKey);

async function callHelloFunction() {
  const { data, error } = await supabase.functions.invoke('hello-world', {
    body: { name: 'CoddyKit User' },
  });

  if (error) {
    console.error('Error invoking function:', error);
  } else {
    console.log('Function response:', data);
  }
}

callHelloFunction();

Edge Function Essentials

Let's check your understanding of Supabase Edge Functions!

Recap: Edge Functions Intro

Great job! You've learned the basics of serverless computing and Supabase Edge Functions.

  • Edge Functions are Supabase's serverless offering.
  • They run on the Deno runtime, supporting TypeScript.
  • They offer automatic scaling, pay-per-use, and reduced ops.
  • They execute on demand, close to your users.

Next, we'll learn how to deploy your first function!

Часто задаваемые вопросы

Урок «Введение в пограничные функции» бесплатный?

Да — полный текст урока «Введение в пограничные функции» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Supabase Backend as a Service, подпишись на CoddyKit PRO. Курс Supabase Backend as a Service содержит 4 уроков всего.

Чему я научусь в уроке «Введение в пограничные функции»?

Изучите понятие бессерверных функций и узнайте, как пограничные функции Supabase, созданные на основе Deno, расширяют возможности серверной части. Ты практикуешь Supabase Backend as a Service с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Supabase Backend as a Service?

Предыдущий опыт не требуется. Supabase Backend as a Service на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Введение в пограничные функции»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Supabase Backend as a Service?

Да. Каждый урок Supabase Backend as a Service включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Введение в пограничные функции
  2. Развёртывание первой функции
  3. Интеграция функций с приложением
  4. Секреты, переменные окружения и функции по расписанию
← Назад к Supabase Backend as a Service