使用JS的服务帐户调用Google bigquery

时间:2014-04-09 21:12:03

标签: javascript json google-bigquery

我使用以下代码通过使用客户帐户使用JS中的图表调用Gogole bigquery。 如何为Google服务帐户配置相同的脚本,例如,我也有p12密钥,但我可以传递此密钥信息。

     <html>
<head>
<script type="text/javascript" src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load('visualization', '1', { packages: ['geochart'] });
</script>
<script>
    // UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
    var project_id = 'xxxxx';
    var client_id = 'xxx.apps.googleusercontent.com';

    var config = {
        'client_id': client_id,       
        'scope': 'https://www.googleapis.com/auth/bigquery'
    };

    function runQuery() {
        var request = gapi.client.bigquery.jobs.query({
            'projectId': project_id,
            'timeoutMs': '30000',
            'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
        });
        request.execute(function (response) {
            var stateValues = [["State", "Age"]];
            $.each(response.result.rows, function (i, item) {
                var state = item.f[0].v;
                var age = parseFloat(item.f[1].v);
                var stateValue = [state, age];
                stateValues.push(stateValue);
            });
            var data = google.visualization.arrayToDataTable(stateValues);
            var geochart = new google.visualization.GeoChart(
                document.getElementById('map'));
            geochart.draw(data, { width: 556, height: 347, resolution: "provinces", region: "US" });
        });
    }

    function auth() {
        gapi.auth.authorize(config, function () {
            gapi.client.load('bigquery', 'v2', runQuery);
            $('#client_initiated').html('BigQuery client initiated');
        });
        $('#auth_button').hide();
    }
</script>
</head>

<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我从google bigquery文档中了解到 - 由于JS的安全原因,我们无法使用服务帐户。