Skip to content

Instantly share code, notes, and snippets.

@cathandnya
Created July 28, 2023 05:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cathandnya/33c962d2394b1407b568a962144b8cf2 to your computer and use it in GitHub Desktop.
Save cathandnya/33c962d2394b1407b568a962144b8cf2 to your computer and use it in GitHub Desktop.
functionCall.ts
export const functionCall = async (method: string, body: any): Promise<any> => {
console.log("functionCall", method);
// Constants for setting up metadata server request
// See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
const functionURL = `https://${REGION}-${PROJECT_ID}.cloudfunctions.net/${method}`;
const metadataServerURL =
"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=";
const tokenUrl = metadataServerURL + functionURL;
// Fetch the token
console.log("functionCall get token", tokenUrl);
const tokenResponse = await fetch.default(tokenUrl, {
headers: {
"Metadata-Flavor": "Google",
},
});
const token = await tokenResponse.text();
// Provide the token in the request to the receiving function
console.log("functionCall fetch", token);
const bodyText = JSON.stringify(body);
console.log("functionCall fetch body", bodyText);
const res = await fetch.default(functionURL, {
method: "POST",
headers: { Authorization: `bearer ${token}` },
body: bodyText,
});
const json = await res.json();
console.log("functionCall fetch result", json);
return json;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment