Example: BigQuery Function

In this example you will learn how to send Glassfy Events to Google BigQuery database using a Glassfy Function

1. Setup a BigQuery Database

Setup the database following the instructions here Google guide

Create a table with all the fields you want to receive referencing this Glassfy events data documentation

Be sure to include all the fields you want to use in the sample code below in the TABLE_FIELDS array

2. Create the function in Glassfy

Use the code below and follow the instructions at the Glassfy Function Doc to upload it in the dashboard

Be sure to add two secrets: private_key_b64 & client_email that you can retrieve from the Google Cloud Console

3. You are now ready to go !

All your monetisation data will now be delivered to your BigQuery Database in real time

const { BigQuery } = require('@google-cloud/bigquery');
const { RetryError } = require('glassfy-function');

const datasetId = 'TestImportDataset';
const tableId = 'production';
const projectId = 'glassfy-test-project';

const atob = (base64) => Buffer.from(base64, 'base64').toString('binary');

exports.onEvent = async (event, ctx) => {
	
	console.log(`processing event ${event.id}`);
	
    // prepare the event
    const TABLE_FIELDS = [
        "id",
        "event_date",
        "source",
        "type",
        "environment",
        "store",
        "vendorid",
        "appid",
        "subscriberid",
        "productid",
        "date_ms",
        "original_purchase_date_ms",
        "price",
        "price_usd",
        "currency_code",
        "country_code",
        "sub_platform",
        "system_version",
        "device",
        "sdk_version",
        "bundle_version",
        "app_version",
        "is_trial_period",
        "trial_status",
        "userid"
    ];
    const bigQueryEvent = TABLE_FIELDS
        .filter(key => event[key])
        .reduce((prev, key) => {
            prev[key] = event[key];
            return prev;
        }, {});

	// credentials
	const private_key_b64 = ctx.settings["private_key_b64"];
	const credentials = {
		private_key: atob(private_key_b64),
		client_email: ctx.settings["client_email"]
	};
	
    // insert event
    const bigquery = new BigQuery({
        projectId,
        credentials
    });

    const createdRows = await bigquery
        .dataset(datasetId)
        .table(tableId)
        .insert([bigQueryEvent]);
    if (createdRows.length > 0) {
        const insertEvent = createdRows[0];
        if (insertEvent.insertErrors?.length) {
            console.debug(insertEvent.insertErrors);
            throw new RetryError("Error inserting row");
        }
    }
}