Skill 01 · Extension To Functions Codebase
Subchapter 1.2
references/destructuring-shim.mdMarkdown4 KBView on GitHub
The Destructuring Compatibility Shim is a Zero-Touch Logic Migration pattern. It allows you to upgrade a function’s infrastructure to V2 (and take advantage of GCF 2nd Gen runtimes) without rewriting any of your internal business logic.
When you migrate a V1 function to V2, the signature changes from two parameters
(data, context) to a single CloudEvent object.
Instead of manually rewriting all usages of context.params or message.json
inside the function, you use JavaScript’s Object Destructuring in the
signature.
export const processOrder = functions.pubsub.topic("orders").onPublish((message, context) => {
const orderId = message.json.id;
console.log(`Processing order ${orderId} at ${context.timestamp}`);
});We change the trigger to onMessagePublished, and instead of accepting event,
we destructure { message, context } directly:
export const processOrder = onMessagePublished("orders", ({ message, context }) => {
const orderId = message.json.id; // Legacy logic remains untouched!
console.log(`Processing order ${orderId} at ${context.timestamp}`);
});The Firebase Functions SDK uses a utility called addV1Compat to attach these
properties via Lazy Getters on the CloudEvent object for standard event
triggers. When you attempt to destructure { message, context } from the event,
the SDK transparently maps the V2 event properties back into V1-compatible
objects on the fly! This feature is available in modern V2 environments
supported by the SDK.
Here are the exact destructuring patterns for every supported V2 provider:
// V2: onDocumentCreated, onDocumentDeleted
export const processDoc = onDocumentCreated("users/{id}", ({ snapshot, context }) => { ... });// V2: onDocumentUpdated, onDocumentWritten
export const processDoc = onDocumentUpdated("users/{id}", ({ change, context }) => { ... });onObjectFinalized, onObjectDeleted, onObjectArchived,
onObjectMetadataUpdated):
export const processFile = onObjectFinalized(({ object, context }) => { ... });export const processData = onValueCreated("/users/{id}", ({ snapshot, context }) => { ... });export const processData = onValueWritten("/users/{id}", ({ change, context }) => { ... });export const processConfig = onConfigUpdated(({ version, context }) => { ... });{ shimmedKey, context }) by default to minimize risk and avoid
introducing subtle bugs.tsc) after the rewrite. If the types are wrong, the
shim might not be fully supported for that specific provider yet.V1Compat or a context object. Instead, all context properties
are flattened onto the request object.
(data, context) => { ... }({ data, auth, app }) => { ... }For a complete guide on migrating runtime options and functions.config() to V2
Parameterized Configuration, refer to
configuration-migration.md.