Reputation: 530
Having a hard time finding some code to do this and I'm actually having trouble myself trying to get this working. I want to create Firebase Function which would call an image URL (this URL has a token associated with it from Mapbox). Then I want to write the image to Firebase Storage so I can reference it from there later to serve it. So far I've figured out how to fetch the image but saving it to storage seems to be too much for me! Help!
exports.getPolylineFromSessionId = functions.https.onRequest(async (req, res) => {
const sessionId = req.query.id;
if (sessionId) {
const sessionInfo = await db
.collection('sessions')
.doc(sessionId)
.get();
const session = sessionInfo.data();
const results = encodeURIComponent(polyline.encode(convertGpsTrack(session.gpsTrack)));
const url =
'https://api.mapbox.com/styles/v1/mapbox/satellite-v9/static/path-1+fff-0.5(' + results + ')/auto/700x200?access_token=' + mapboxToken;
const bucket = admin
.storage()
.bucket('gs://mybucket.appspot.com')
.file('thumbnails/' + sessionId + '.jpg');
const res = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'image/jpeg',
},
});
const blob = await res.blob();
bucket.save(blob, {
metadata: {
contentType: 'image/jpeg',
},
});
res.status(200).send(session);
} else {
res.status(400).send('sessionId required');
}
});
Upvotes: 0
Views: 1299
Reputation: 530
I was able to figure it out finally! Below is the code I used!
var file = admin
.storage()
.bucket('gs://mybucket.appspot.com')
.file('thumbnails/' + sessionId + '.jpg');
request({ url: url, encoding: null }, function(err, response, buffer) {
var stream = file.createWriteStream({
metadata: {
contentType: response.headers['content-type'],
},
});
stream.end(buffer);
});
Upvotes: 4