Typescript types for google cloud function's event and context

Viewed 1005

I am trying out google cloud functions using typescript. I would like the function to be triggered by message from PubSub. The general format of the function is as follows

exports.readMessage = async (event, context): Promise<void> => {
  const message = event.data
    ? Buffer.from(event.data, "base64").toString()
    : "No Message";
  console.log(message);}

I have error as typescript complains about any type for event and context. package @google-cloud/PubSub mentions that it exports its types but I don't see any types related to event or context.

Any pointers to what am I missing and from which package I can import the types?

1 Answers

I don't have experience with this library but try my best to help you.

From the code, it should be receiving the message from Google Cloud Function (GCF) and the context is actually the metadata returned by GCF after the Pub event.

The event should be the pub/sub message, so the type is PubsubMessage.

In order to get the context type, there is a need to add GCF library.

yarn add @google-cloud/functions-framework
or 
npm install @google-cloud/functions-framework
// context type
import { Context } from "@google-cloud/functions-framework/build/src/functions";

// event message type
import { PubsubMessage } from "@google-cloud/pubsub/build/src/publisher";

exports.readMessage = async (event: PubsubMessage, context: Context): Promise<void> => {
  // event.data can be Uint8Array|string|null, so need to cast it as string explicitly to allow base64 operations.
  const message = event.data
    ? Buffer.from(event.data as string, "base64").toString()
    : "No Message";
  console.log(message);
}
Related