Cloud Functions中的存储触发器将永远循环

时间:2018-09-10 19:45:27

标签: node.js google-cloud-functions

我具有此功能,可以从Google存储桶中检索上传的图像,然后生成图像的缩略图。该功能运行良好,但不会停止运行。 这是功能

 const thumbarray = []
 exports.generateTHUMBPIC = 
functions.storage.object('productpics/{pushId}').onFinalize((object, context) => {

// [START eventAttributes]
const fileBucket = object.bucket; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
const resourceState = object.resourceState; // The resourceState is 'exists' or 'not_exists' (for file/folder deletions).
const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.

const fileDir1 = path.dirname(filePath);
const fileName0 = path.basename(filePath);

const fileDir = fileDir1.replace('productpics/', '')

console.log("file directory ***********",fileDir)

console.log("This is the object ",object)
 console.log("This is the object ",context)

var listingid = fileDir.split("*")[1];
var userid = fileDir.split("*")[0];
var productid = fileDir.split("*")[2];
var thumbname = fileDir.split("*")[3]; // thumbnail 1 or 2 or 3
thumbarray.push(thumbname);
console.log("product id  ^^^^^^^^^^^^^^^",productid)

console.log("This is the file path ",filePath)
console.log('This is the created path',"productpics/ "+ context.params.pushId +" /productimg" );



const thumbFilePath = path.normalize(path.join(fileDir1, `${THUMB_PREFIX}${productid}`));
const tempLocalFile = path.join(os.tmpdir(), filePath);
const tempLocalDir = path.dirname(tempLocalFile);
const tempLocalThumbFile = path.join(os.tmpdir(), thumbFilePath);
const thumbnail_bucket = "thumbnails/"+fileDir;


    console.log('This is the thumb nail bucket ', thumbnail_bucket);

// [END eventAttributes]

// [START stopConditions]
// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith('image/')) {
    console.log('This is not an image.');
    return null;
}


// Exit if the image is already a thumbnail.
if (productid.startsWith(THUMB_PREFIX)) {
    console.log('Already a Thumbnail.');
    return null;
}

// Download file from bucket.
const bucket = gcs.bucket(fileBucket);
const file = bucket.file(filePath);
const thumbFile = bucket.file(thumbFilePath);

const metadata = {
    contentType: contentType,
};
// Create the temp directory where the storage file will be downloaded.
return mkdirp(tempLocalDir).then(() => {

    console.log("This is the tempLocalfile ", tempLocalFile)
    // Download file from bucket.
    return file.download({
        destination: tempLocalFile
    });
}).then(() => {
     // Generate a thumbnail using ImageMagick.
    return spawn('convert', [tempLocalFile, '-thumbnail', `${THUMB_MAX_WIDTH}x${THUMB_MAX_HEIGHT}>`, tempLocalThumbFile], {
        capture: ['stdout', 'stderr']
    });
}).then(() => {
    console.log('Thumbnail created at', tempLocalThumbFile);
    // Uploading the Thumbnail.
               console.log("thumb file use to be saved in ",thumbFilePath)

    return bucket.upload(tempLocalThumbFile, {
        destination: thumbnail_bucket,
        metadata: metadata
    });
})
   .then(() => {
    console.log('Thumbnail uploaded to Storage at', thumbnail_bucket);
    // Once the image has been uploaded delete the local files to free up disk space.
    fs.unlinkSync(tempLocalFile);
    // fs.unlinkSync(tempLocalThumbFile);
    // Get the Signed URLs for the thumbnail and original image.
    const config = {
        action: 'read',
        expires: '03-01-2500',
    };
    return Promise.all([
        thumbFile.getSignedUrl(config),
        file.getSignedUrl(config),
    ]);
}).then((results) => {
    // console.log('Got Signed URLs.');
    // var thumbname = fileName0.split("*")[2];

    const thumbResult = results[0];
    const originalResult = results[1];
    const thumbFileUrl = thumbResult[0];
    const fileUrl = originalResult[0];

    var updates = {};


    updates['Listings/' + listingid + "/" + thumbname + "thumb"] = thumbFileUrl;
    // updates['Listings/' + fileName +'/'+ thumbname] = thumbFileUrl;

    return admin.database().ref().update(updates);


}).then(() => console.log('Thumbnail URLs saved to database.'));
})

我无法弄清楚我做错了什么。似乎正在触发自己。我该如何解决?

1 个答案:

答案 0 :(得分:0)

如果在Cloud Storage触发期间将文件上传到Cloud Storage,则每次上传都会获得一次功能。

如果要防止这种情况,您将需要一种方法来提前终止函数,方法是检查更改后的文件是否是您要处理的文件,然后不做任何进一步处理就退出该函数。

例如,看看some of the official samples