Zvika Badalov
Zvika Badalov

Reputation: 193

How to define a Google Cloud Function with Typescript?

I am trying to setup a NodeJS function using Google Cloud Function (GCF) in typescript. I am trying to be strict with my code which requires definition for all parameters in which case the (req, res) parameter needs to be define.

I know that GCF uses Express under the hood but I don't think I need to import Express because of that. Are there any best practices or documentation that explains how to use typescript with GCF?

I tried using the @google-cloud/functions-framework package and find there are any helpful interfaces or classes to use but I cannot determine what should be the starting point of the function.

import GCF from '@google-cloud/functions-framework';

export const startFunction = ((req: GCF.???, res: GCF.???)): void => {
  // additional work done here
}

Any help is greatly appreciated.

Upvotes: 10

Views: 15300

Answers (2)

Shrike
Shrike

Reputation: 9500

import type {HttpFunction} from '@google-cloud/functions-framework/build/src/functions';
import express, { query } from 'express';

export const main: HttpFunction =
  async (req: express.Request, res: express.Response) => {
    console.log(req.query);
  }

in your package.json we'll have only dev dependencies:

  "devDependencies": {
    "@google-cloud/functions-framework": "^3.1.2",
    "@types/express": "^4.17.13",
  }

Upvotes: 0

Daniel M.
Daniel M.

Reputation: 3505

Looks like the latest @google-cloud/functions-framework includes the function signatures now.

// Start writing Cloud Functions
// https://cloud.google.com/functions/docs/writing/http

import { HttpFunction } from '@google-cloud/functions-framework/build/src/functions';

export const helloHttp: HttpFunction = (req, res) => {
  res.send(`Hello World`);
};

Upvotes: 11

Related Questions