|
| 1 | +--- |
| 2 | +title: "Supabase database operations using Trigger.dev" |
| 3 | +sidebarTitle: "Supabase database operations" |
| 4 | +description: "These examples demonstrate how to run basic CRUD operations on a table in a Supabase database using Trigger.dev." |
| 5 | +--- |
| 6 | + |
| 7 | +import SupabaseDocsCards from "/snippets/supabase-docs-cards.mdx"; |
| 8 | + |
| 9 | +## Add a new user to a table in a Supabase database |
| 10 | + |
| 11 | +This is a basic task which inserts a new row into a table from a Trigger.dev task. |
| 12 | + |
| 13 | +### Key features |
| 14 | + |
| 15 | +- Shows how to set up a Supabase client using the `@supabase/supabase-js` library |
| 16 | +- Shows how to add a new row to a table using `insert` |
| 17 | + |
| 18 | +### Prerequisites |
| 19 | + |
| 20 | +- A [Supabase account](https://supabase.com/dashboard/) and a project set up |
| 21 | +- In your Supabase project, create a table called `user_subscriptions`. |
| 22 | +- In your `user_subscriptions` table, create a new column: |
| 23 | + - `user_id`, with the data type: `text` |
| 24 | + |
| 25 | +### Task code |
| 26 | + |
| 27 | +```ts trigger/supabase-database-insert.ts |
| 28 | +import { createClient } from "@supabase/supabase-js"; |
| 29 | +import { task } from "@trigger.dev/sdk/v3"; |
| 30 | +// Generate the Typescript types using the Supabase CLI: https://supabase.com/docs/guides/api/rest/generating-types |
| 31 | +import { Database } from "database.types"; |
| 32 | + |
| 33 | +// Create a single Supabase client for interacting with your database |
| 34 | +// 'Database' supplies the type definitions to supabase-js |
| 35 | +const supabase = createClient<Database>( |
| 36 | + // These details can be found in your Supabase project settings under `API` |
| 37 | + process.env.SUPABASE_PROJECT_URL as string, // e.g. https://abc123.supabase.co - replace 'abc123' with your project ID |
| 38 | + process.env.SUPABASE_SERVICE_ROLE_KEY as string // Your service role secret key |
| 39 | +); |
| 40 | + |
| 41 | +export const supabaseDatabaseInsert = task({ |
| 42 | + id: "add-new-user", |
| 43 | + run: async (payload: { userId: string }) => { |
| 44 | + const { userId } = payload; |
| 45 | + |
| 46 | + // Insert a new row into the user_subscriptions table with the provided userId |
| 47 | + const { error } = await supabase.from("user_subscriptions").insert({ |
| 48 | + user_id: userId, |
| 49 | + }); |
| 50 | + |
| 51 | + // If there was an error inserting the new user, throw an error |
| 52 | + if (error) { |
| 53 | + throw new Error(`Failed to insert new user: ${error.message}`); |
| 54 | + } |
| 55 | + |
| 56 | + return { |
| 57 | + message: `New user added successfully: ${userId}`, |
| 58 | + }; |
| 59 | + }, |
| 60 | +}); |
| 61 | +``` |
| 62 | + |
| 63 | +<Note> |
| 64 | + This task uses your service role secret key to bypass Row Level Security. There are different ways |
| 65 | + of configuring your [RLS |
| 66 | + policies](https://supabase.com/docs/guides/database/postgres/row-level-security), so always make |
| 67 | + sure you have the correct permissions set up for your project. |
| 68 | +</Note> |
| 69 | + |
| 70 | +### Testing your task |
| 71 | + |
| 72 | +To test this task in the [Trigger.dev dashboard](https://cloud.trigger.dev), you can use the following payload: |
| 73 | + |
| 74 | +```json |
| 75 | +{ |
| 76 | + "userId": "user_12345" |
| 77 | +} |
| 78 | +``` |
| 79 | + |
| 80 | +If the task completes successfully, you will see a new row in your `user_subscriptions` table with the `user_id` set to `user_12345`. |
| 81 | + |
| 82 | +## Update a user's subscription on a table in a Supabase database |
| 83 | + |
| 84 | +This task shows how to update a user's subscription on a table. It checks if the user already has a subscription and either inserts a new row or updates an existing row with the new plan. |
| 85 | + |
| 86 | +This type of task is useful for managing user subscriptions, updating user details, or performing other operations you might need to do on a database table. |
| 87 | + |
| 88 | +### Key features |
| 89 | + |
| 90 | +- Shows how to set up a Supabase client using the `@supabase/supabase-js` library |
| 91 | +- Adds a new row to the table if the user doesn't exist using `insert` |
| 92 | +- Checks if the user already has a plan, and if they do updates the existing row using `update` |
| 93 | +- Demonstrates how to use [AbortTaskRunError](https://trigger.dev/docs/errors-retrying#using-aborttaskrunerror) to stop the task run without retrying if an invalid plan type is provided |
| 94 | + |
| 95 | +### Prerequisites |
| 96 | + |
| 97 | +- A [Supabase account](https://supabase.com/dashboard/) and a project set up |
| 98 | +- In your Supabase project, create a table called `user_subscriptions` (if you haven't already) |
| 99 | +- In your `user_subscriptions` table, create these columns (if they don't already exist): |
| 100 | + |
| 101 | + - `user_id`, with the data type: `text` |
| 102 | + - `plan`, with the data type: `text` |
| 103 | + - `updated_at`, with the data type: `timestamptz` |
| 104 | + |
| 105 | +### Task code |
| 106 | + |
| 107 | +```ts trigger/supabase-update-user-subscription.ts |
| 108 | +import { createClient } from "@supabase/supabase-js"; |
| 109 | +import { AbortTaskRunError, task } from "@trigger.dev/sdk/v3"; |
| 110 | +// Generate the Typescript types using the Supabase CLI: https://supabase.com/docs/guides/api/rest/generating-types |
| 111 | +import { Database } from "database.types"; |
| 112 | + |
| 113 | +// Define the allowed plan types |
| 114 | +type PlanType = "hobby" | "pro" | "enterprise"; |
| 115 | + |
| 116 | +// Create a single Supabase client for interacting with your database |
| 117 | +// 'Database' supplies the type definitions to supabase-js |
| 118 | +const supabase = createClient<Database>( |
| 119 | + // These details can be found in your Supabase project settings under `API` |
| 120 | + process.env.SUPABASE_PROJECT_URL as string, // e.g. https://abc123.supabase.co - replace 'abc123' with your project ID |
| 121 | + process.env.SUPABASE_SERVICE_ROLE_KEY as string // Your service role secret key |
| 122 | +); |
| 123 | + |
| 124 | +export const supabaseUpdateUserSubscription = task({ |
| 125 | + id: "update-user-subscription", |
| 126 | + run: async (payload: { userId: string; newPlan: PlanType }) => { |
| 127 | + const { userId, newPlan } = payload; |
| 128 | + |
| 129 | + // Abort the task run without retrying if the new plan type is invalid |
| 130 | + if (!["hobby", "pro", "enterprise"].includes(newPlan)) { |
| 131 | + throw new AbortTaskRunError( |
| 132 | + `Invalid plan type: ${newPlan}. Allowed types are 'hobby', 'pro', or 'enterprise'.` |
| 133 | + ); |
| 134 | + } |
| 135 | + |
| 136 | + // Query the user_subscriptions table to check if the user already has a subscription |
| 137 | + const { data: existingSubscriptions } = await supabase |
| 138 | + .from("user_subscriptions") |
| 139 | + .select("user_id") |
| 140 | + .eq("user_id", userId); |
| 141 | + |
| 142 | + if (!existingSubscriptions || existingSubscriptions.length === 0) { |
| 143 | + // If there are no existing users with the provided userId and plan, insert a new row |
| 144 | + const { error: insertError } = await supabase.from("user_subscriptions").insert({ |
| 145 | + user_id: userId, |
| 146 | + plan: newPlan, |
| 147 | + updated_at: new Date().toISOString(), |
| 148 | + }); |
| 149 | + |
| 150 | + // If there was an error inserting the new subscription, throw an error |
| 151 | + if (insertError) { |
| 152 | + throw new Error(`Failed to insert user subscription: ${insertError.message}`); |
| 153 | + } |
| 154 | + } else { |
| 155 | + // If the user already has a subscription, update their existing row |
| 156 | + const { error: updateError } = await supabase |
| 157 | + .from("user_subscriptions") |
| 158 | + // Set the plan to the new plan and update the timestamp |
| 159 | + .update({ plan: newPlan, updated_at: new Date().toISOString() }) |
| 160 | + .eq("user_id", userId); |
| 161 | + |
| 162 | + // If there was an error updating the subscription, throw an error |
| 163 | + if (updateError) { |
| 164 | + throw new Error(`Failed to update user subscription: ${updateError.message}`); |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + // Return an object with the userId and newPlan |
| 169 | + return { |
| 170 | + userId, |
| 171 | + newPlan, |
| 172 | + }; |
| 173 | + }, |
| 174 | +}); |
| 175 | +``` |
| 176 | + |
| 177 | +<Note> |
| 178 | + This task uses your service role secret key to bypass Row Level Security. There are different ways |
| 179 | + of configuring your [RLS |
| 180 | + policies](https://supabase.com/docs/guides/database/postgres/row-level-security), so always make |
| 181 | + sure you have the correct permissions set up for your project. |
| 182 | +</Note> |
| 183 | + |
| 184 | +## Testing your task |
| 185 | + |
| 186 | +To test this task in the [Trigger.dev dashboard](https://cloud.trigger.dev), you can use the following payload: |
| 187 | + |
| 188 | +```json |
| 189 | +{ |
| 190 | + "userId": "user_12345", |
| 191 | + "newPlan": "pro" |
| 192 | +} |
| 193 | +``` |
| 194 | + |
| 195 | +If the task completes successfully, you will see a new row in your `user_subscriptions` table with the `user_id` set to `user_12345`, the `plan` set to `pro`, and the `updated_at` timestamp updated to the current time. |
| 196 | + |
| 197 | +<SupabaseDocsCards /> |
0 commit comments