### Install Dependencies and Start Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/esm.md Commands to install project dependencies and start the Functions Framework locally for an ES Module function. ```sh npm i npm start ``` -------------------------------- ### Set up New Project with Functions Framework Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/README.md Initializes a new Node.js project, defines an HTTP function using the framework, installs the framework, and adds a start script for local development. ```bash npm init ``` ```javascript const functions = require('@google-cloud/functions-framework'); functions.http('helloWorld', (req, res) => { res.send('Hello, World'); }); ``` ```bash npm install @google-cloud/functions-framework ``` ```json "scripts": { "start": "functions-framework --target=helloWorld" } ``` ```bash npm start ``` ```bash curl localhost:8080 ``` -------------------------------- ### Configure Functions Framework in package.json Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/README.md Set command-line flags for the Functions Framework within the 'start' script in your package.json file. This example targets the 'helloWorld' function. ```json { "scripts": { "start": "functions-framework --target=helloWorld" } } ``` -------------------------------- ### Start the Functions Framework Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/cloudevents.md Start the Functions Framework locally using the npm start script. Your function will be available at http://localhost:8080/. ```bash npm start ``` -------------------------------- ### Configure Start Script for Functions Framework Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/cloudevents.md Add a 'start' script to your package.json to run the Functions Framework. Specify the target function and signature type. ```json { "scripts": { "start": "functions-framework --target=helloCloudEvents --signature-type=cloudevent" } } ``` -------------------------------- ### Install Required Packages Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript-pubsub.md Install the Functions Framework, Pub/Sub client library, and development dependencies for concurrent execution and live reloading. ```sh npm install @google-cloud/functions-framework npm install @google-cloud/pubsub npm install concurrently nodemon --save-dev ``` -------------------------------- ### Dockerfile for Node.js Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/docker.md This Dockerfile sets up a Node.js 10 environment, installs dependencies, copies application code, and configures the container to start the application using npm start. ```docker # Use the official Node.js 10 image. # https://hub.docker.com/_/node FROM node:10 # Create and change to the app directory. WORKDIR /usr/src/app # Copy application dependency manifests to the container image. # A wildcard is used to ensure both package.json AND package-lock.json are copied. # Copying this separately prevents re-running npm install on every code change. COPY package.json package*.json ./ # Install production dependencies. RUN npm install --only=production # Copy local code to the container image. COPY . . # Run the web service on container startup. CMD [ "npm", "start" ] ``` -------------------------------- ### Install Dependencies Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript.md Install the Functions Framework and Typescript as development dependencies. ```sh npm install @google-cloud/functions-framework npm install --save-dev typescript ``` -------------------------------- ### Run Conformance Tests Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/CONTRIBUTING.md Execute the conformance tests after installing Go 1.16+. Ensure Go is installed before running. ```bash npm run conformance ``` -------------------------------- ### Install Functions Framework Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/debugging.md Install the Functions Framework for Node.js using npm. This is a prerequisite for running your function locally. ```bash npm install @google-cloud/functions-framework ``` -------------------------------- ### Configure package.json for ES Modules Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/esm.md Sets up the `package.json` file to enable ES Module loading by specifying `"type": "module"` and configuring the start script. ```json { "type": "module", "scripts": { "start": "functions-framework --target=helloGET" }, "main": "index.js", "dependencies": { "@google-cloud/functions-framework": "^1.9.0" } } ``` -------------------------------- ### Write a Node.js Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/debugging.md Define your Cloud Function in an index.js file. This example shows a simple 'helloWorld' function. ```javascript exports.helloWorld = (req, res) => { res.send('Hello, World'); }; ``` -------------------------------- ### Configure package.json Scripts Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript.md Add build and start scripts to package.json. The 'gcp-build' script is used during deployment to Google Cloud Functions. ```json { "main": "dist/index.js", "scripts": { "build": "tsc", "start": "functions-framework --target=TypescriptFunction", "prestart": "npm run build", "gcp-build": "npm run build" }, ... } ``` -------------------------------- ### Deploy HTTP and Event-Triggered Functions Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Deploy Node.js functions to Google Cloud Run using the `gcloud` CLI. The framework is automatically installed if not in `package.json`. ```bash # Deploy an HTTP function gcloud functions deploy helloHttp \ --runtime nodejs22 \ --trigger-http \ --allow-unauthenticated \ --entry-point helloHttp \ --region us-central1 # Deploy a Pub/Sub event-triggered function gcloud functions deploy helloPubSub \ --runtime nodejs22 \ --trigger-topic my-topic \ --entry-point helloPubSub \ --region us-central1 # Deploy a TypeScript function (gcp-build script compiles it) gcloud functions deploy TypescriptFunction \ --runtime nodejs22 \ --trigger-http \ --allow-unauthenticated ``` -------------------------------- ### Local HTTP Function Example Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/README.md Defines and runs a local HTTP function. The --target flag specifies the function to execute. ```javascript exports.helloWorld = (req, res) => { res.send('Hello, World'); }; ``` ```bash npx @google-cloud/functions-framework --target=helloWorld ``` -------------------------------- ### Test Function with curl Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/docker.md Example of how to send a request to the locally running containerized function using curl and the expected output. ```sh curl localhost:8080 # Output: Hello, World ``` -------------------------------- ### Typescript HTTP Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript.md An example of a basic HTTP function written in Typescript. ```typescript import * as ff from '@google-cloud/functions-framework'; ff.http('TypescriptFunction', (req: ff.Request, res: ff.Response) => { res.send('OK'); }); ``` -------------------------------- ### Build Deployable Container Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/README.md Builds a Docker container for a function using Cloud Native Buildpacks. Ensure Docker and 'pack' are installed. The environment variables specify the function signature type and target. ```bash pack build \ --builder gcr.io/buildpacks/builder:v1 \ --env GOOGLE_FUNCTION_SIGNATURE_TYPE=http \ --env GOOGLE_FUNCTION_TARGET=helloWorld \ my-first-function ``` ```bash docker run --rm -p 8080:8080 my-first-function ``` ```bash curl localhost:8080 ``` -------------------------------- ### Node.js Cloud Function Example Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/events.md A basic Node.js function that logs incoming event data. Ensure the function name matches the --target in package.json. ```javascript exports.helloPubSub = (data, context) => { console.log(data); } ``` -------------------------------- ### Typescript CloudEvent Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript.md An example of a CloudEvent function in Typescript, with type annotation for the event payload. ```typescript import * as ff from '@google-cloud/functions-framework'; interface PubSubData { subscription: string; message: { messageId: string; publishTime: string; data: string; attributes?: {[key: string]: string}; }; } ff.cloudEvent('TypescriptFunction', ce => { console.log(ce.data?.message.messageId); }); ``` -------------------------------- ### Remove gts prepare script Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript-pubsub.md Remove the 'prepare' script from package.json. This script, added by gts, requires Typescript to be installed globally and can cause deployment failures if not removed. ```json "scripts": { "prepare": "npm run compile", ... } ``` -------------------------------- ### Initialize Node.js Project Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript.md Create a new Node.js project and navigate into its directory. ```sh mkdir typescript-function && cd typescript-function npm init -y ``` -------------------------------- ### Build and Run Docker Container Locally Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/docker.md Commands to build a Docker image tagged 'helloworld' from the current directory and then run it, exposing port 8080. ```sh docker build -t helloworld . && docker run --rm -p 8080:8080 helloworld ``` -------------------------------- ### Configure Pub/Sub Emulator Subscription Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/events.md Use the Pub/Sub client library to create a subscription pointing to the Functions Framework endpoint, enabling local testing with the emulator. ```javascript const { PubSub } = require('@google-cloud/pubsub'); async function main() { const apiEndpoint = 'localhost:8085'; console.log(`Listening to the Pub/Sub emulator event at: ${apiEndpoint}`); const pubsub = new PubSub({ apiEndpoint, // Pub/Sub emulator endpoint projectId: 'myproject', }); const topic = await pubsub.topic('my-topic'); const [topicExists] = await topic.exists(); if (!topicExists) { await topic.create(); } const createSubscriptionResponse = await topic.createSubscription('my_subscription', { pushEndpoint: 'http://localhost:8080/projects/myproject/topics/my-topic', }); } main(); ``` -------------------------------- ### CLI Configuration: Flags and Environment Variables Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Configure the Functions Framework using command-line flags or environment variables. Flags take precedence over environment variables. ```bash # Start with all options explicitly configured functions-framework \ --target=myFunction \ --port=3000 \ --signature-type=http \ --source=./dist \ --log-execution-id=true \ --timeout=300 \ --ignored-routes="/health|/metrics" ``` ```bash # Equivalent environment variable configuration export FUNCTION_TARGET=myFunction export PORT=3000 export FUNCTION_SIGNATURE_TYPE=http export FUNCTION_SOURCE=./dist export LOG_EXECUTION_ID=true export CLOUD_RUN_TIMEOUT_SECONDS=300 export IGNORED_ROUTES="/health|/metrics" functions-framework ``` ```json # package.json scripts example # { # "scripts": { # "start": "functions-framework --target=helloWorld --port=8080", # "start:events": "functions-framework --target=processEvent --signature-type=event", # "start:cloudevents": "functions-framework --target=processCloudEvent --signature-type=cloudevent" # } # } ``` -------------------------------- ### Initialize Project with gts Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript-pubsub.md Use gts to configure your Typescript project. This command initializes the project structure and necessary configurations. ```sh npx gts init ``` -------------------------------- ### Create Pub/Sub Topic Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript-pubsub.md Create a new Pub/Sub topic in your Google Cloud project. Replace `COOL_TOPIC` with your desired topic name. ```sh gcloud pubsub topics create COOL_TOPIC ``` -------------------------------- ### Compile Local Functions Framework Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/CONTRIBUTING.md Compile your local clone of the Functions Framework before linking it. ```bash npm compile ``` -------------------------------- ### Build, Push, and Deploy Container to Cloud Run Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/docker.md Commands to build a Docker image for Cloud Run, push it to Google Container Registry, and deploy it to Cloud Run. ```sh docker build -t gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld . docker push gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld gcloud run deploy helloworld --image gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld --region us-central1 ``` -------------------------------- ### Generate API Extractor Documentation Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/CONTRIBUTING.md Run this command to generate the API Extractor documentation. The generated files will be placed in the `docs/generated/` directory. ```bash npm run docs ``` -------------------------------- ### Configure package.json for Deployment Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript-pubsub.md Adjust the 'main' field in package.json to point to the compiled Javascript output. This ensures the Functions Framework can locate your function's entry point. ```json "main": "build/src/index.js", ``` -------------------------------- ### Containerize and Deploy with Docker Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Package a function as a Docker container for deployment to Cloud Run. This provides full environment control. Alternatively, use Buildpacks without a Dockerfile. ```dockerfile # Dockerfile FROM node:22-slim WORKDIR /usr/src/app COPY package*.json ./ RUN npm install --only=production COPY . . CMD ["npm", "start"] ``` ```bash # Build and run locally docker build -t my-function . docker run --rm -p 8080:8080 my-function # Test curl http://localhost:8080 # Output: Hello, World! # Deploy to Cloud Run docker build -t gcr.io/$GOOGLE_CLOUD_PROJECT/my-function . docker push gcr.io/$GOOGLE_CLOUD_PROJECT/my-function gcloud run deploy my-function \ --image gcr.io/$GOOGLE_CLOUD_PROJECT/my-function \ --platform managed \ --region us-central1 \ --allow-unauthenticated # Or use Buildpacks (no Dockerfile needed) pack build \ --builder gcr.io/buildpacks/builder:v1 \ --env GOOGLE_FUNCTION_SIGNATURE_TYPE=http \ --env GOOGLE_FUNCTION_TARGET=helloWorld \ my-function docker run --rm -p 8080:8080 my-function ``` -------------------------------- ### Configure Docker Credential Helper Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/docker.md Command to configure the Docker credential helper for gcloud, enabling authentication with Google Container Registry. ```sh gcloud auth configure-docker ``` -------------------------------- ### Configure Functions Framework for Events Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/events.md Specify --signature-type=event in package.json to configure the Functions Framework for event-driven functions. ```json { "scripts": { "start": "functions-framework --target=helloPubSub --signature-type=event" } } ``` -------------------------------- ### Run Node.js with Inspector for Debugging Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/debugging.md Execute your function using Node.js with the --inspect flag to enable the debugger. The Functions Framework is then run to serve your specified target function. ```bash node --inspect node_modules/.bin/functions-framework --target=helloWorld ``` ```text ... Debugger listening on ws://127.0.0.1:9229/5f57f5e9-ea4b-43ce-be1d-6e9b838ade4a For help see https://nodejs.org/en/docs/inspector Serving function... Function: helloWorld URL: http://localhost:8080/ ``` -------------------------------- ### Load Function for Testing with getFunction Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/testing-functions.md Use the `getFunction` helper from `@google-cloud/functions-framework/testing` to access functions registered with the Functions Framework. Ensure the module defining the function is loaded first. ```javascript import {getFunction} from "@google-cloud/functions-framework/testing"; describe("HelloTests", () => { before(async () => { // load the module that defines HelloTests await import("./hello_tests.js"); }); it("is testable", () => { // get the function using the name it was registered with const HelloTest = getFunction("HelloTests"); // ... }); }); ``` -------------------------------- ### Deploy Functions Framework Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript-pubsub.md Deploy your Pub/Sub triggered function using the gcloud CLI. Specify the function name, runtime, and the Pub/Sub topic to trigger it. ```sh gcloud functions deploy helloPubSub \ --runtime nodejs16 \ --trigger-topic COOL_TOPIC ``` -------------------------------- ### Link Local Functions Framework Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/CONTRIBUTING.md Link the Functions Framework locally after compiling it. This allows for local testing. ```bash npm link ``` -------------------------------- ### Integration Test HTTP Functions with SuperTest Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/testing-functions.md Utilize the `getTestServer` helper from the functions-framework/testing module to create a test server. This allows integration testing of HTTP functions using SuperTest for making mock requests. ```javascript import supertest from 'supertest'; import {getTestServer} from '@google-cloud/functions-framework/testing'; describe("HelloTests", function () { before(async () => { // load the module that defines HelloTests await import("./hello_tests.js"); }); it("uses works with SuperTest", async () => { // call getTestServer with the name of function you wish to test const server = getTestServer("HelloTests"); // invoke HelloTests with SuperTest await supertest(server) .post("/") .send({ some: "payload" }) .set("Content-Type", "application/json") .expect("Hello, World!") .expect(200); }); }); ``` -------------------------------- ### Configure tsconfig.json Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript.md Set up the Typescript compiler options for the project. ```json { "compilerOptions": { "target": "es2016", "module": "commonjs", "esModuleInterop": true, "strict": true, "outDir": "dist" }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` -------------------------------- ### Run Individual Unit Test Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/CONTRIBUTING.md Use this command to run a specific unit test. The `-g` flag filters tests by name. ```bash npm run test -- -g 'loading function' ``` -------------------------------- ### Debug Functions Locally with Node.js Inspector Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Enable interactive debugging for functions running locally by attaching the Node.js inspector. Configure your IDE's launch settings to connect to the specified port. ```bash # Attach the Node.js inspector to the Functions Framework process node --inspect node_modules/.bin/functions-framework --target=helloWorld # Output: # Debugger listening on ws://127.0.0.1:9229/5f57f5e9-ea4b-43ce-be1d-6e9b838ade4a # For help see https://nodejs.org/en/docs/inspector # Serving function... # Function: helloWorld # URL: http://localhost:8080/ # In VS Code, add to .vscode/launch.json: # { # "type": "node", # "request": "attach", # "name": "Attach to Functions Framework", # "port": 9229 # } ``` -------------------------------- ### Simulate Pub/Sub Message with cURL Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/events.md Use cURL to send a POST request with a mock Pub/Sub message payload to the Functions Framework endpoint for local testing. ```sh curl -d "@mockPubsub.json" \ -X POST \ -H "Ce-Type: true" \ -H "Ce-Specversion: true" \ -H "Ce-Source: true" \ -H "Ce-Id: true" \ -H "Content-Type: application/json" \ http://localhost:8080 ``` -------------------------------- ### Publish Message to Pub/Sub Topic Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript-pubsub.md Publish a test message to your Pub/Sub topic to verify that your deployed function is triggered and processes the message correctly. ```sh gcloud pubsub topics publish COOL_TOPIC --message="hello" ``` -------------------------------- ### ES Modules (ESM) Support Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Functions can be authored and loaded as native ES Modules by setting `"type": "module"` in `package.json`. Use `export const` for legacy-style functions or import the framework for declarative registration. ```javascript // index.js (ESM) import * as functions from '@google-cloud/functions-framework'; export const helloESM = (req, res) => { res.send('Hello from ESM!'); }; functions.http('helloESM', helloESM); ``` ```json // package.json // { // "type": "module", // "scripts": { // "start": "functions-framework --target=helloESM" // }, // "dependencies": { // "@google-cloud/functions-framework": "^5.0.0" // } // } ``` ```bash // curl http://localhost:8080 // # Output: Hello from ESM! ``` -------------------------------- ### Configure .gitignore Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript.md Ensure node_modules and compiled output are not committed to source control or uploaded during deployment. ```text node_modules/ dist/ ``` -------------------------------- ### Convert CommonJS to ES Module Syntax Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/esm.md Illustrates the syntax change required when migrating from CommonJS to ES Modules for defining Cloud Functions. ```javascript exports.helloGET = (req, res) => { res.send('No ESM.'); }; ``` ```javascript export const helloGET = (req, res) => { res.send('ESM!'); }; ``` -------------------------------- ### Test HTTP Function with Request/Response Stubs Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/testing-functions.md Test HTTP functions by creating simple request and response stubs. This allows you to invoke the function directly and assert against its output without a live server. ```javascript import assert from "assert"; import {getFunction} from "@google-cloud/functions-framework/testing"; describe("HelloTests", () => { before(async () => { // load the module that defines HelloTests await import("./hello_tests.js"); }); it("is testable", () => { // get the function using the name it was registered with const HelloTest = getFunction("HelloTests"); // a Request stub with a simple JSON payload const req = { body: { foo: "bar" }, }; // a Response stub that captures the sent response let result; const res = { send: (x) => { result = x; }, }; // invoke the function HelloTest(req, res); // assert the response matches the expected value assert.equal(result, "Hello, World!"); }); }); ``` -------------------------------- ### Send Test Request with cURL Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Use this command to send a test request to your locally running function. Ensure the Functions Framework is running on port 8080. ```bash curl http://localhost:8080 ``` -------------------------------- ### Unpublish a Specific Package Version Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/CONTRIBUTING.md Use this command to unpublish a specific version of the package. This action must be performed within 72 hours of publishing. If the time limit is exceeded, deprecate the release and publish a newer version instead. ```bash # Login to the Wombat Dressing Room. Create a 24 hour token. Close the window. npm login --registry https://wombat-dressing-room.appspot.com # Unpublish the package (must be done within 72 hours of publishing). # If >72 hours, deprecate a specific release and publish a newer version. # i.e. `npm deprecate @google-cloud/functions-framework@1.10.0 "Deprecate 1.10.0" # See https://docs.npmjs.com/policies/unpublish#what-to-do-if-your-package-does-not-meet-the-unpublish-criteria npm unpublish @google-cloud/functions-framework@1.10.0 # Set the default version to the previous working version. npm dist-tag add @google-cloud/functions-framework@1.9.0 latest --registry=https://wombat-dressing-room.appspot.com ``` -------------------------------- ### Basic HTTP Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/README.md Defines a simple HTTP function that sends 'Hello, World!'. This is the basic structure for an HTTP-triggered function. ```javascript /** * Send "Hello, World!" * @param req https://expressjs.com/en/api.html#req * @param res https://expressjs.com/en/api.html#res */ exports.helloWorld = (req, res) => { res.send('Hello, World!'); }; ``` -------------------------------- ### Deploy with gcloud CLI Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript.md Deploy the Typescript function to Google Cloud Functions using the gcloud CLI. ```sh gcloud functions deploy TypescriptFunction \ --runtime nodejs16 \ --trigger-http ``` -------------------------------- ### Integration Test a Function with getTestServer Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Use `getTestServer` to create an Express HTTP server for integration testing with SuperTest. Import the module that registers the function before calling `getTestServer`. ```javascript // test/integration.test.js import supertest from 'supertest'; import { getTestServer } from '@google-cloud/functions-framework/testing'; describe('helloHttp integration', () => { before(async () => { await import('../index.js'); // registers the function }); it('handles GET with query param', async () => { const server = getTestServer('helloHttp'); await supertest(server) .get('/?name=World') .expect(200) .expect('Content-Type', /json/) .expect({ message: 'Hello, World!' }); }); it('handles POST with JSON body', async () => { const server = getTestServer('helloHttp'); await supertest(server) .post('/') .set('Content-Type', 'application/json') .send({ name: 'SuperTest' }) .expect(200) .expect({ message: 'Hello, SuperTest!' }); }); }); ``` -------------------------------- ### Mock Pub/Sub Message Payload Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/events.md Define a JSON file to simulate the structure of a Pub/Sub message for local testing. ```json { "message": { "attributes": { "key": "value" }, "data": "SGVsbG8gQ2xvdWQgUHViL1N1YiEgSGVyZSBpcyBteSBtZXNzYWdlIQ==", "messageId": "136969346945" }, "subscription": "projects/myproject/subscriptions/mysubscription" } ``` -------------------------------- ### Test CloudEvent Functions with Mocks Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/testing-functions.md Use sinonjs to mock dependencies and assert function behavior. Ensure CloudEvent objects are correctly constructed for testing. ```javascript import assert from "assert"; import sinon from "sinon"; import {CloudEvent} from "cloudevents"; import {getFunction} from "@google-cloud/functions-framework/testing"; import {MyDependency} from "./my_dependency.js"; describe("HelloCloudEvent", () => { before(async () => { // load the module that defines HelloCloudEvent await import("./hello_cloud_event.js"); }); const sandbox = sinon.createSandbox(); beforeEach(() => { sandbox.spy(MyDependency); }); afterEach(() => { sandbox.restore(); }); it("uses MyDependency", () => { const HelloCloudEvent = getFunction("HelloCloudEvent"); HelloCloudEvent(new CloudEvent({ type: 'com.google.cloud.functions.test', source: 'https://github.com/GoogleCloudPlatform/functions-framework-nodejs', })); // assert that the cloud function invoked `MyDependency.someMethod()` assert(MyDependency.someMethod.calledOnce); }); }); ``` -------------------------------- ### Register an HTTP function with functions.http Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Use this to register a function that responds to HTTP requests. The handler receives Express Request and Response objects. All HTTP methods are accepted. ```javascript // index.js const functions = require('@google-cloud/functions-framework'); functions.http('helloHttp', (req, res) => { const name = req.query.name || req.body?.name || 'World'; res.status(200).json({ message: `Hello, ${name}!` }); }); // Start locally: // npx @google-cloud/functions-framework --target=helloHttp // // Test: // curl http://localhost:8080?name=Alice // # Output: {"message":"Hello, Alice!"} // // curl -X POST http://localhost:8080 \ // -H "Content-Type: application/json" \ // -d '{"name":"Bob"}' // # Output: {"message":"Hello, Bob!"} ``` -------------------------------- ### Functions Framework Output for Pub/Sub Message Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/events.md The expected output in the Functions Framework console when a simulated Pub/Sub message is received and processed. ```javascript { message: { attributes: { key: 'value' }, data: 'SGVsbG8gQ2xvdWQgUHViL1N1YiEgSGVyZSBpcyBteSBtZXNzYWdlIQ==', messageId: '136969346945' }, subscription: 'projects/myproject/subscriptions/mysubscription' } ``` -------------------------------- ### Compile Typescript to Javascript Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript-pubsub.md Compile your Typescript source files into Javascript. This command is typically part of the build process. ```sh npm run compile ``` -------------------------------- ### Create an ES Module Cloud Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/esm.md Defines a simple HTTP-triggered Cloud Function using ES Module syntax in `index.js`. ```javascript export const helloGET = (req, res) => { res.send('ESM!'); }; ``` -------------------------------- ### Send a CloudEvent to the Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/cloudevents.md Send a CloudEvent to your locally running function using the cloudevents CLI. Specify the target URL, event ID, source, and type. ```bash cloudevents send http://localhost:8080 --id abc-123 --source cloudevents.conformance.tool --type foo.bar ``` -------------------------------- ### Register Cloud Function Directly Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/testing-functions.md Register your function directly with the Functions Framework to benefit from implicit type hints and autocompletion. This method is suitable when explicit export is not required. ```javascript import * as functions from '@google-cloud/functions-framework'; // register the HelloTests with the Functions Framework functions.http('HelloTests', (req, res) => { // req and res are strongly typed here }); ``` -------------------------------- ### Legacy Exports-Style Functions (CommonJS) Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Supports legacy Cloud Functions-style exports for backwards compatibility without framework import. HTTP functions export a handler directly; event functions receive `(data, context)`. ```javascript // index.js — HTTP function (legacy export style) exports.helloWorld = (req, res) => { res.send('Hello, World!'); }; // index.js — Event (background) function (legacy export style) exports.helloPubSub = (data, context) => { const message = Buffer.from(data.data, 'base64').toString(); console.log(`Pub/Sub message: ${message}`); console.log(`Event ID: ${context.eventId}`); console.log(`Event type: ${context.eventType}`); console.log(`Resource: ${context.resource}`); }; ``` ```bash # Start with signature type: # functions-framework --target=helloPubSub --signature-type=event # # Simulate a Pub/Sub push subscription payload: # curl -X POST http://localhost:8080 \ # -H "Content-Type: application/json" \ # -H "Ce-Type: google.pubsub.topic.publish" \ # -H "Ce-Specversion: 1.0" \ # -H "Ce-Source: //pubsub.googleapis.com/projects/myproject/topics/my-topic" \ # -H "Ce-Id: msg-001" \ # -d '{ # "message": { # "data": "SGVsbG8gV29ybGQ=", # "messageId": "136969346945", # "attributes": {"env": "production"} # }, # "subscription": "projects/myproject/subscriptions/my-sub" # }' ``` -------------------------------- ### functions.http(name, handler) Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Registers a function to respond to HTTP requests. The handler receives Express Request and Response objects, extended with additional properties. All HTTP methods are accepted. ```APIDOC ## functions.http(name, handler) — Register an HTTP function Registers a function to respond to HTTP requests. The handler receives a full Express `Request` and `Response` object, extended with `rawBody`, `executionId`, `spanId`, and `abortController` properties. All HTTP methods are accepted. ### Example Usage ```js // index.js const functions = require('@google-cloud/functions-framework'); functions.http('helloHttp', (req, res) => { const name = req.query.name || req.body?.name || 'World'; res.status(200).json({ message: `Hello, ${name}!` }); }); ``` ### Local Execution and Testing ```bash # Start locally: npx @google-cloud/functions-framework --target=helloHttp # Test with GET request: curl http://localhost:8080?name=Alice # Output: {"message":"Hello, Alice!"} # Test with POST request: curl -X POST http://localhost:8080 \ -H "Content-Type: application/json" \ -d '{"name":"Bob"}' # Output: {"message":"Hello, Bob!"} ``` ``` -------------------------------- ### Register a CloudEvent function with functions.cloudEvent Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Use this to register a function that handles CloudEvents. The framework automatically unmarshals structured (JSON body) and binary (CE-* headers) CloudEvent formats. ```javascript // index.js const functions = require('@google-cloud/functions-framework'); functions.cloudEvent('processStorageEvent', (cloudevent) => { console.log('CloudEvent received:'); console.log(' ID: ', cloudevent.id); console.log(' Type: ', cloudevent.type); console.log(' Source: ', cloudevent.source); console.log(' Time: ', cloudevent.time); console.log(' Data: ', JSON.stringify(cloudevent.data)); }); // package.json scripts: // "start": "functions-framework --target=processStorageEvent --signature-type=cloudevent" // // Send a CloudEvent: // curl http://localhost:8080 \ // -X POST \ // -H "Content-Type: application/cloudevents+json" \ // -d '{ // "specversion": "1.0", // "type": "google.cloud.storage.object.v1.finalized", // "source": "//storage.googleapis.com/projects/_/buckets/my-bucket", // "id": "abc-123", // "time": "2024-01-15T12:00:00Z", // "data": {"name": "my-file.txt", "bucket": "my-bucket"} // }' ``` -------------------------------- ### Handle Google Cloud Functions Events Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/README.md Implement an 'event'-style function signature to receive and process Google Cloud Functions event payloads as 'data' and 'context' objects. Ensure the signature type is set to 'event' for automatic unmarshalling. ```javascript exports.helloEvents = (data, context) => { console.log(data); console.log(context); }; ``` -------------------------------- ### LegacyEvent Interface Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Represents a legacy event structure containing both context and data. ```typescript export interface LegacyEvent { // (undocumented) context: CloudFunctionsContext; // (undocumented) data: { [key: string]: any; }; } ``` -------------------------------- ### Pub/Sub Event Function in Typescript Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/typescript-pubsub.md Implement a Typescript function that receives and processes Pub/Sub messages. It decodes the message data from base64 and logs it to the console. ```typescript import {Context, EventFunction} from "@google-cloud/functions-framework/build/src/functions"; import {PubsubMessage} from "@google-cloud/pubsub/build/src/publisher"; export const helloPubSub: EventFunction = (message: PubsubMessage, context: Context) => { const data = message.data ? Buffer.from(message.data as string, "base64").toString() : "No Message"; console.log(data); }; ``` -------------------------------- ### Unit Test a Function with getFunction Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Use `getFunction` to retrieve a registered function for direct invocation in unit tests. Ensure the module that registers the function is imported before calling `getFunction`. ```javascript // test/hello.test.js import assert from 'assert'; import { getFunction } from '@google-cloud/functions-framework/testing'; // Load the module that registers the function describe('helloHttp', () => { before(async () => { await import('../index.js'); // registers functions.http('helloHttp', ...) }); it('responds with a greeting', () => { const fn = getFunction('helloHttp'); // Stub req and res const req = { query: { name: 'Alice' }, body: {} }; let responseBody; const res = { status: () => res, json: (body) => { responseBody = body; }, }; fn(req, res); assert.deepStrictEqual(responseBody, { message: 'Hello, Alice!' }); }); it('uses default name when none provided', () => { const fn = getFunction('helloHttp'); const req = { query: {}, body: {} }; let responseBody; const res = { status: () => res, json: (b) => { responseBody = b; } }; fn(req, res); assert.deepStrictEqual(responseBody, { message: 'Hello, World!' }); }); }); ``` -------------------------------- ### Define an HTTP Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Use the `http` function to register an HTTP handler. This function takes the name of the function and the handler itself as arguments. ```typescript export const http: (functionName: string, handler: HttpFunction) => void; ``` -------------------------------- ### Export Cloud Function for Testing Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/testing-functions.md Declare and export your Cloud Function to make it importable for unit tests. This approach decouples your application code from the Functions Framework. ```javascript import * as functions from '@google-cloud/functions-framework'; // declare a cloud function and export it so that it can be // imported in unit tests export const HelloTests = (req, res) => { res.send('Hello, World!'); }; // register the HelloTests with the Functions Framework functions.http('HelloTests', HelloTests); ``` -------------------------------- ### CloudFunctionsContext Interface Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Defines the structure for legacy Cloud Functions context properties. ```typescript export interface CloudFunctionsContext { eventId?: string; eventType?: string; resource?: string | { [key: string]: string; }; timestamp?: string; } ``` -------------------------------- ### functions.cloudEvent(name, handler) Source: https://context7.com/googlecloudplatform/functions-framework-nodejs/llms.txt Registers a function that handles CloudEvents spec-compliant events. The handler receives a CloudEvent object, and the framework automatically unmarshals both structured and binary CloudEvent formats. ```APIDOC ## functions.cloudEvent(name, handler) — Register a CloudEvent function Registers a function that handles [CloudEvents](https://cloudevents.io/) spec-compliant events. The handler receives a `CloudEvent` object from the `cloudevents` SDK. The framework automatically unmarshals both structured (JSON body) and binary (CE-* headers) CloudEvent formats. ### Example Usage ```js // index.js const functions = require('@google-cloud/functions-framework'); functions.cloudEvent('processStorageEvent', (cloudevent) => { console.log('CloudEvent received:'); console.log(' ID: ', cloudevent.id); console.log(' Type: ', cloudevent.type); console.log(' Source: ', cloudevent.source); console.log(' Time: ', cloudevent.time); console.log(' Data: ', JSON.stringify(cloudevent.data)); }); ``` ### Local Execution and Testing ```bash # package.json scripts: "start": "functions-framework --target=processStorageEvent --signature-type=cloudevent" # Send a CloudEvent: curl http://localhost:8080 \ -X POST \ -H "Content-Type: application/cloudevents+json" \ -d '{ "specversion": "1.0", "type": "google.cloud.storage.object.v1.finalized", "source": "//storage.googleapis.com/projects/_/buckets/my-bucket", "id": "abc-123", "time": "2024-01-15T12:00:00Z", "data": {"name": "my-file.txt", "bucket": "my-bucket"} }' ``` ``` -------------------------------- ### Defining a Typed Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Use the `typed` function for functions with specific input and output types, leveraging `InvocationFormat` for request deserialization and response serialization. ```APIDOC ## typed ### Description Defines a Cloud Function with specific input and output types, allowing for custom request/response handling. ### Parameters - **functionName** (string) - The name of the function. - **handler** (TypedFunction | ((req: T) => U | Promise)) - The function handler or a `TypedFunction` object. ### TypedFunction Signature ```typescript interface TypedFunction { format: InvocationFormat; handler: (req: T) => U | Promise; } ``` ### InvocationFormat An interface for defining how requests are deserialized and responses are serialized. ### Example ```typescript import functions from '@google-cloud/functions-framework'; interface MyRequest { name: string; } interface MyResponse { greeting: string; } // Using a handler function directly functions.typed('myTypedFunction', (req) => { return { greeting: `Hello, ${req.name}!` }; }); // Using a TypedFunction object with custom format (e.g., JsonInvocationFormat) import { JsonInvocationFormat } from '@google-cloud/functions-framework'; functions.typed('myCustomTypedFunction', { format: new JsonInvocationFormat(), handler: async (req) => { return { greeting: `Hello, ${req.name}!` }; } }); ``` ``` -------------------------------- ### JsonInvocationFormat Implementation Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Implements the `InvocationFormat` interface for JSON serialization and deserialization. Used for typed functions. ```typescript export class JsonInvocationFormat implements InvocationFormat { // (undocumented) deserializeRequest(request: InvocationRequest): T; // (undocumented) serializeResponse(responseWriter: InvocationResponse, response: U): void; } ``` -------------------------------- ### Defining an HTTP Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Use the `http` function to define an HTTP-triggered Cloud Function. It takes the function name and a handler function that accepts Express `Request` and `Response` objects. ```APIDOC ## http ### Description Defines an HTTP-triggered Cloud Function. ### Parameters - **functionName** (string) - The name of the function. - **handler** (HttpFunction) - The function handler that processes requests and sends responses. ### HttpFunction Signature ```typescript (req: Request, res: Response) => any; ``` ### Example ```typescript import functions from '@google-cloud/functions-framework'; import { Request, Response } from 'express'; functions.http('myHttpFunction', (req: Request, res: Response) => { res.send(`Hello ${req.query.name || 'World'}!`); }); ``` ``` -------------------------------- ### Define a CloudEvent Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Use the `cloudEvent` function to register a CloudEvent handler. This function takes the name of the function and the handler itself as arguments. ```typescript export const cloudEvent: (functionName: string, handler: CloudEventFunction) => void; ``` -------------------------------- ### Data Interface Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Interface for data payload, typically used in legacy event functions. ```typescript export interface Data { // (undocumented) data: object; } ``` -------------------------------- ### InvocationFormat Interface Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Defines the interface for custom request deserialization and response serialization for typed functions. ```typescript export interface InvocationFormat { deserializeRequest(request: InvocationRequest): T | Promise; serializeResponse(responseWriter: InvocationResponse, response: U): void | Promise; } ``` -------------------------------- ### Response Type Alias Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Provides an alias for the Express Response type. ```typescript export { Response_2 as Response } ``` -------------------------------- ### Defining a CloudEvent Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Use the `cloudEvent` function to define a CloudEvents-triggered Cloud Function. It accepts the function name and a handler that receives a CloudEvent object. ```APIDOC ## cloudEvent ### Description Defines a CloudEvents-triggered Cloud Function. ### Parameters - **functionName** (string) - The name of the function. - **handler** (CloudEventFunction) - The function handler that processes CloudEvents. ### CloudEventFunction Signature ```typescript (cloudEvent: CloudEvent) => any; ``` ### Example ```typescript import functions from '@google-cloud/functions-framework'; import { CloudEvent } from 'cloudevents'; interface MyEventData { message: string; } functions.cloudEvent('myCloudEventFunction', (event: CloudEvent) => { console.log('Received CloudEvent:', event.data.message); }); ``` ``` -------------------------------- ### InvocationResponse Interface Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Represents the response object for invocation, providing methods to write data and set headers. ```typescript export interface InvocationResponse { end(data: string | Buffer): void; setHeader(key: string, value: string): void; write(data: string | Buffer): void; } ``` -------------------------------- ### InvocationRequest Interface Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Represents an incoming request for invocation, providing methods to access the body and headers. ```typescript export interface InvocationRequest { body(): string | Buffer; header(header: string): string | undefined; } ``` -------------------------------- ### Context Type Alias Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md A type alias for context, which can be either `CloudFunctionsContext` or a `CloudEvent`. ```typescript export type Context = CloudFunctionsContext | CloudEvent; ``` -------------------------------- ### HttpFunction Interface Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Represents a standard HTTP function handler that receives a request and response object. ```typescript export interface HttpFunction { // (undocumented) (req: Request_2, res: Response_2): any; } ``` -------------------------------- ### http Function Export Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md.api.md Exports an HTTP function to be deployed on Google Cloud Functions. This function will be invoked for incoming HTTP requests. ```APIDOC ## http Function Export ### Description Exports an HTTP function that can be deployed to Google Cloud Functions. This function is designed to handle incoming HTTP requests. ### Method Signature `http(functionName: string, handler: HttpFunction): void` ### Parameters - `functionName` (string): The name of the function to export. This name is used for deployment and invocation. - `handler` (HttpFunction): The function to be executed in response to HTTP requests. It receives `Request` and `Response` objects. ### HttpFunction Interface ```ts interface HttpFunction { (req: Request, res: Response): any; } ``` ### Example Usage ```javascript const functions = require('@google-cloud/functions-framework'); functions.http('myHttpFunction', (req, res) => { res.send(`Hello, ${req.query.name || 'World'}!`); }); ``` ``` -------------------------------- ### EventFunction Interface Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Represents a legacy event function handler that receives data and context. ```typescript export interface EventFunction { // (undocumented) (data: {}, context: Context): any; } ``` -------------------------------- ### EventFunctionWithCallback Interface Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Represents a legacy event function handler that uses a callback for asynchronous operations. ```typescript export interface EventFunctionWithCallback { // (undocumented) (data: {}, context: Context, callback: Function): any; } ``` -------------------------------- ### LegacyCloudFunctionsContext Type Alias Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md A type alias for legacy context, which can be `CloudFunctionsContext` or `Data`. ```typescript export type LegacyCloudFunctionsContext = CloudFunctionsContext | Data; ``` -------------------------------- ### Declare a CloudEvent Function Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/cloudevents.md Declare a CloudEvent function in your index.js file. This function will be triggered by CloudEvents. ```javascript const functions = require('@google-cloud/functions-framework'); functions.cloudEvent('helloCloudEvents', (cloudevent) => { console.log(cloudevent.specversion); console.log(cloudevent.type); console.log(cloudevent.source); console.log(cloudevent.subject); console.log(cloudevent.id); console.log(cloudevent.time); console.log(cloudevent.datacontenttype); }); ``` -------------------------------- ### CloudEventFunctionWithCallback Interface Source: https://github.com/googlecloudplatform/functions-framework-nodejs/blob/main/docs/generated/api.md Represents a CloudEvent function handler that uses a callback for asynchronous operations. ```typescript export interface CloudEventFunctionWithCallback { // (undocumented) (cloudEvent: CloudEvent, callback: Function): any; } ```