Call the Cloud Vision API with Cloud Functions for Firebase
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.json
of 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.js
edit. 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 ));
});