在Firebase Funcion中使用Google API

时间:2018-11-08 11:46:48

标签: javascript firebase google-cloud-functions google-authentication

我想使用Firebase函数中的google iot core API。 都可以,但是非常慢。我认为是由于身份验证过程需要一次调用。有没有办法加快速度?

现在我有这个:

function getClient(cb) {
    const API_VERSION = 'v1';
    const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
    const jwtAccess = new google.auth.JWT();
    jwtAccess.fromJSON(serviceAccount);
    // Note that if you require additional scopes, they should be specified as a
    // string, separated by spaces.
    jwtAccess.scopes = 'https://www.googleapis.com/auth/cloud-platform';
    // Set the default authentication to the above JWT access.
    google.options({ auth: jwtAccess });
    const discoveryUrl = `${DISCOVERY_API}?version=${API_VERSION}`;
    google.discoverAPI(discoveryUrl, {}).then( end_point => {
        cb(end_point);
    });
}

这使我可以这样做:

export function sendCommandToDevice(deviceId, subfolder, mqtt_data) {
    const cloudRegion = 'europe-west1';
    const projectId = 'my-project-id;
    const registryId = 'my-registry-id';

    getClient(client => {
        const parentName = `projects/${projectId}/locations/${cloudRegion}`;
        const registryName = `${parentName}/registries/${registryId}`;
        const binaryData = Buffer.from(mqtt_data).toString('base64');
        const request = {
            name: `${registryName}/devices/${deviceId}`,
            binaryData: binaryData,
            subfolder: subfolder
        };
        client.projects.locations.registries.devices.sendCommandToDevice(request,
            (err, data) => {
                if (err) {
                    console.log('Could not update config:', deviceId);
                }
            });
    });
}

我发现加快速度的方法是避免进行身份验证。我已经解决了这个问题:

const google = new GoogleApis();
const API_VERSION = 'v1';
const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
const jwtAccess = new google.auth.JWT();
jwtAccess.fromJSON(serviceAccount);
// Note that if you require additional scopes, they should be specified as a
// string, separated by spaces.
jwtAccess.scopes = 'https://www.googleapis.com/auth/cloud-platform';
// Set the default authentication to the above JWT access.
google.options({ auth: jwtAccess });
const discoveryUrl = `${DISCOVERY_API}?version=${API_VERSION}`;
var googleClient;
google.discoverAPI(discoveryUrl, {}).then( client => {
    //cb(end_point);
    googleClient = client;
});

// Returns an authorized API client by discovering the Cloud IoT Core API with
// the provided API key.
function getClient(cb) {
    cb(googleClient);
}

但是什么时候发生,然后客户端过期?从firebase函数使用google api有什么好的解决方案?

1 个答案:

答案 0 :(得分:0)

问题可能出在发现方面。有直接的IoT Core管理员REST API,因此您不必使用发现...我认为。我尚未使用Firebase Functions,但它们大致相当于Google Cloud Functions,它可能最终也可以在这里使用。如果您想修改一下,看看是否可以在Firebase Function中运行它,我们(在现场演示中执行的)运行的代码是here