Call the Cloud Vision API with Cloud Functions for Firebase

shogo.yamada
2 min readAug 2, 2019

--

I leave it as a note.
I made it move with copy and paste.

It is premised that you pre-configure GCP and Firebase settings.

First package.jsonof all dependencies, copy below.

"dependencies": {
"@google-cloud/storage": "^3.0.3",
"@google-cloud/vision": "^1.1.3",
"firebase-admin": "^7.0.0",
"firebase-functions": "^3.2.0",
},

After copying, execute the following command

npm install

Then index.jsedit. It should move with copy and paste.
The following implementation is triggered by the file being uploaded to Firebase Storage. In case of another trigger, please change accordingly.

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp(functions.config().firebase);
const vision = require("@google-cloud/vision").v1p1beta1;
const client = new vision.ImageAnnotatorClient();

// resize process image
export const DetectImage = functions . Storage
. Object ()
. OnFinalize ( async object => {
// file path acquired
const filePath = `gs: // $ { object . Bucket } / $ { object . name } ` ;
// Get ContentType
const contentType = object . contentType ;

if ( filePath == null) Return Null ;
If ( ContentType == Null ) Return Null ;

// not When was other than the image nothing
If ( ! ContentType . StartsWith ( " Image / " )) {
Console . Log ( " This is not a image " ) ;
return ;
}

an if ( typeof filePath === " undefined " ) {
console . log ( "filePath undefined");
return;
}

return (async () => {
const data = await client.labelDetection(filePath);
console.log(data[0].labelAnnotations);
})()
.then(() => console.log("success"))
.catch(err => console. Log ( " An error has occurred " Tasu Err ));
});

reference

--

--

shogo.yamada
shogo.yamada

Written by shogo.yamada

普段はエンジニアやってます👨‍💻 自分の資産運用の記録として書いてり、プライベートなことを書いていきます。

Responses (1)