2017-08-08 107 views
2

我想在將記錄添加到數據庫時生成拇指圖像。 在火力地堡的網站,他們有一些例子,但它們都是基於存儲觸發的,而不是一個數據庫觸發器:在數據庫觸發的雲功能上獲取Firebase存儲對象

圖片數據庫對象:

image: { 
    name: abc123, 
    raw: download url abc123 
} 

-

火力拇指發生器示例(存儲觸發):

exports.generateThumbnail = functions.storage.object().onChange(event => { 
    const object = event.data; // The Storage object. 

    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. 

    // 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; 
    } 

    // Get the file name. 
    const fileName = path.basename(filePath); 
    // Exit if the image is already a thumbnail. 
    if (fileName.startsWith('thumb_')) { 
    console.log('Already a Thumbnail.'); 
    return; 
    } 

    // Exit if this is a move or deletion event. 
    if (resourceState === 'not_exists') { 
    console.log('This is a deletion event.'); 
    return; 
    } 

    // Exit if file exists but is not new and is only being triggered 
    // because of a metadata change. 
    if (resourceState === 'exists' && metageneration > 1) { 
    console.log('This is a metadata change event.'); 
    return; 
    } 

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

    const metadata = { 
    contentType: contentType 
    }; 
    // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail. 
    const thumbFileName = `thumb_${fileName}`; 
    const thumbFilePath = path.join(path.dirname(filePath), thumbFileName); 
    // Create write stream for uploading thumbnail 
    const thumbnailUploadStream = bucket.file(thumbFilePath).createWriteStream({metadata}); 

    // Create Sharp pipeline for resizing the image and use pipe to read from bucket read stream 
    const pipeline = sharp(); 
    pipeline 
    .resize(THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT) 
    .max() 
    .pipe(thumbnailUploadStream); 

    bucket.file(filePath).createReadStream().pipe(pipeline); 

    const streamAsPromise = new Promise((resolve, reject) => 
    thumbnailUploadStream.on('finish', resolve).on('error', reject)); 
    return streamAsPromise.then(() => { 
    console.log('Thumbnail created successfully'); 
    }); 
}); 

-

我怎麼想它的工作(數據庫觸發):

數據庫觸發事件沒有存儲對象。我如何訪問存儲對象? 當成功創建縮略圖我想補充拇指圖像的donwloadUrl到數據庫

exports.generateThumbnail = functions.database.ref('/data/{dataID}/childData/{childDataID}/image/name').onCreate(event => { 

     const object = event.data; // This Storage object does not work when using a database trigger so how do I access the same storage object, I have the image name? 

     //thumb generator code... 

     return streamAsPromise.then(() => { 
     console.log('Thumbnail created successfully'); 
     //add thumb image download url back to the database 
     }); 
    }); 

-

image: { 
    name: abc123, 
    raw: download url abc123 
    thumb: download url thumb_abc123 //added after thumb is created 
} 

回答

2

這就是我如何運作的。

將雲存儲添加到您的項目中。
如果你想獲取圖像標識的URL像我這樣做,加入專案編號和的KeyFileName你雲存儲參考

const gcs = require('@google-cloud/storage')({ 
    projectId: 'name-1234', 
    keyFilename: './keyfile.json' 
}); 

generateThumbnail功能

exports.generateThumbnail = functions.database.ref('/data/${dataID}/childData/${childDataID/image/name').onCreate(image => { 

    const dataID = image.params.dataID 
    const childDataID = image.params.childDataID 
    const fileName = image.data.val() 

    //get your project storage bucket id 
    const storageBucket = functions.config().firebase.storageBucket 
    //path to image 
    const imagePath = `${dataID}/${childDataID}` 
    //open bucket 
    const bucket = gcs.bucket(storageBucket) 
    //location of the image in the bucket 
    const object = bucket.file(imagePath) 

    const fileBucket = object.bucket; // The Storage bucket that contains the file. 
    const filePath = object.name; // File path in the bucket. 

    const metadata = { 
    contentType: 'image/jpeg' 
    }; 

    // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail. 
    const thumbFileName = `thumb_${fileName}`; 
    const thumbFilePath = path.join(path.dirname(filePath), thumbFileName); 
    // Create write stream for uploading thumbnail 
    const thumbnailUploadStream = bucket.file(thumbFilePath).createWriteStream({metadata}); 

    // Create Sharp pipeline for resizing the image and use pipe to read from bucket read stream 
    const pipeline = sharp(); 
    pipeline 
    .resize(400, 400) 
    .max() 
    .pipe(thumbnailUploadStream); 


    bucket.file(filePath).createReadStream().pipe(pipeline); 

    const streamAsPromise = new Promise((resolve, reject) => 
    thumbnailUploadStream.on('finish', resolve).on('error', reject)); 

    return streamAsPromise.then(() => { 
    console.log('Thumbnail created successfully'); 

    var today = new Date(); 
    var dd = today.getDate(); 
    var mm = today.getMonth() + 1; //January is 0! 
    const yyyy = today.getFullYear() + 5; // add a few years 

    if (dd < 10) { 
     dd = '0' + dd 
    } 

    if (mm < 10) { 
     mm = '0' + mm 
    } 

    today = mm + '-' + dd + '-' + yyyy; 

    bucket.file(filePath).getSignedUrl({ 
     action: 'read', 
     expires: today 
    }, function(err, url) { 
     if (err) { 
     console.error(err); 
     return; 
     } 
     //add thumb image url to message (in database) 
     return admin.database().ref(`/${dataID}/childData/${childDataID}`).child('image').update({ 
     thumb: url 
     }) 
    }); 
    }); 
}) 
0

當一個事件在數據庫中觸發創建存儲參考圖像和處理它。 這裏是docs如何創建一個參考。 https://firebase.google.com/docs/storage/web/create-reference

+0

糾正我,如果我錯了,但參考鏈接您提供的是用於在網站/ Web應用程序中創建存儲參考的文檔。我正在尋找一種方法來在Firebase函數中創建存儲引用。 – user1242574

+0

這是一樣的,你可以使用它在firebase雲功能。 functions.storage()。ref()。child('images/space.jpg') –

+0

你能告訴我如何在firebase上傳一個帶有云功能的圖像 –

相關問題