Resource
Resources are the core building blocks of Alchemy. Each resource represents a piece of infrastructure or configuration that can be created, updated, and deleted automatically.
What is a Resource?
Section titled “What is a Resource?”A Resource is simply a memoized async function that implemented a lifecycle handler for three phases:
create
- what to do when first creating the resourceupdate
- what to do when updating a resourcedelete
- what to when deleting a resource
Resource ID
Section titled “Resource ID”When creating a resource, you always pass an id
that is unique within the Resource’s Scope.
await MyResource("id")
This ID is what Alchemy uses to track the state of the resource and trigger the appropriate create/update/delete phase.
Resource Props
Section titled “Resource Props”Each Resource has an interface for its “input properties”
export interface DatabaseProps { name: string; branchId: string; projectId: string; // Other properties...}
Resource Instance
Section titled “Resource Instance”Each Resource has an interface for its “output attributes”:
export interface Database extends Resource<"neon::Database">, DatabaseProps { id: string; createdAt: number; // Additional properties...}
Resource Provider
Section titled “Resource Provider”Each Resource exports a “Provider” function with a globally unique name and an implementation of the lifecycle handler logic.
export const Database = Resource( "neon::Database", async function(this: Context<Database>, id: string, props: DatabaseProps): Promise<Database> { if (this.phase === "delete") { // Delete resource logic // ... return this.destroy(); } else if (this.phase === "update") { // Update resource logic // ... return this({/* updated resource */}); } else { // Create resource logic // ... return this({/* new resource */}); } });
Let’s break this down a bit futher, since it may seem confusing at first.
Resource FQN
Section titled “Resource FQN”Each Resource has a globally unique name (aka. fully qualified name), e.g "neon:Database"
:
export const Database = Resource("neon::Database"),
Alchemy and uses this FQN to delete orphaned resources (stored in your State files) by looking up the corresponding “provider”.
Lifecycle Function
Section titled “Lifecycle Function”The Resource’s lifecycle handler is defined using an async function
declaration with 3 required arguments:
async function( // the resource's state/context is bound to `this` this: Context<Database>, // the id of the resource (unique within a SCope) id: string, // the input properties props: DatabaseProps): Promise<Database>
Lifecycle Phases
Section titled “Lifecycle Phases”The lifecycle handler is a simple function that handles the 3 phases: "create"
, "update"
or "delete"
:
if (this.phase === "delete") { // Delete resource logic // ... return this.destroy();} else if (this.phase === "update") { // Update resource logic // ... return this({/* updated properties */});} else { // Create resource logic // ... return this({/* initial properties */});}
this.destroy()
Section titled “this.destroy()”When a resource is being deleted, you must return this.destroy()
to signal that the resource deletion process is complete.
this({..})
Section titled “this({..})”To construct the resource (including your properites and Alchemy’s intrinsic properties), call this(props)
with your output properties:
return this({/* updated properties */});
What’s going on here? this
is a function? Huh?
Alchemy resources are implemented with pure functions, but are designed to emulate classes (except with an async constructor that implements a CRUD lifecycle handler).
this
is analagous to super
in a standard class:
return super({/* updated properties */});
Adoption
Section titled “Adoption”When creating a resource, Alchemy will fail if a resource with the same name already exists. Resource adoption allows you to opt in to using the pre-existing resource instead.
// Without adoption - fails if bucket already existsconst bucket = await R2Bucket("my-bucket", { name: "existing-bucket",});
// With adoption - uses existing bucket if it existsconst bucket = await R2Bucket("my-bucket", { name: "existing-bucket", adopt: true,});
During the create phase, if a resource already exists:
- Without adoption (default): Throws an “already exists” error
- With adoption: Finds and adopts the existing resource
Replacement
Section titled “Replacement”Sometimes it’s impossible to UPDATE a resource (e.g., you cannot rename an R2 Bucket). In these cases, you need to perform a REPLACE operation to create a new version and delete the old one.
// Trigger replacement during update phaseif (this.phase === "update") { if (this.output.name !== props.name) { // Trigger replace and terminate this "update" phase this.replace(); // (unreachable code) } else { return updateResource(); }}
After calling this.replace()
, the “update” phase terminates and re-invokes with “create” to create the new resource. The old resource is deleted when you call app.finalize()
.
Testing
Section titled “Testing”See the Testing documentation for a comprehensive walkthrough on how to test your own resources.