|
| 1 | +const functions = require('firebase-functions'); |
| 2 | +const cors = require('cors')({ origin: true }); |
| 3 | +const Busboy = require('busboy'); |
| 4 | +const os = require('os'); |
| 5 | +const path = require('path'); |
| 6 | +const fs = require('fs'); |
| 7 | +const uuid = require('uuid/v4'); |
| 8 | + |
| 9 | +const { Storage } = require('@google-cloud/storage'); |
| 10 | + |
| 11 | +const storage = new Storage({ |
| 12 | + projectId: 'ionic-angular-project-a9d42' |
| 13 | +}); |
| 14 | + |
| 15 | +exports.storeImage = functions.https.onRequest((req, res) => { |
| 16 | + return cors(req, res, () => { |
| 17 | + if (req.method !== 'POST') { |
| 18 | + return res.status(500).json({ message: 'Not allowed.' }); |
| 19 | + } |
| 20 | + const busboy = new Busboy({ headers: req.headers }); |
| 21 | + let uploadData; |
| 22 | + let oldImagePath; |
| 23 | + |
| 24 | + busboy.on('file', (fieldname, file, filename, encoding, mimetype) => { |
| 25 | + const filePath = path.join(os.tmpdir(), filename); |
| 26 | + uploadData = { filePath: filePath, type: mimetype, name: filename }; |
| 27 | + file.pipe(fs.createWriteStream(filePath)); |
| 28 | + }); |
| 29 | + |
| 30 | + busboy.on('field', (fieldname, value) => { |
| 31 | + oldImagePath = decodeURIComponent(value); |
| 32 | + }); |
| 33 | + |
| 34 | + busboy.on('finish', () => { |
| 35 | + const id = uuid(); |
| 36 | + let imagePath = 'images/' + id + '-' + uploadData.name; |
| 37 | + if (oldImagePath) { |
| 38 | + imagePath = oldImagePath; |
| 39 | + } |
| 40 | + |
| 41 | + console.log(uploadData.type); |
| 42 | + return storage |
| 43 | + .bucket('ionic-angular-project-a9d42.appspot.com') |
| 44 | + .upload(uploadData.filePath, { |
| 45 | + uploadType: 'media', |
| 46 | + destination: imagePath, |
| 47 | + metadata: { |
| 48 | + metadata: { |
| 49 | + contentType: uploadData.type, |
| 50 | + firebaseStorageDownloadTokens: id |
| 51 | + } |
| 52 | + } |
| 53 | + }) |
| 54 | + |
| 55 | + .then(() => { |
| 56 | + return res.status(201).json({ |
| 57 | + imageUrl: |
| 58 | + 'https://firebasestorage.googleapis.com/v0/b/' + |
| 59 | + storage.bucket('ionic-angular-project-a9d42.appspot.com').name + |
| 60 | + '/o/' + |
| 61 | + encodeURIComponent(imagePath) + |
| 62 | + '?alt=media&token=' + |
| 63 | + id, |
| 64 | + imagePath: imagePath |
| 65 | + }); |
| 66 | + }) |
| 67 | + .catch(error => { |
| 68 | + console.log(error); |
| 69 | + return res.status(401).json({ error: 'Unauthorized!' }); |
| 70 | + }); |
| 71 | + }); |
| 72 | + return busboy.end(req.rawBody); |
| 73 | + }); |
| 74 | +}); |
0 commit comments