Skip to content

Instantly share code, notes, and snippets.

@ahaverty
Last active April 26, 2018 13:46
Show Gist options
  • Save ahaverty/16f05d224f964e057f0c6a40bf3d3240 to your computer and use it in GitHub Desktop.
Save ahaverty/16f05d224f964e057f0c6a40bf3d3240 to your computer and use it in GitHub Desktop.
Firebase Test Call API
import * as functions from 'firebase-functions';
import * as rp from 'request-promise';
import { google } from 'googleapis';
let projectId: string = "my-firebase-project-id";
export let testFunctions = functions.pubsub.topic("testfunctions").onPublish(async (message, context) => {
let functionsToExecute = ["functionA", "functionB", "functionC", "functionD",]
let token: string = await generateAccessToken();
for (let i in functionsToExecute) {
let functionName = functionsToExecute[i];
await testCallFunction(functionName, token);
}
});
async function generateAccessToken(): Promise<string> {
var scopes = ["https://www.googleapis.com/auth/cloud-platform"];
const serviceAccountEmail = functions.config().priming.email;
const serviceAccountPrivateKey = functions.config().priming.private_key.replace(/\\n/g, '\n');
// Authenticate a JWT client with the service account.
var jwtClient = new google.auth.JWT(
serviceAccountEmail,
null,
serviceAccountPrivateKey,
scopes
);
// Use the JWT client to generate an access token.
let accessToken: string;
let credential = await jwtClient.authorize();
return credential.access_token;
}
async function testCallFunction(name: string, token: string) {
const options = {
method: 'POST',
uri: `https://content-cloudfunctions.googleapis.com/v1beta2/projects/${projectId}/locations/us-central1/functions/${name}:call`,
body: { "data": "{\"data\": {\"test\": true}}" },
headers: {
Authorization: `Bearer ${token}`
},
json: true
}
return await rp(options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment