Skip to content

Instantly share code, notes, and snippets.

@shinchit
Last active December 27, 2019 14:27
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 shinchit/25f166b75470f1a441b11bdbcd11d1d1 to your computer and use it in GitHub Desktop.
Save shinchit/25f166b75470f1a441b11bdbcd11d1d1 to your computer and use it in GitHub Desktop.
import * as Functions from "firebase-functions";
import * as Admin from "firebase-admin";
import * as CORS from "cors";
import * as ua from "universal-analytics";
Admin.initializeApp(Functions.config().firebase);
const someProcess = async (request: Functions.Request, response: Functions.Response) => {
let visitor = ua('UA-XXXXXXXX-X'); // set your Google Analytics account ID
visitor.pageview({dp: "/someprocess", dt: "SomeProcessExecuted"}).send();
send(response, 200, {
message: 'Success',
});
};
function send(response: Functions.Response, statusCode: number, body: any) {
response.send({
statusCode,
headers: { "Access-Control-Allow-Origin": "*" },
body: JSON.stringify(body),
});
}
exports.someProcess = Functions.https.onRequest((request, response) => {
const CORSRequestHandler = CORS({ origin: true });
CORSRequestHandler(request, response, () => {
if (request.method !== "POST") {
send(response, 405, { error: "Invalid Request" });
}
try {
someProcess(request, response)
.catch(err => {
console.log(err);
send(response, 500, {
error: err.message,
});
});
} catch(e) {
console.log(e);
send(response, 500, {
error: `The server received an unexpected error. Please try again and contact the site admin if the error persists.`,
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment