# Supabase 集成

来源：https://docs.nestjs.com/recipes/supabase

Supabase 为应用提供了 Postgres 数据库、登录、文件存储，以及一套浏览器可以直接调用的 API，这已经能覆盖很多场景而无需后端。它没有覆盖的，是需要密钥、重试或时钟的工作：Stripe webhook、定时任务、队列、管理 API。Nest 就在 Supabase 旁边承担这些工作，使用同一个数据库，面向同一批用户。

| 留在 Supabase | 交给 Nest 处理 |
| --- | --- |
| 注册、登录与重置密码 | 判断调用者是谁，以及它可以做什么 |
| Postgres、它的迁移与行级安全 | 业务规则，以及跨多张表的查询 |
| 行级安全所覆盖的浏览器读写 | 一切需要密钥的东西：支付、邮件、其他 API |
| Storage 与 Realtime | Stripe webhook、定时任务、队列与管理 API |

凡是行级安全覆盖的部分，浏览器继续直接调用 Supabase；其余部分则带着同一个访问令牌调用 Nest。

如果你只需要一两个短小的函数，[Edge Functions](https://supabase.com/docs/guides/functions) 也许就够了，无需运行服务器。它们对 [CPU 时间与执行时长设有限制](https://supabase.com/docs/guides/functions/limits)，也没有地方运行队列的 worker，所以一旦有了任务、队列，或大量共享代码的路由，Nest 就更合适。

本配方在本地 Supabase 栈上构建这样一个应用，以便你在阅读的同时逐步运行。[最终成品模块](/recipes/supabase#the-finished-module)展示了各部分是如何串联起来的。

#### 创建项目

本地栈需要 Docker。

```bash
$ npx @nestjs/cli new my-api
$ cd my-api
$ npx supabase init
$ npx supabase start
```

`npx supabase status -o env` 会打印该栈的 URL 与密钥。把 `API_URL`、`PUBLISHABLE_KEY`、`SECRET_KEY` 和 `DB_URL` 放进 `.env`，使用本配方所读取的那些名字：

```bash
SUPABASE_URL=http://127.0.0.1:54321
SUPABASE_PUBLISHABLE_KEY=sb_publishable_...
SUPABASE_SECRET_KEY=sb_secret_...
DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:54322/postgres
```

> warning **警告** 密钥会绕过行级安全。它只应放在服务端，绝不能出现在任何交付给浏览器或移动应用的产物里。

> info **提示** 托管项目在控制面板里有同样的密钥。Supabase 将在 2026 年底[弃用](https://supabase.com/docs/guides/api/api-keys)较旧的 `anon` 与 `service_role` 密钥，所以请使用这两个。

用 [`@nestjs/config`](/application/configuration) 加载 `.env`：

```bash
$ npm i --save @nestjs/config
```

```typescript
@Module({
  imports: [ConfigModule.forRoot()],
})
export class AppModule {}
```

把它放在 `imports` 的第一位，因为你在它之后添加的模块会在声明时就读取 `process.env`。在另一个文件中声明的模块会更早读取，即在那个文件被导入时，因此对于你要在那个文件里注册的东西，请使用 `forRootAsync()`。

#### 定义一张表

表结构放在 Supabase 的迁移里：

```bash
$ npx supabase migration new notes
```

把这张表写进该命令在 `supabase/migrations` 下创建的文件，并配一条策略，让用户只能访问自己的行。`auth.uid()` 就是请求的访问令牌所属的那个用户：

```sql
create table public.notes (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id) on delete cascade,
  body text not null
);

alter table public.notes enable row level security;

create policy "Users manage their own notes" on public.notes
  for all to authenticated
  using ((select auth.uid()) = user_id)
  with check ((select auth.uid()) = user_id);
```

把它应用到本地数据库：

```bash
$ npx supabase db reset
```

> warning **警告** Supabase 的 API 会把 `public` schema 里的表提供给任何持有可发布密钥的人，而那把密钥就在你的浏览器代码中。请为你在此创建的每张表启用行级安全，包括仅供 Nest 使用的表。启用它却没有任何策略时，这把密钥什么也读不到。

#### 校验 Supabase 令牌

Supabase Auth 会为每个已登录用户签发访问令牌，并公布用于校验它的公钥。[`@nestjs/authentication`](/security/authentication) 可以校验来自其他签发者的令牌，因此 Nest 无需从 Supabase 取得任何密钥，就能知道调用者是谁：

```bash
$ npm i --save @nestjs/authentication
```

```typescript
@@filename(supabase/supabase-auth)
import { Injectable } from '@nestjs/common';
import { AuthenticationRegistry, JwtBearerProvider, type JwtClaims } from '@nestjs/authentication';

export interface SupabaseUser {
  id: string;
  email?: string;
  role?: string;
}

@Injectable()
export class SupabaseAuth extends JwtBearerProvider<SupabaseUser> {
  constructor(registry: AuthenticationRegistry) {
    super({
      jwks: `${process.env.SUPABASE_URL}/auth/v1/.well-known/jwks.json`,
      issuer: `${process.env.SUPABASE_URL}/auth/v1`,
      audience: 'authenticated',
    });
    registry.registerProvider(this);
  }

  validate(claims: JwtClaims) {
    if (!claims.sub) {
      return null;
    }
    const { email, app_metadata } = claims as JwtClaims & {
      email?: string;
      app_metadata?: { role?: string };
    };
    return { id: claims.sub, email, role: app_metadata?.role };
  }
}
```

角色来自 `app_metadata`，只有你的服务端才能改动它。已登录的用户可以用 `supabase.auth.updateUser()` 修改自己的 `user_metadata`，所以绝不要基于它做决策。

注册模块与提供者：

```typescript
@Module({
  imports: [AuthenticationModule.forRoot({})],
  providers: [SupabaseAuth],
})
export class AppModule {}
```

该模块会注册一个全局守卫，因此现在每条路由在没有有效令牌时都会返回 `401 Unauthorized`，包括签名有误、签发者或受众不同、以及已过期的令牌。用 `@Public()` 标记需要保持开放的路由，并用 `@CurrentUser()` 读取用户：

```typescript
@@filename(me/me.controller)
import { Controller, Get } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import type { SupabaseUser } from '../supabase/supabase-auth.js';

@Controller('me')
export class MeController {
  @Get()
  me(@CurrentUser() user: SupabaseUser) {
    return user;
  }
}
```

> info **提示** 仍在使用旧版 JWT 密钥的项目用它签发令牌，且不公布任何公钥。在[迁移到签名密钥](https://supabase.com/docs/guides/auth/signing-keys)之前，请传入 `key: process.env.SUPABASE_JWT_SECRET` 而不是 `jwks`。

#### 从浏览器调用 Nest

浏览器会发送 Supabase 交给它的访问令牌。`getSession()` 会在令牌过期时刷新它：

```typescript
const { data: { session } } = await supabase.auth.getSession();

const response = await fetch(`${API_URL}/me`, {
  headers: { Authorization: `Bearer ${session.access_token}` },
});
```

如果浏览器从另一个源调用 Nest，请在应用启动时[允许该源](/security/cors)：

```typescript
@@filename(main)
app.enableCors({ origin: process.env.WEB_ORIGIN });
```

#### 以用户身份查询，或以服务端身份查询

`@supabase/supabase-js` 是访问你数据库 REST API 的客户端。请从 schema 生成类型，这样查询不存在的表或列时就会编译失败；每次迁移之后都要重新运行一次：

```bash
$ npm i --save @supabase/supabase-js
$ npx supabase gen types typescript --local > src/supabase/database.types.ts
```

为服务端创建一个客户端，为用户按请求各创建一个。客户端并不持有数据库连接，所以这样做开销很小：

```typescript
@@filename(supabase/supabase.service)
import { Injectable } from '@nestjs/common';
import { createClient } from '@supabase/supabase-js';
import type { Database } from './database.types.js';

const options = { auth: { persistSession: false, autoRefreshToken: false } };

@Injectable()
export class SupabaseService {
  /** 绕过行级安全。仅用于服务端自身的操作。 */
  readonly admin = createClient<Database>(
    process.env.SUPABASE_URL!,
    process.env.SUPABASE_SECRET_KEY!,
    options,
  );

  /** 以发送该令牌的用户身份查询，因此行级安全会生效。 */
  forUser(token: string) {
    return createClient<Database>(process.env.SUPABASE_URL!, process.env.SUPABASE_PUBLISHABLE_KEY!, {
      ...options,
      accessToken: async () => token,
    });
  }
}
```

一个小装饰器读取守卫已经校验过的令牌：

```typescript
@@filename(supabase/access-token.decorator)
import { createParamDecorator, type ExecutionContext } from '@nestjs/common';

export const AccessToken = createParamDecorator((_: unknown, context: ExecutionContext) => {
  const { authorization } = context.switchToHttp().getRequest().headers;
  return authorization?.replace(/^Bearer /i, '');
});
```

在为某个用户执行操作的路由里，优先使用 `forUser()`。你的策略会继续生效，因此即使某个查询忘了过滤条件，也只会返回该用户自己的行，而为他人插入数据会被拒绝：

```typescript
@@filename(notes/notes.controller)
import { Body, Controller, Get, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { AccessToken } from '../supabase/access-token.decorator.js';
import type { SupabaseUser } from '../supabase/supabase-auth.js';
import { SupabaseService } from '../supabase/supabase.service.js';

@Controller('notes')
export class NotesController {
  constructor(private readonly supabase: SupabaseService) {}

  @Get()
  async findAll(@AccessToken() token: string) {
    const { data, error } = await this.supabase.forUser(token).from('notes').select('body');
    if (error) {
      throw error;
    }
    return data;
  }

  @Post()
  async create(
    @AccessToken() token: string,
    @CurrentUser() user: SupabaseUser,
    @Body('body') body: string,
  ) {
    const { error } = await this.supabase.forUser(token).from('notes').insert({ user_id: user.id, body });
    if (error) {
      throw error;
    }
  }
}
```

对于服务端以自身名义执行、不涉及任何用户的操作（例如任务或 webhook），请使用 `admin`。

#### 直接查询 Postgres

对于事务，以及 REST API 无法表达的查询，请用 [`@nestjs/drizzle`](/data/drizzle) 或其他[数据库集成](/data/overview)连接数据库。下面的 webhook 与任务也使用这个连接：

```bash
$ npm i --save @nestjs/drizzle drizzle-orm pg
```

```typescript
DrizzleModule.forRoot({ drizzle, connection: process.env.DATABASE_URL! }),
```

在本地，`DATABASE_URL` 就是这个栈的 `DB_URL`。在托管项目上，Nest 是常驻后端，所以请使用[直连字符串](https://supabase.com/docs/guides/database/connecting-to-postgres)；如果你的主机只有 IPv4，也可以使用 session 模式的共享连接池。连接池的 transaction 模式既不支持预处理语句，也不支持 BullMQ 的 PostgreSQL 后端所使用的 `LISTEN`。

Supabase 的迁移仍是唯一事实来源，因此 Drizzle schema 只描述要查询的表：

```typescript
@@filename(database/schema)
import { pgTable, text, uuid } from 'drizzle-orm/pg-core';

export const notes = pgTable('notes', {
  id: uuid('id').primaryKey().defaultRandom(),
  userId: uuid('user_id').notNull(),
  body: text('body').notNull(),
});
```

> warning **警告** 行级安全保护不了这些查询。`postgres` 角色会绕过它，因此不带过滤条件的查询会返回所有用户的行，每个查询都必须自行校验归属。

若要让直连查询也沿用你的策略，请以 `authenticated` 角色、带着 `auth.uid()` 所读取的 claims，在事务中运行它：

```typescript
@@filename(database/row-level-security)
import { Injectable } from '@nestjs/common';
import type { JwtClaims } from '@nestjs/authentication';
import { InjectDrizzle } from '@nestjs/drizzle';
import { sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';

type Transaction = Parameters<Parameters<NodePgDatabase['transaction']>[0]>[0];

@Injectable()
export class RowLevelSecurity {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  asUser<T>(claims: JwtClaims, work: (tx: Transaction) => Promise<T>): Promise<T> {
    return this.db.transaction(async (tx) => {
      await tx.execute(sql`
        select set_config('request.jwt.claims', ${JSON.stringify(claims)}, true),
               set_config('role', 'authenticated', true)
      `);
      return work(tx);
    });
  }
}
```

两项设置都随事务结束，因此绝不会传到该连接上的下一次查询。下面把每种方式并排列出，其中 `@CurrentSession()` 会把已校验的 claims 交给路由：

```typescript
@@filename(notes/notes.repository)
import { Injectable } from '@nestjs/common';
import type { JwtClaims } from '@nestjs/authentication';
import { InjectDrizzle } from '@nestjs/drizzle';
import { eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { RowLevelSecurity } from '../database/row-level-security.js';
import { notes } from '../database/schema.js';
import type { SupabaseUser } from '../supabase/supabase-auth.js';

@Injectable()
export class NotesRepository {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    private readonly rls: RowLevelSecurity,
  ) {}

  /** 自行校验归属。 */
  findAll(user: SupabaseUser) {
    return this.db.select({ body: notes.body }).from(notes).where(eq(notes.userId, user.id));
  }

  /** 把归属交给表的策略处理。 */
  findAllAsUser(claims: JwtClaims) {
    return this.rls.asUser(claims, (tx) => tx.select({ body: notes.body }).from(notes));
  }
}
```

#### 保护管理 API

管理 API 是浏览器自己做不到的事，因为它需要密钥。把用户的角色保存在 `app_metadata` 中（`SupabaseAuth` 已经在读它），并从服务端设置：

```typescript
await supabase.admin.auth.admin.updateUserById(userId, {
  app_metadata: { role: 'admin' },
});
```

角色会出现在用户的下一个令牌里，因此已经登录的人会在令牌刷新时拿到它，默认在一小时之内。

用 [`@nestjs/authorization`](/security/authorization) 校验它：

```bash
$ npm i --save @nestjs/authorization
```

```typescript
@@filename(admin/admin.policy)
import { Policy } from '@nestjs/authorization';
import type { SupabaseUser } from '../supabase/supabase-auth.js';

@Policy()
export class AdminPolicy {
  manage(user: SupabaseUser | null) {
    return user?.role === 'admin';
  }
}
```

```typescript
@@filename(admin/admin-users.controller)
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthorizationGuard, Can } from '@nestjs/authorization';
import { SupabaseService } from '../supabase/supabase.service.js';
import { AdminPolicy } from './admin.policy.js';

@UseGuards(AuthorizationGuard)
@Can(AdminPolicy, 'manage')
@Controller('admin/users')
export class AdminUsersController {
  constructor(private readonly supabase: SupabaseService) {}

  @Get()
  async findAll() {
    const { data, error } = await this.supabase.admin.auth.admin.listUsers();
    if (error) {
      throw error;
    }
    return data.users.map(({ id, email }) => ({ id, email }));
  }
}
```

用 `AuthorizationModule.forRoot({{ '{' }} globalGuard: false {{ '}' }})` 注册该模块，并把 `AdminPolicy` 放进 `providers`。它的全局守卫默认开启，会拒绝每一条没有 `@Can()` 的路由，这也会把上面那些路由一并关掉。访客得到 `401`，没有该角色的用户得到 `403`。

#### 接收 Stripe webhook

[`@nestjs/webhooks`](/http/webhooks) 会校验 webhook 的签名，并记住已经处理过哪些事件。它通过 `@nestjs/outbox` 把状态保存在你的数据库中，放在各自独立的 schema 里。Supabase 的 API 不提供这些 schema，因此它们保持私有：

```bash
$ npm i --save @nestjs/webhooks @nestjs/outbox
```

签名覆盖的是 Stripe 发送的原始字节，所以创建应用时要启用 `rawBody`：

```typescript
@@filename(main)
const app = await NestFactory.create(AppModule, { rawBody: true });
```

在模块的 `receivers` 中指定发送方，签名密钥取自 Stripe 控制面板或 `stripe listen`。这个应用只接收 webhook，所以两个后台 worker 都不需要：

```typescript
OutboxModule.forRoot({ relay: { enabled: false } }),
WebhooksModule.forRoot({
  worker: { enabled: false },
  receivers: {
    stripe: { scheme: 'stripe', secret: process.env.STRIPE_WEBHOOK_SECRET! },
  },
}),
```

在 `providers` 中注册这两个存储。`migrate: true` 会在启动时创建它们的 schema，这适合开发环境（生产环境见[部署](/recipes/supabase#deployment)）：

```typescript
{
  provide: PostgresOutboxStore,
  inject: [getDrizzleToken(), OutboxStorage],
  useFactory: (db: NodePgDatabase, storage: OutboxStorage) =>
    new PostgresOutboxStore({ executor: fromDrizzle(db), migrate: true }, storage),
},
{
  provide: PostgresWebhookStore,
  inject: [getDrizzleToken(), WebhooksStorage],
  useFactory: (db: NodePgDatabase, storage: WebhooksStorage) =>
    new PostgresWebhookStore({ executor: fromDrizzle(db), migrate: true }, storage),
},
```

为 webhook 改动的数据新增一张表。只有 Nest 会读它，而无策略的行级安全把它挡在浏览器之外。把它加到一个新的迁移里：

```sql
create table public.subscriptions (
  stripe_customer text primary key,
  active boolean not null,
  expires_at timestamptz
);

alter table public.subscriptions enable row level security;
```

```typescript
@@filename(database/schema)
import { boolean, pgTable, text, timestamp } from 'drizzle-orm/pg-core';

export const subscriptions = pgTable('subscriptions', {
  stripeCustomer: text('stripe_customer').primaryKey(),
  active: boolean('active').notNull(),
  expiresAt: timestamp('expires_at', { withTimezone: true }),
});
```

这条路由是 `@Public()`，因为鉴权靠的是签名，签名无效则得到 `401`。`processInTransaction()` 会把事件 id 与你的改动记录在同一个事务中，所以重复投递不会改变任何东西：

```typescript
@@filename(billing/stripe-webhooks.controller)
import { Controller, HttpCode, Post } from '@nestjs/common';
import { Public } from '@nestjs/authentication';
import { InjectDrizzle } from '@nestjs/drizzle';
import { IncomingWebhook, VerifyWebhook } from '@nestjs/webhooks';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { subscriptions } from '../database/schema.js';

interface StripeEvent {
  id: string;
  type: string;
  data: { object: { customer: string; status: string; cancel_at: number | null } };
}

@Public()
@Controller('webhooks/stripe')
export class StripeWebhooksController {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  @Post()
  @HttpCode(200)
  @VerifyWebhook('stripe')
  async receive(@IncomingWebhook() webhook: IncomingWebhook<StripeEvent>) {
    const { type, data } = webhook.payload;
    if (type !== 'customer.subscription.updated') {
      return;
    }
    const { customer, status, cancel_at } = data.object;
    const values = {
      active: status === 'active',
      expiresAt: cancel_at ? new Date(cancel_at * 1000) : null,
    };
    await this.db.transaction(async (tx) =>
      webhook.processInTransaction(tx, async () => {
        await tx
          .insert(subscriptions)
          .values({ stripeCustomer: customer, ...values })
          .onConflictDoUpdate({ target: subscriptions.stripeCustomer, set: values });
      }),
    );
  }
}
```

要试用它，请用 [Stripe CLI](https://docs.stripe.com/stripe-cli) 把事件转发到你的应用，它会打印签名密钥，供你填入 `STRIPE_WEBHOOK_SECRET`：

```bash
$ stripe listen --forward-to localhost:3000/webhooks/stripe
$ stripe trigger customer.subscription.updated
```

#### 运行定时任务

在 Nest 中运行任务有两种方式。两者都能在任意数量的实例上工作，每次运行只发生在其中一个实例上：

|  | `@nestjs/schedule` 配合 `@nestjs/locks` | BullMQ |
| --- | --- | --- |
| **在哪里运行** | 在持有租约的实例中 | 在取到它的 worker 中 |
| **某次运行失败时** | 等待下一个 tick | 带退避地重试 |
| **所有实例都宕机时** | 该 tick 被错过 | 任务在队列中等待 |
| **给 Postgres 增加什么** | 一张表 | 一个独立的 schema |
| **还提供什么** | 别的都没有 | 从你的代码中入队的任务、优先级与流程 |
| **选它的理由** | 可以安全跳过的任务，下一个 tick 会补上 | 绝不能丢、或者运行时间很长的任务 |

两者都可以调用同一段代码：

```typescript
@@filename(billing/subscriptions.service)
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, eq, lt } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { subscriptions } from '../database/schema.js';

@Injectable()
export class SubscriptionsService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  /** 补上取消事件始终没有到达的订阅。 */
  async expireOverdue() {
    await this.db
      .update(subscriptions)
      .set({ active: false })
      .where(and(eq(subscriptions.active, true), lt(subscriptions.expiresAt, new Date())));
  }
}
```

> info **提示** [Supabase Cron](https://supabase.com/docs/guides/cron) 在 Postgres 内部调度 SQL，不涉及任何应用。它很适合纯 SQL 的任务，比如删除旧行。

##### 使用 `@nestjs/schedule` 与 `@nestjs/locks`

[`@nestjs/schedule`](/application/task-scheduling) 在应用内部运行任务，紧挨着它要调用的代码。单靠它，任务会在每个实例上运行。[`@nestjs/locks`](/reliability/locks) 增加了 `@OnOneInstance()`：第一个触发的实例取得租约，并在其存活期间执行每一个 tick，其余实例则跳过这些 tick。它停止后，另一个实例会接手，正常关闭后大约一秒，崩溃后 30 秒之内：

```bash
$ npm i --save @nestjs/schedule @nestjs/locks
```

```typescript
@@filename(billing/expire-subscriptions.job)
import { Injectable } from '@nestjs/common';
import { OnOneInstance } from '@nestjs/locks';
import { Cron, CronExpression } from '@nestjs/schedule';
import { SubscriptionsService } from './subscriptions.service.js';

@Injectable()
export class ExpireSubscriptionsJob {
  constructor(private readonly subscriptions: SubscriptionsService) {}

  @Cron(CronExpression.EVERY_HOUR)
  @OnOneInstance({ key: 'subscriptions:expire' })
  async run() {
    await this.subscriptions.expireOverdue();
  }
}
```

```typescript
ScheduleModule.forRoot(),
LocksModule.forRoot(),
```

租约必须存放在所有实例共享的地方，而在生产环境中，若只有默认的内存存储，应用会拒绝启动。把它放在你的数据库里，在新迁移中建一张表：

```sql
create table public.locks (
  key text primary key,
  owner text,
  fencing_token bigint not null,
  expires_at timestamptz not null
);

alter table public.locks enable row level security;

create sequence public.locks_fencing_token_seq;
```

然后从[把锁保存在数据库中](/reliability/locks#keep-locks-in-your-database)复制 Drizzle 表和 `DrizzleLockStore`，并把该存储加入 `providers`。

##### 使用 BullMQ

[BullMQ](/application/queues) 把任务保存在队列中，支持重试与退避。它通常运行在 Redis 上，同时也有 PostgreSQL 后端，因此在 Supabase 上它可以复用你已经拥有的数据库：

```bash
$ npm i --save @nestjs/bullmq bullmq
```

```typescript
BullModule.forRoot({
  backendFactory: createPostgresBackend,
  connection: { connectionString: process.env.DATABASE_URL!, migrate: true },
}),
BullModule.registerQueue({ name: 'billing' }),
```

`migrate: true` 会在启动时创建 `bullmq` schema，Supabase 的 API 不提供它。该迁移会获取一个建议锁，因此一起启动的多个实例只会应用它一次。

> info **提示** 想用 Redis，就安装 `ioredis`，并把那些选项换成 `connection: {{ '{' }} host, port {{ '}' }}`。其他都不用改。

任务调度器会在每个 tick 创建任务。id 使它成为一个调度，无论有多少实例声明它：

```typescript
@@filename(billing/billing.scheduler)
import { InjectQueue } from '@nestjs/bullmq';
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import type { Queue } from 'bullmq';

@Injectable()
export class BillingScheduler implements OnApplicationBootstrap {
  constructor(@InjectQueue('billing') private readonly billing: Queue) {}

  async onApplicationBootstrap() {
    await this.billing.upsertJobScheduler(
      'expire-subscriptions',
      { pattern: '0 * * * *' },
      {
        name: 'expire-subscriptions',
        opts: { attempts: 3, backoff: { type: 'exponential', delay: 1000 } },
      },
    );
  }
}
```

处理器负责运行它，落在哪个空闲的实例上就在哪个实例上运行：

```typescript
@@filename(billing/billing.processor)
import { Processor, WorkerHost } from '@nestjs/bullmq';
import type { Job } from 'bullmq';
import { SubscriptionsService } from './subscriptions.service.js';

@Processor('billing')
export class BillingProcessor extends WorkerHost {
  constructor(private readonly subscriptions: SubscriptionsService) {
    super();
  }

  async process(job: Job) {
    if (job.name === 'expire-subscriptions') {
      await this.subscriptions.expireOverdue();
    }
  }
}
```

同一个队列也承接你自己代码中的任务，比如一条不该等邮件发完的路由。用 `@InjectQueue('billing')` 注入队列，并在处理器中为该任务加一个分支：

```typescript
await this.billing.add('send-invoice', { customer }, {
  attempts: 3,
  backoff: { type: 'exponential', delay: 1000 },
});
```

#### 分发文件上传

浏览器可以在 `storage.objects` 表的策略约束下，直接上传到 Supabase Storage。当决定权在服务端时（例如配额或付费方案），请把存储桶设为私有，让 Nest 为每次上传签名。在迁移中创建存储桶：

```sql
insert into storage.buckets (id, name, public) values ('uploads', 'uploads', false);
```

```typescript
@@filename(uploads/uploads.controller)
import { randomUUID } from 'node:crypto';
import { Controller, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import type { SupabaseUser } from '../supabase/supabase-auth.js';
import { SupabaseService } from '../supabase/supabase.service.js';

@Controller('uploads')
export class UploadsController {
  constructor(private readonly supabase: SupabaseService) {}

  @Post()
  async create(@CurrentUser() user: SupabaseUser) {
    const path = `${user.id}/${randomUUID()}`;
    const { data, error } = await this.supabase.admin.storage.from('uploads').createSignedUploadUrl(path);
    if (error) {
      throw error;
    }
    return { path: data.path, token: data.token };
  }
}
```

随后浏览器直接上传到 Supabase，文件从不经过你的应用：

```typescript
await supabase.storage.from('uploads').uploadToSignedUrl(path, token, file);
```

要把文件交回，用管理客户端上的 `createSignedUrl(path, 60)` 生成一个 60 秒内有效的链接。

#### 针对本地栈做测试

端到端测试可以使用真实的令牌和你真实的策略，因为这个栈把两者都提供给你。把它放在 `test/` 下，并在运行前执行 `npx supabase start` 与 `npx supabase db reset`：

```typescript
@@filename(notes.e2e-spec)
import type { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { createClient } from '@supabase/supabase-js';
import { randomUUID } from 'node:crypto';
import request from 'supertest';
import { AppModule } from '../src/app.module.js';
import { SupabaseService } from '../src/supabase/supabase.service.js';

describe('Notes', () => {
  let app: INestApplication;

  const signUp = async () => {
    const client = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_PUBLISHABLE_KEY!, {
      auth: { persistSession: false, autoRefreshToken: false },
    });
    const { data, error } = await client.auth.signUp({
      email: `${randomUUID()}@example.test`,
      password: randomUUID(),
    });
    if (error) {
      throw error;
    }
    return { id: data.user!.id, token: data.session!.access_token };
  };

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
    app = moduleRef.createNestApplication();
    await app.init();
  });

  afterAll(() => app.close());

  it('shows a user only their own notes', async () => {
    const [alice, bob] = [await signUp(), await signUp()];
    await app.get(SupabaseService).admin.from('notes').insert([
      { user_id: alice.id, body: 'from alice' },
      { user_id: bob.id, body: 'from bob' },
    ]);

    const { body } = await request(app.getHttpServer())
      .get('/notes')
      .set('Authorization', `Bearer ${alice.token}`)
      .expect(200);

    expect(body).toEqual([{ body: 'from alice' }]);
  });
});
```

#### 把 Edge Function 迁移到 Nest

一个函数的大部分内容都有直接对应的做法，你可以一次迁移一个，因为两者使用相同的令牌和数据库：

| 在 Edge Function 中 | 在 Nest 中 |
| --- | --- |
| 读取 `Authorization` 头并调用 `supabase.auth.getUser()` | `SupabaseAuth` 与 `@CurrentUser()` |
| 用调用方请求头创建的客户端 | `SupabaseService.forUser()` |
| 用密钥创建的客户端 | `SupabaseService.admin` |
| 手动校验 Stripe 的签名 | `@VerifyWebhook('stripe')` |
| `pg_cron` 通过 HTTP 调用该函数 | `@Cron()`，或 BullMQ 任务调度器 |
| `supabase secrets set` | 你主机上的环境变量 |
| 浏览器中的 `supabase.functions.invoke('name')` | 带访问令牌的 `fetch()` |

#### 最终成品模块

下面是以上全部内容串在一起的样子，其中包含两种运行任务的方式，你只会保留一种：

```typescript
@@filename(app.module)
import { Module } from '@nestjs/common';
import { AuthenticationModule } from '@nestjs/authentication';
import { AuthorizationModule } from '@nestjs/authorization';
import { BullModule } from '@nestjs/bullmq';
import { ConfigModule } from '@nestjs/config';
import { DrizzleModule, getDrizzleToken } from '@nestjs/drizzle';
import { LocksModule } from '@nestjs/locks';
import { OutboxModule, OutboxStorage } from '@nestjs/outbox';
import { PostgresOutboxStore } from '@nestjs/outbox/postgres';
import { ScheduleModule } from '@nestjs/schedule';
import { WebhooksModule, WebhooksStorage } from '@nestjs/webhooks';
import { fromDrizzle, PostgresWebhookStore } from '@nestjs/webhooks/postgres';
import { createPostgresBackend } from 'bullmq';
import { drizzle, type NodePgDatabase } from 'drizzle-orm/node-postgres';
import { AdminUsersController } from './admin/admin-users.controller.js';
import { AdminPolicy } from './admin/admin.policy.js';
import { BillingProcessor } from './billing/billing.processor.js';
import { BillingScheduler } from './billing/billing.scheduler.js';
import { ExpireSubscriptionsJob } from './billing/expire-subscriptions.job.js';
import { StripeWebhooksController } from './billing/stripe-webhooks.controller.js';
import { SubscriptionsService } from './billing/subscriptions.service.js';
import { DrizzleLockStore } from './database/drizzle-lock.store.js';
import { RowLevelSecurity } from './database/row-level-security.js';
import { MeController } from './me/me.controller.js';
import { NotesController } from './notes/notes.controller.js';
import { NotesRepository } from './notes/notes.repository.js';
import { SupabaseAuth } from './supabase/supabase-auth.js';
import { SupabaseService } from './supabase/supabase.service.js';
import { UploadsController } from './uploads/uploads.controller.js';

@Module({
  imports: [
    ConfigModule.forRoot(), // 放第一位，因为下面的几行要读取 process.env
    AuthenticationModule.forRoot({}),
    AuthorizationModule.forRoot({ globalGuard: false }),
    DrizzleModule.forRoot({ drizzle, connection: process.env.DATABASE_URL! }),
    OutboxModule.forRoot({ relay: { enabled: false } }),
    WebhooksModule.forRoot({
      worker: { enabled: false },
      receivers: {
        stripe: { scheme: 'stripe', secret: process.env.STRIPE_WEBHOOK_SECRET! },
      },
    }),
    // 用 @nestjs/schedule 与 @nestjs/locks 运行的任务
    ScheduleModule.forRoot(),
    LocksModule.forRoot(),
    // 用 BullMQ 运行的任务
    BullModule.forRoot({
      backendFactory: createPostgresBackend,
      connection: { connectionString: process.env.DATABASE_URL!, migrate: true },
    }),
    BullModule.registerQueue({ name: 'billing' }),
  ],
  controllers: [
    MeController,
    NotesController,
    AdminUsersController,
    StripeWebhooksController,
    UploadsController,
  ],
  providers: [
    SupabaseAuth,
    SupabaseService,
    RowLevelSecurity,
    NotesRepository,
    AdminPolicy,
    SubscriptionsService,
    {
      provide: PostgresOutboxStore,
      inject: [getDrizzleToken(), OutboxStorage],
      useFactory: (db: NodePgDatabase, storage: OutboxStorage) =>
        new PostgresOutboxStore({ executor: fromDrizzle(db), migrate: true }, storage),
    },
    {
      provide: PostgresWebhookStore,
      inject: [getDrizzleToken(), WebhooksStorage],
      useFactory: (db: NodePgDatabase, storage: WebhooksStorage) =>
        new PostgresWebhookStore({ executor: fromDrizzle(db), migrate: true }, storage),
    },
    // 用 @nestjs/schedule 与 @nestjs/locks 运行的任务
    ExpireSubscriptionsJob,
    DrizzleLockStore,
    // 用 BullMQ 运行的任务
    BillingScheduler,
    BillingProcessor,
  ],
})
export class AppModule {}
```

```typescript
@@filename(main)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { rawBody: true });
  app.enableCors({ origin: process.env.WEB_ORIGIN });
  app.enableShutdownHooks();
  await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();
```

`enableShutdownHooks()` 让正在运行的任务得以完成，并在部署停止某个实例时把它的租约传递下去。

#### 部署

Nest 与 Supabase 分开部署，可运行在任何能跑 Node.js 的环境上（见[部署](/deployment)）。请把它托管在靠近数据库区域的机房，因为每次查询都要跨越这段距离。

把你的迁移应用到托管项目：

```bash
$ npx supabase link --project-ref your-project-ref
$ npx supabase db push
```

在主机上设置同样的环境变量，值取自托管项目，连接字符串取自[直接查询 Postgres](/recipes/supabase#query-postgres-directly)。每个实例都会为 Drizzle 和 BullMQ 各自打开连接，因此要按项目的[连接数上限](https://supabase.com/docs/guides/database/connection-management)来核算。

webhook 的存储不应在新版本启动时——也就是滚动部署进行到一半时——去改动 schema。请把这两个配置里的 `migrate: true` 去掉，并在新版本启动之前、设置好 `DATABASE_URL`，把它们的迁移作为一个步骤来应用。BullMQ 的那个可以保留，因为它在建议锁下以单个事务运行：

```bash
$ npx @nestjs/webhooks migrate
$ npx @nestjs/outbox migrate
```
